Skip to content

Commit 524f547

Browse files
committed
FX converter doc
1 parent e7f4752 commit 524f547

File tree

1 file changed

+188
-0
lines changed

1 file changed

+188
-0
lines changed

docsrc/contributors/fx_converters.rst

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
.. _conversion:
2+
3+
FX Converters
4+
==================
5+
The converter library in Torch-TensorRT is located in ``TensorRT/py/torch_tensorrt/fx/converters``.
6+
They are categorized into - ``aten_ops_converters``, ``acc_ops_converters`` and ``nn_ops_converters``.
7+
The individual converters present are useful for the quantization workflow.
8+
The converters are registered using the ``tensorrt_converter``.
9+
10+
Steps
11+
==================
12+
13+
Operation Sets
14+
-------------------
15+
There are three different converter sets for FX in torch_tensorrt. Depending on whether the operation is generated using acc_trace, aten_trace or fx_trace, the converters are categorized to one of the three operation sets -
16+
``aten_ops_converters``, ``acc_ops_converters`` or ``nn_ops_converters``. The converters are registered using ``tensorrt_converter`` decorator. The function decorated
17+
has the arguments - ``network, target, args, kwargs, name``, which is common across all the operators schema.
18+
These functions are mapped in the ``aten`` converter registry dictionary (at present a compilation of FX and dynamo converters, FX will be deprecated soon), with key as the function target name.
19+
20+
* acc_ops_converters
21+
* acc_trace is produced by ``torch_tensorrt.fx.tracer.acc_tracer.acc_tracer.trace``.
22+
* aten_ops
23+
There are two options at present for this
24+
#. Dynamo: aten_trace is produced by ``torch_tensorrt.dynamo.backend.compile``. The second round of trace is produced by ``aot_torch_tensorrt_aten_backend`` by invoking ``aot_module_simplified`` from ``torch._functorch.aot_autograd``
25+
#. FX: aten_trace is produced by ``torch_tensorrt.fx.tracer.dispatch_tracer.aten_tracer.trace``. This flow is more common currently, but this will soon be deprecated in torch_tensorrt.
26+
* nn_ops
27+
* symbolic_trace is produced by ``torch.fx._symbolic_trace``.
28+
29+
The implementation of the above converter set is to be included in the common implementation library present in ``TensorRT/py/torch_tensorrt/fx/impl``.
30+
This documentation focuses on the implementation of the ``aten_ops`` converters. There might be some steps involved in reorganizing files for ``acc_ops`` converters. This is discussed in more detail in the next section.
31+
32+
Converter implementation
33+
------------------------
34+
In this section, we illustrate the steps to be implemented for writing a converter. We divide them according to activation, operator or lowering pass implementation.
35+
Each of them is detailed with the help of an example
36+
37+
* Registration
38+
39+
The converter needs to be registered with the appropriate op code in the ``tensorrt_converter``.
40+
41+
* Activation
42+
43+
Example: ``leaky_relu``
44+
45+
* acc_ops_converters
46+
47+
Define in ``py/torch_tensorrt/fx/converters/acc_ops_converters``. One needs to register the opcode generated in the trace, with ``tensorrt_converter`` decorator. Op code to be used for the registration or the converter registry key in this case is ``acc_ops.leaky_relu``
48+
49+
.. code-block:: python
50+
51+
@tensorrt_converter(acc_ops.leaky_relu)
52+
def acc_ops_leaky_relu(
53+
network: TRTNetwork,
54+
target: Target,
55+
args: Tuple[Argument, ...],
56+
kwargs: Dict[str, Argument],
57+
name: str,
58+
) -> Union[TRTTensor, Sequence[TRTTensor]]:
59+
input_val = kwargs["input"]
60+
negative_slope = kwargs["negative_slope"]
61+
operation_type = trt.ActivationType.LEAKY_RELU
62+
return activation.leaky_relu(
63+
network, target, SourceIR.ACC, name, kwargs["input"], kwargs["negative_slope"]
64+
)
65+
66+
* aten_ops_converters
67+
68+
Define in ``py/torch_tensorrt/fx/converters/aten_ops_converters``. One needs to register the opcode generated in the trace with ``tensorrt_converter`` decorator. Op code to be used for the registration or the converter registry key in this case is ``torch.ops.aten.leaky_relu.default``
69+
70+
.. code-block:: python
71+
72+
@tensorrt_converter(torch.ops.aten.leaky_relu.default)
73+
def aten_ops_leaky_relu(
74+
network: TRTNetwork,
75+
target: Target,
76+
args: Tuple[Argument, ...],
77+
kwargs: Dict[str, Argument],
78+
name: str,
79+
) -> Union[TRTTensor, Sequence[TRTTensor]]:
80+
return activation.leaky_relu(network, target, SourceIR.ATEN, name, args[0], args[1])
81+
82+
The function decorated by ``tensorrt_converter`` has the following arguments which are automatically generated by the trace functions mentioned above.
83+
84+
#. network : Node in the form of ``call_module`` or ``call_function`` having the target as the key
85+
#. target: Target key in the ``call_module`` or ``call_function`` above. eg: ``torch.ops.aten_.leaky_relu.default``
86+
#. args: The arguments passed in the ``call_module`` or ``call_function`` above
87+
#. kwargs: The kwargs passed in the ``call_module`` or ``call_function`` above
88+
#. name: String containing the name of the target
89+
90+
As a user writing new converters, one just needs to take care that the approriate arguments are extracted from the trace generated to the implementation function in the implementation lib function ``activation.leaky_relu`` (which we will discuss below in detail). As one can see in the example above, the trace for ``acc_op`` and ``aten_op`` is different.
91+
``Acc_ops`` has arguments in the ``args`` whereas ``aten_ops`` has arguments in the ``kwargs`` in the trace.
92+
93+
94+
* Operation type
95+
96+
Example: ``fmod``
97+
98+
It follows the same steps as the above converter. In this case the opcode is ``torch.ops.aten.fmod.Scalar`` or ``torch.ops.aten.fmod.Tensor``.
99+
Hence both the opcodes are registered in ``py/torch_tensorrt/fx/converters/aten_ops_converters``. The opcode is ``acc_ops.fmod`` in ``py/torch_tensorrt/fx/converters/acc_ops_converters``.
100+
101+
102+
* Implementation Library
103+
104+
The converters across all the above three opsets have the common implementation library ``py/torch_tensorrt/fx/converters/impl``
105+
106+
* Activation
107+
108+
Example: ``leaky_relu``
109+
110+
The implementation is to be placed in present in ``py/torch_tensorrt/fx/impl/activation.py``. This is where all the activation functions are defined and implemented.
111+
112+
.. code-block:: python
113+
114+
def leaky_relu(
115+
network: TRTNetwork,
116+
target: Target,
117+
source_ir: Optional[SourceIR],
118+
name: str,
119+
input_val: TRTTensor,
120+
alpha: Optional[Any],
121+
):
122+
#implementation
123+
124+
The implementation function has the following arguments.
125+
126+
#. network : ``network`` passed from the decorated function registration
127+
#. target: ``target`` passed from the decorated function registration
128+
#. source_ir: Enum attribute. ``SourceIR`` enum is defined in ``py/torch_tensorrt/fx/converters/impl/converter_utils``
129+
#. name: ``name`` passed from the decorated function registration
130+
#. input_val: Approriate arguments extracted from the decorated function registration from args or kwargs
131+
#. alpha: Approriate arguments extracted from the decorated function registration from args or kwargs. If not None, it will set the alpha attribute of the created TensorRT activation layer eg: Used in leaky_relu, elu, hardtanh
132+
#. beta: Approriate arguments extracted from the decorated function registration from args or kwargs. If not None, it will set the beta attribute of the created TensorRT activation layer eg: Used in hardtanh
133+
#. dyn_range_fn: A optional function which takes the dynamic range of a TensorRT Tensor and returns the output dynamic range
134+
135+
The implementation functions call the ``convert_activation`` function in ``py/torch_tensorrt/fx/impl/activation.py``. This function will add the approriate activation layer via ``network.add_activation``.
136+
137+
* Operator
138+
139+
The implementation is to be placed in ``py/torch_tensorrt/fx/impl/elementwise/ops.py``. This is where all the elementwise functions are defined and implemented.
140+
For a new operator, one should identify the category to which it belongs. Following are some examples
141+
142+
#. Elementwise operators like ``fmod`` is present in ``py/torch_tensorrt/fx/impl/elementwise``. The ``py/torch_tensorrt/fx/impl/elementwise/base`` contains base functions for elementwise operator.
143+
#. Unary operators like ``sqrt`` will be present in ``py/torch_tensorrt/fx/impl/unary``. The ``py/torch_tensorrt/fx/impl/unary/base`` contains base functions for unary operator.
144+
#. Normalization operators like ``softmax``, ``layer_norm``, ``batch_norm`` will be present in ``py/torch_tensorrt/fx/impl/normalization``. Since there are no base operations common to all, there is no base file. But one can choose to implement a base file, if there are common functions across all normalization operations
145+
#. Individual operators like ``slice``, ``select``, ``where``, ``embedding`` will be present in ``py/torch_tensorrt/fx/impl/*.py``. They will have individual operator implementation with the same API structure as above but with different individual arguments
146+
147+
Please note that the above operators would have common functions to be implemented which should be placed in
148+
``py/torch_tensorrt/fx/impl/converter_utils.py``
149+
150+
151+
* Lowering type
152+
153+
There are some converters which can be decomposed into suboperations and need not have seperate converter registration.
154+
Such converters can be implemented via ``lowering passes``
155+
156+
Example: ``addmm``
157+
158+
The decompositions are registered via ``register_decomposition`` in ``py/torch_tensorrt/dynamo/backend/lowering/_decompositions.py``
159+
We define ``addmm_replacement`` and replace it with the torch ops, which will have their corresponding converters called.
160+
161+
.. code-block:: python
162+
163+
@register_decomposition(torch.ops.aten.addmm, registry=DECOMPOSITIONS)
164+
def addmm_replacement(
165+
input_: torch.Tensor, mat1: torch.Tensor, mat2: torch.Tensor, *, beta=1, alpha=1
166+
) -> torch.Tensor:
167+
return torch.add(
168+
torch.mul(input_, beta), torch.mul(torch.matmul(mat1, mat2), alpha)
169+
)
170+
171+
172+
173+
Tests
174+
----------------
175+
176+
* FX testing: Implement the fx tests in ``py/torch_tensorrt/fx/test/converters/aten_op/test_<operator_name>_aten.py``. Derive the test class from ``DispatchTestCase``, with parameterized testing to implement different test cases. Check for the following two conditions
177+
#. Compare the results for ``dispatch_tracer.aten_trace`` and torch.
178+
#. Test the ``expected_op``. You can find examples in the above tests. This op will be called by the model and needs to be specified in the test so that the test checks that the approriate converter is invoked
179+
180+
The tests should fail if any of the above two conditions fail
181+
182+
* Dynamo testing: Dynamo tests are present for the lowering ops in ``py/torch_tensorrt/dynamo/backend/test/test_decompositions.py``. The above converters will soon be ported to dynamo tests
183+
#. Compare the results for ``fx.symbolic_trace `` and ``torch_tensorrt.dynamo.compile``
184+
#. The tests also test for the ``expected_op`` and the ``unexpected_op``.
185+
* ``expected_op``: Operations the operations are lowered to. eg: ``mul`` and ``add`` for ``addmm``
186+
* ``unexpected_op``: Original operation. eg: ``addmm`` for ``addmm``
187+
188+
The tests should fail if any of the above two conditions fail

0 commit comments

Comments
 (0)