.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "prototype/numeric_suite_tutorial.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_prototype_numeric_suite_tutorial.py: PyTorch Numeric Suite Tutorial ============================== Introduction ------------ Quantization is good when it works, but it’s difficult to know what's wrong when it doesn't satisfy the accuracy we expect. Debugging the accuracy issue of quantization is not easy and time consuming. One important step of debugging is to measure the statistics of the float model and its corresponding quantized model to know where are they differ most. We built a suite of numeric tools called PyTorch Numeric Suite in PyTorch quantization to enable the measurement of the statistics between quantized module and float module to support quantization debugging efforts. Even for the quantized model with good accuracy, PyTorch Numeric Suite can still be used as the profiling tool to better understand the quantization error within the model and provide the guidance for further optimization. PyTorch Numeric Suite currently supports models quantized through both static quantization and dynamic quantization with unified APIs. In this tutorial we will first use ResNet18 as an example to show how to use PyTorch Numeric Suite to measure the statistics between static quantized model and float model in eager mode. Then we will use LSTM based sequence model as an example to show the usage of PyTorch Numeric Suite for dynamic quantized model. Numeric Suite for Static Quantization ------------------------------------- Setup ^^^^^^ We’ll start by doing the necessary imports: .. GENERATED FROM PYTHON SOURCE LINES 43-44 Then we load the pretrained float ResNet18 model, and quantize it into qmodel. We cannot compare two arbitrary models, only a float model and the quantized model derived from it can be compared. .. GENERATED FROM PYTHON SOURCE LINES 55-61 1. Compare the weights of float and quantized models ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The first thing we usually want to compare are the weights of quantized model and float model. We can call ``compare_weights()`` from PyTorch Numeric Suite to get a dictionary ``wt_compare_dict`` with key corresponding to module names and each entry is a dictionary with two keys 'float' and 'quantized', containing the float and quantized weights. ``compare_weights()`` takes in floating point and quantized state dict and returns a dict, with keys corresponding to the floating point weights and values being a dictionary of floating point and quantized weights .. GENERATED FROM PYTHON SOURCE LINES 74-78 Once get ``wt_compare_dict``, users can process this dictionary in whatever way they want. Here as an example we compute the quantization error of the weights of float and quantized models as following. Compute the Signal-to-Quantization-Noise Ratio (SQNR) of the quantized tensor ``y``. The SQNR reflects the relationship between the maximum nominal signal strength and the quantization error introduced in the quantization. Higher SQNR corresponds to lower quantization error. .. GENERATED FROM PYTHON SOURCE LINES 88-89 As another example ``wt_compare_dict`` can also be used to plot the histogram of the weights of floating point and quantized models. .. GENERATED FROM PYTHON SOURCE LINES 105-113 2. Compare float point and quantized models at corresponding locations ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The second tool allows for comparison of weights and activations between float and quantized models at corresponding locations for the same input as shown in the figure below. Red arrows indicate the locations of the comparison. .. figure:: /_static/img/compare_output.png We call ``compare_model_outputs()`` from PyTorch Numeric Suite to get the activations in float model and quantized model at corresponding locations for the given input data. This API returns a dict with module names being keys. Each entry is itself a dict with two keys 'float' and 'quantized' containing the activations. .. GENERATED FROM PYTHON SOURCE LINES 114-129 .. code-block:: default # Take in floating point and quantized model as well as input data, and returns a dict, with keys # corresponding to the quantized module names and each entry being a dictionary with two keys 'float' and # 'quantized', containing the activations of floating point and quantized model at matching locations. .. GENERATED FROM PYTHON SOURCE LINES 130-131 This dict can be used to compare and compute the quantization error of the activations of float and quantized models as following. .. GENERATED FROM PYTHON SOURCE LINES 135-139 If we want to do the comparison for more than one input data, we can do the following. Prepare the model by attaching the logger to both floating point module and quantized module if they are in the ``white_list``. Default logger is ``OutputLogger``, and default white_list is ``DEFAULT_NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_WHITE_LIST`` .. GENERATED FROM PYTHON SOURCE LINES 139-151 .. code-block:: default # Find the matching activation between floating point and quantized modules, and return a dict with key # corresponding to quantized module names and each entry being a dictionary with two keys 'float' # and 'quantized', containing the matching floating point and quantized activations logged by the logger .. GENERATED FROM PYTHON SOURCE LINES 152-153 The default logger used in above APIs is ``OutputLogger``, which is used to log the outputs of the modules. We can inherit from base ``Logger`` class and create our own logger to perform different functionalities. For example we can make a new ``MyOutputLogger`` class as below. .. GENERATED FROM PYTHON SOURCE LINES 167-168 And then we can pass this logger into above APIs such as: .. GENERATED FROM PYTHON SOURCE LINES 173-174 or: .. GENERATED FROM PYTHON SOURCE LINES 184-200 3. Compare a module in a quantized model with its float point equivalent, with the same input data ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The third tool allows for comparing a quantized module in a model with its float point counterpart, feeding both of them the same input and comparing their outputs as shown below. .. figure:: /_static/img/compare_stub.png In practice we call prepare_model_with_stubs() to swap the quantized module that we want to compare with the Shadow module, which is illustrated as below: .. figure:: /_static/img/shadow.png The Shadow module takes quantized module, float module and logger as input, and creates a forward path inside to make the float module to shadow quantized module sharing the same input tensor. The logger can be customizable, default logger is ``ShadowLogger`` and it will save the outputs of the quantized module and float module that can be used to compute the module level quantization error. Notice before each call of ``compare_model_outputs()`` and ``compare_model_stub()`` we need to have clean float and quantized model. This is because ``compare_model_outputs()`` and ``compare_model_stub()`` modify float and quantized model inplace, and it will cause unexpected results if call one right after another. .. GENERATED FROM PYTHON SOURCE LINES 211-212 In the following example we call ``compare_model_stub()`` from PyTorch Numeric Suite to compare ``QuantizableBasicBlock`` module with its float point equivalent. This API returns a dict with key corresponding to module names and each entry being a dictionary with two keys 'float' and 'quantized', containing the output tensors of quantized and its matching float shadow module. .. GENERATED FROM PYTHON SOURCE LINES 212-229 .. code-block:: default # Takes in floating point and quantized model as well as input data, and returns a dict with key # corresponding to module names and each entry being a dictionary with two keys 'float' and # 'quantized', containing the output tensors of quantized module and its matching floating point shadow module. .. GENERATED FROM PYTHON SOURCE LINES 230-231 This dict can be then used to compare and compute the module level quantization error. .. GENERATED FROM PYTHON SOURCE LINES 236-237 If we want to do the comparison for more than one input data, we can do the following. .. GENERATED FROM PYTHON SOURCE LINES 244-245 The default logger used in above APIs is ``ShadowLogger``, which is used to log the outputs of the quantized module and its matching float shadow module. We can inherit from base ``Logger`` class and create our own logger to perform different functionalities. For example we can make a new ``MyShadowLogger`` class as below. .. GENERATED FROM PYTHON SOURCE LINES 259-260 And then we can pass this logger into above APIs such as: .. GENERATED FROM PYTHON SOURCE LINES 265-266 or: .. GENERATED FROM PYTHON SOURCE LINES 273-278 Numeric Suite for Dynamic Quantization -------------------------------------- Numeric Suite APIs are designed in such as way that they work for both dynamic quantized model and static quantized model. We will use a model with both LSTM and Linear modules to demonstrate the usage of Numeric Suite on dynamic quantized model. This model is the same one used in the tutorial of dynamic quantization on LSTM word language model [1]. .. GENERATED FROM PYTHON SOURCE LINES 280-283 Setup ^^^^^^ First we define the model as below. Notice that within this model only ``nn.LSTM`` and ``nn.Linear`` modules will be quantized dynamically and ``nn.Embedding`` will remain as floating point module after quantization. .. GENERATED FROM PYTHON SOURCE LINES 316-317 Then we create the ``float_model`` and quantize it into qmodel. .. GENERATED FROM PYTHON SOURCE LINES 334-338 1. Compare the weights of float and quantized models ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We first call ``compare_weights()`` from PyTorch Numeric Suite to get a dictionary ``wt_compare_dict`` with key corresponding to module names and each entry is a dictionary with two keys 'float' and 'quantized', containing the float and quantized weights. .. GENERATED FROM PYTHON SOURCE LINES 343-344 Once we get ``wt_compare_dict``, it can be used to compare and compute the quantization error of the weights of float and quantized models as following. .. GENERATED FROM PYTHON SOURCE LINES 352-358 The Inf value in ``encoder.weight`` entry above is because encoder module is not quantized and the weights are the same in both floating point and quantized models. 2. Compare float point and quantized models at corresponding locations ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Then we call ``compare_model_outputs()`` from PyTorch Numeric Suite to get the activations in float model and quantized model at corresponding locations for the given input data. This API returns a dict with module names being keys. Each entry is itself a dict with two keys 'float' and 'quantized' containing the activations. Notice that this sequence model has two inputs, and we can pass both inputs into ``compare_model_outputs()`` and ``compare_model_stub()``. .. GENERATED FROM PYTHON SOURCE LINES 368-369 This dict can be used to compare and compute the quantization error of the activations of float and quantized models as following. The LSTM module in this model has two outputs, in this example we compute the error of the first output. .. GENERATED FROM PYTHON SOURCE LINES 375-381 3. Compare a module in a quantized model with its float point equivalent, with the same input data ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Next we call ``compare_model_stub()`` from PyTorch Numeric Suite to compare LSTM and Linear module with its float point equivalent. This API returns a dict with key corresponding to module names and each entry being a dictionary with two keys 'float' and 'quantized', containing the output tensors of quantized and its matching float shadow module. We reset the model first. .. GENERATED FROM PYTHON SOURCE LINES 397-398 Next we call ``compare_model_stub()`` from PyTorch Numeric Suite to compare LSTM and Linear module with its float point equivalent. This API returns a dict with key corresponding to module names and each entry being a dictionary with two keys 'float' and 'quantized', containing the output tensors of quantized and its matching float shadow module. .. GENERATED FROM PYTHON SOURCE LINES 404-405 This dict can be then used to compare and compute the module level quantization error. .. GENERATED FROM PYTHON SOURCE LINES 410-421 SQNR of 40 dB is high and this is a situation where we have very good numerical alignment between the floating point and quantized model. Conclusion ---------- In this tutorial, we demonstrated how to use PyTorch Numeric Suite to measure and compare the statistics between quantized model and float model in eager mode with unified APIs for both static quantization and dynamic quantization. Thanks for reading! As always, we welcome any feedback, so please create an issue `here `_ if you have any. References ---------- [1] `DYNAMIC QUANTIZATION ON AN LSTM WORD LANGUAGE MODEL `_. .. GENERATED FROM PYTHON SOURCE LINES 421-422 .. code-block:: default # %%%%%%RUNNABLE_CODE_REMOVED%%%%%% .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.001 seconds) .. _sphx_glr_download_prototype_numeric_suite_tutorial.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: numeric_suite_tutorial.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: numeric_suite_tutorial.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_