Optimization

Optimization

The optimum.fx.optimization module provides a set of torch.fx graph transformations, along with classes and functions to write your own transformations and compose them.

The transformation guide

In 🌍 Optimum, there are two kinds of transformations: reversible and non-reversible transformations.

Write a non-reversible transformation

The most basic case of transformations is non-reversible transformations. Those transformations cannot be reversed, meaning that after applying them to a graph module, there is no way to get the original model back. To implement such transformations in 🌍 Optimum, it is very easy: you just need to subclass Transformationarrow-up-right and implement the transform()arrow-up-right method.

For instance, the following transformation changes all the multiplications to additions:

Copied

>>> import operator
>>> from optimum.fx.optimization import Transformation

>>> class ChangeMulToAdd(Transformation):
...     def transform(self, graph_module):
...         for node in graph_module.graph.nodes:
...             if node.op == "call_function" and node.target == operator.mul:
...                 node.target = operator.add
...         return graph_module

After implementing it, your transformation can be used as a regular function:

Copied

Write a reversible transformation

A reversible transformation implements both the transformation and its reverse, allowing to retrieve the original model from the transformed one. To implement such transformation, you need to subclass ReversibleTransformationarrow-up-right and implement the transform()arrow-up-right and reverse()arrow-up-right methods.

For instance, the following transformation is reversible:

Copied

Composing transformations together

As applying multiple transformations in chain is needed more often that not, compose()arrow-up-right is provided. It is an utility function that allows you to create a transformation by chaining multiple other transformations.

Copied

Last updated