FX Quantization Principle
Before reading this section, it is recommended to read the torch.fx — PyTorch documentation to get an initial understanding of torch's FX mechanism.
FX uses the symbolic execution approach, which allows models to be graphically constructed at the nn.Module or function level, allowing for automated fuse and other graph-based optimizations.
Quantized Process
Fuse (Optional)
FX can sense the computational graph, so you can automate the fusion of operators. You no longer need to manually specify the operators to be fused, just call the interface directly.
- Note that there is no
inplaceparameter forfuse_fx, because internally you need to do symbolic trace on the model to generate aGraphModule, so you can't do inplace modification. - The
fused_modelandmodelwill share almost all attributes (including submodules, operators, etc.), so do not make any changes to themodelafter fuse, as this may affect thefused_model. - It is not necessary to explicitly call the
fuse_fxinterface, as the subsequentprepareinterface integrates the fuse procedure internally.
Prepare
The global march must be set according to the target hardware platform before calling the prepare interface, which internally performs a fuse procedure (even if the model has already been fused) and then replaces the eligible operators in the model with implementations from horizon.nn.qat.
- You can choose the appropriate qconfig (Calibtaion or QAT, note that you can't mix the two qconfigs) if you want.
- Similar to
fuse_fx, this interface does not support theinplaceparameter, and please do not make any changes to the input model afterprepare.
Eager Mode Compatibility
In most cases, FX quantized interfaces can directly replace eager mode quantized interfaces, but they cannot be mixed with eager mode interfaces. Some models require some modifications to the code structure in the following cases.
- Operations not supported by FX: the symbolic trace of torch supports limited operations, e.g., it does not support non-static variables as judgment conditions, it does not support pkgs (e.g., numpy) other than torch by default, etc., and unexecuted conditional branches will be discarded.
- Operations that don't want to be processed by FX: If torch's ops are used in the model's pre- and post-processing, FX will treat them as part of the model when tracing, producing undesired behavior (e.g., replacing some of torch's function calls with FloatFunctional).
Both of these cases can be avoided by using wrap, as illustrated by RetinaNet.
