Advanced quantization

This guide covers advanced ONNX quantization workflows for:

  • improving quality metrics of quantized models

  • 4-bits and 16-bits quantization

  • designing mixed precision models

  • investigation of quantization issues

  • creating an efficient calibration dataset

Preliminary definitions:

  • quality metric: respectively accuracy in IC, mAp in OD. The definition will be extended in time as other use-cases benefit from the advanced operating modes described herafter.

  • w4a4: quantization set-up where all weights and all activations are quantized in 4-bits

  • w8a8: all weights and all activations are quantized in 8-bits

  • w8a16: all weights are quantized in 8-bits and all activations are quantized in 16-bits

1. Yaml configuration parameters

The description provided in this readme assume that we use ONNX quantizer and not LiteRT.

The following applies with ONNX quantizer only and not LiteRT. Therefore, quantization.quantizer must be set to Onnx_quantizer. If quantization.operating_mode is not defined or is set to default, we simply execute quantization with the yaml specified parameters.

The quantization section has the following sub-sections:

quantization.onnx_quant_parameters:  
      
      weight_type: Int8 (default), other possible values are Int4, UInt4, Int8, UInt8, Int16, UInt16. Note that 4-bits and 16-bits are only supported if `quantization.target_opset` >= 21.
      
      activ_type: Int8 (default), other possible values are Int4, UInt4, Int8, UInt8, Int16, UInt16. Note that 4-bits and 16-bits are only supported if `quantization.target_opset` >= 21.
      
      calibrate_method: MinMax (default), activations calibration methods supported are MinMax, Entropy and Percentile.

      ChannelZeroingThreshold: 1e-7 (default), threshold for zeroing channels during quantization if they are below this value. Only applicable for external quantization, that is AMD-quark. This zeroing helps to prevent bias saturation during quantization.
      
      op_types_to_quantize: None (default), types of operators to quantize, like [`Conv`] to quantize Conv only. It quantizes all supported operators by default.
      
      nodes_to_quantize: None (default), nodes names to quantize. When this list is not None only the nodes in this list are quantized. For example, [`Conv__224`, `Conv__252`].
      
      nodes_to_exclude: None (default), the nodes in this list will be excluded from quantization.      
      
      AdaQuant: False (default), if True execute AdaQuant (from AMD-quark).      
      
      Qmn: False (default), if True execute Qmn quantization on weights and activation (from AMD-quark).
      
quantization.onnx_extra_options:

      WeightSymmetric: True (default), symmetric weight quantization if True else assymetric

      ActivationSymmetric: False (default), symmetric activation quantization if True else assymetric

      QuantizeBias: True (default), if True biases are quantized in Int32, else they are kept in floating point

      CalibMovingAverage: False (default), if True, the moving average of the activations minimum and maximum values is computed when the calibration method is MinMax.
      
      weights_tensor_override: None (default), specifies specific weight tensor quantization settings such as bit-width for example, see [Tensor Override](#5) section for more details

      activations_tensor_override: None (default), specifies specific activation tensor quantization settings such as bit-width for example, see [Tensor Override](#5) section for more details

quantization.iterative_quant_parameters: # only used if `quantization.operating_mode` is `inspection`, `full_auto_w4w8a8` or `full_auto_w8a8a16`
      
      inspection_split: 1.0 (default), float value in the range ]0...1]. Take a split of the quantization dataset to inspect tensor SNR
      
      accuracy_tolerance: float value in the range [0...100]. Quality metric margin we tolerate in percent relatively to w8a8 performance in `full_auto_w4w8a8` or relatively to w8a16 in `full_auto_w8a8a16`. It is mandatory to specify this parameter in these 2 operating modes.

quantization.calib_dataset_search_parameters: # only used if `quantization.operating_mode` is `calib_dataset_search`
      
      flex_parameters: default value is False, mandatory to set it to True or False when `quantization.operating_mode` ==  `calib_dataset_search`. Specify type of search to be executed: standard (False) or permissive (True).

      created_dataset_path: no default value, mandatory to set a path to a directory to store selected input samples when `quantization.operating_mode` == `calib_dataset_search` 

3. Various Operating Modes

Various operating modes are available. The operating mode is defined under the quantization section by the quantization.operating_mode field. It is different from the top level parameter operation_mode. quantization.operating_mode can be set to: calib_dataset_search, full_auto_w4w8a8, full_auto_w8a8a16 or inspection. Please, note that calib_dataset_search can only be used when operation_mode is quantization.

3.2 Operating mode: full_auto_w4w8a8

The goal of this mode is to automatically search for which weight tensors could be quantized in 4 bits or must remain in 8 bits taken into account a quality metric degradation budget of quantization.iterative_quant_parameters.accuracy_tolerance defined in percent with respect to full 8 bits. Activations are kept in 8 bits and biases in 32 bits in any case. It is clear that the better the weight quantizer the higher the number of weights tensors could be moved to 4-bits. However this algorithm can also be run with the basic MinMax quantization algorithm embedded into ONNX. Several steps are sequentially performed:

  1. Compute float model quality metric for reference
  2. Perform a first quantization with parameters in the yaml. This provides a quantized reference quality metric typically W8A8
  3. Perform a second quantization with 4 bits for all weights: gives an idea how much it degrades
  4. Rank the weight tensors with respect to a composite score involving some network properties like total number of weigths and number of weights per output channels.
  5. Based on the ranking, search which weights can stay in 4 bits and which ones should be on 8 bits

The score computation does not require any training step. It is done statically based on network properties. Among these parameters, we can mention (not restrictive):

  • layer type (conv2D, point-wise, depthwise, dense…)

  • kernel size (2x2, 3x3…)

  • total number of weights

  • number of weights associated to each output channel

Once the ranking is done, we start the search which is iterative, by dichotomy. Lower ranking tensors are first candidates for a quantization on 8 bits. We report the model with the minimum number of layer weights on 8 bits whose quality metric is not worse than iterative_quant_parameters.accuracy_tolerance compared to full 8 bits.

When running full_auto_w4w8a8, and search for which weights could be quantized just on 4 bits, the code itself overrides quantization.onnx_quant_parameters.weight_type and quantization.onnx_quant_parameters.activ_type and internally set them to the appropriate values. However, all the other parameters are to be set carefully.

In terms of restrictions, as already mentionned, full_auto_w4w8a8 requires setting quantization.onnx_quant_parameters.AdaQuant to False and quantization.onnx_quant_parameters.Qmn to False too. In addition quantization.onnx_extra_options.weights_tensor_override and quantization.onnx_extra_options.activations_tensor_override should be left to None, since not managed in the search loop of full_auto_w4w8a8.

To finish, we recommend not to define onnx_quant_parameters.op_types_to_quantize, onnx_quant_parameters.nodes_to_quantize and onnx_quant_parameters.nodes_to_exclude in this operating mode: this will give a chance to the algorithm to explore more combinations.

3.3 Operating mode: full_auto_w8a8a16

The goal of this mode is to automatically search for which activation tensors must be quantized in 16-bits or should remain in 8-bits taken into account a quality metric degradation budget of quantization.iterative_quant_parameters.accuracy_tolerance defined in percent with respect to the minimum metric quality between w8a16 and float models. Weights are kept in 8 bits and biases in 32 bits in any case. It is clear that the better the activation quantizer the higher the number of activation tensors could be kept in 8-bits. However this algorithm can also be run with the basic MinMax quantization algorithm embedded into ONNX. Several steps are sequentially performed:

  1. Compute float model quality metric (example: accuracy...) for reference
  2. Perform a first quantization w8a8 with parameters in the yaml.
  3. Perform a second quantization in w8a16: check the quality metric and compare it to the floating point reference
  4. Compute a criteria/score for each activation tensor. Rank them.
  5. Based on the ranking, search which activations should be kept in 8 bits and which activations must be passed on 16 bits

The score computation does not require any training step. It is done statically based on activations SNR comparison in 8-bits and in 16-bits. In this SNR calculation performed by ONNX runtime functions, the noise or the error is mean square error between quantized tensor and float tensor. It is evaluated on a so-called inspection dataset, a subset of inputs used for activation calibration that is a random split of the quantization dataset. The size of this inspection dataset is controlled by quantization.iterative_quant_parameters.inspection_split. A few dozens of inputs are enough in most cases.

In a few words, the following 3 step ranking procedure provides an ordered tensor list that is later used as input of the search loop:

  1. First position in the list belongs to the output tensor, whatever its SNR improvement when passing in 16-bits. Output tensor (directly linked to the output quality) seems to be sensitive in particular when AdaQuant is used. In addition, it is of limited size compared to intermediate feature maps. Passing the output tensor in 16-bits is an easy attempt to increase the quality metric at low cost in terms of memory. This heuristic is often relevant.

  2. Next positions in the list should be occupied by Depthwise output tensors, ranked from the highest SNR criteria value to the lowest. It is known that Depthwises are sensitive to quantization. Their output channels may have higher variance even when the batch normalization layer parameters have been folded into their weights and biases. They are likely to benefit more from 16-bits output tensor quantization.
  
  3. The remaining positions in the list are occupied by all the other layers ranked in decreasing order of SNR criteria, without any other heuristics.

Once the ranking is done, we start the search which is iterative, by dichotomy. Lower indexes in the ranked list are first candidates for a quantization on 16-bits. We report the model with the minimum number of activation tensors on 16-bits whose quality metric is greater than: min(metric quality full w8/full a16, metric quality float) - iterative_quant_parameters.accuracy_tolerance.

When running full_auto_w8a8a16, and search for which activation tensors should be quantized on 16-bits, the code itself overrides quantization.onnx_quant_parameters.weight_type and quantization.onnx_quant_parameters.activ_type and internally set them to the appropriate values. However, all the other parameters are to be set carefully. At the contrary to full_auto_w4w8a8, full_auto_w8a8a16 can be used with quantization.onnx_quant_parameters.AdaQuant to True and quantization.onnx_quant_parameters.Qmn to True too. However, in this case, the python code execution takes longer time. In addition, quantization.onnx_extra_options.weights_tensor_override and quantization.onnx_extra_options.activations_tensor_override should be left to None to avoid any perturbation of the search loop. To finish, we recommend not to define onnx_quant_parameters.op_types_to_quantize, onnx_quant_parameters.nodes_to_quantize and onnx_quant_parameters.nodes_to_exclude in this operating mode: this will give a chance to the algorithm to explore more combinations.

3.4 Operating_mode: inspection

This mode can be useful for debug. It is intended to compute weights, bias and activation tensors SNR. Results are logged in stm32ai_main.log. It quantizes the model with the parameters specified in the yaml sections quantization, including onnx_quant_parameters and onnx_extra_options, which define among others bit-width and potential tensor overrides. It has to be noticed that bias is always quantized in Int32 whatever the scheme selected in the config file. So we expect biases are high in quality. Knowing the tensor quality, one can further investigate potential quantization issues. So it is recommended at the first time to launch this mode without any tensor override to get the complete view of tensors quantization quality. Important remark: computing all tensors quality metrics can take time especially if there are many layers and if the quantization set is large. To reduce the latency of this task, it is possible to use the parameter inspection_split in the section quantization.iterative_quant_parameters to only consider a split of the quantization set.

4. External quantization with AMD quark

In order to get access to a Python implementation of AdaQuant algorithm and Qmn quantization, we have integrated some features of AMD-quark library into our code.

  • AdaQuant is an algorithm designed to improve post training quantization of weights and activations. The core idea is to find improved quantization parameters (scale and offset) to minimize the mismatch between float and quantized layer outputs (layer after layer) using a small calibration dataset. It can theoretically be used with any bit-widths, however current AMD-quark version does not enable it for 4 bits. So, use it only for 8/16 bits. Therefore full_auto_w4w8a8 cannot be executed with AdaQuant, while full_auto_w8a8a16 can be.

  • Qmn is a symmetric quantization (so zero-point=0) with a power-of-2 scale. It is extremely interesting for futher execution on dedicated HW: layer output rescaling ends up in a simple shift rather than a multiplication. Therefore execution time can be reduced. However, not all the signals can be well represented by a power-of-2 scale: without caution, this can lead to high quantization noise and thus reduces output quality metric. With AMD-quark, it is recommended to execute Qmn quantization with AdaQuant parameter set to True. Execution takes more time, but in most cases it is possible to recover a quality metric close to the reference. Since Qmn relies on AMD-quark, it is again restricted to 8 or 16 bits and thus cannot be considered for full_auto_w4w8a8 while it can for full_auto_w8a8a16.

In general, our integration of the AMD-quark quantizer was only validated for activations in UInt8/Int8/UInt16/Int16 and for weights Int8. We strongly recommend to take into account this restriction.

5. Tensor Override

For investigating some quantization issues, it is possible to override some tensors parameters using quantization.onnx_extra_options.weights_tensor_override and quantization.onnx_extra_options.activations_tensor_override parameters.

  • Examples for setting the override parameters:

    weights_tensor_override: [['efficientnetv2-b0_1/block6a_se_reduce_1/convolution/ReadVariableOp:0', {'quant_type': Int16, 'scale': 0.0025, 'zero_point': -12}],
                              ['efficientnetv2-b0_1/stem_conv_1/convolution/merged_input:0', {'quant_type': Int16, 'axis': 0}]
                             ]
    activations_tensor_override: [['efficientnetv2-b0_1/block4a_se_reduce_1/mul_1:0', {'quant_type': Int16}],
                                  ['efficientnetv2-b0_1/block4a_se_expand_1/BiasAdd__79:0', {'quant_type': Int16, 'scale': 0.002, 'zero_point': 0}]
                                 ]

The first string for weights or activations is the tensor name in the ONNX floating point model to be quantized. This name can be obtain in the logging file after having executed the inspection mode as described in (#3-4) or through a model graphical viewer (example: Netron). In the example below:

  • orange box: the layer input tensor name

  • green box: layer weights tensor name

  • blue box: the layer output tensor name

plot

Common remarks: `zero_point` must be: - one integer scalar or a list of one integer value for per-tensor - a list of several integer values for per-channel

scale must be:

  • one float scalar or a list of one floating-point value for per-tensor

  • a list of several floating-point values for per-channel

Remarks for the weights:

  • When one specifies only quant_type without axis: whatever quantization.granularity value, the tensor will be quantized on a per-tensor basis. One scale and one zero_point can optionally be specified. Since weights are quantized per-tensor, bias will automatically be quantized per-tensor too.

  • if axis is specified, then it must be an integer: 0 if the tensor corresponds to the weights of any type of Conv, 1 for a ConvTranspose, 1 too for a Gemm or a MatMul by default.

  • when axis is specified (meaning that we intend to quantize the given tensor per-channel), if scale and zero_point are specified too, they must be a list of values whose length corresponds to the number of output channels for the considered tensor.

Remarks for activations:

  • They are not quantized per-channel. So if scale and zero_point are defined, one value for each is enough.

Potential parameters conflict:

  • With current onnx and ONNX runtime version we must not set onnx_quant_parameters.nodes_to_quantize and onnx_extra_options.weights_tensor_override. It seems they are mutually exclusive in ONNX runtime.