STM32 model quantization

Post-training quantization (PTQ) converts a trained model to a lower-precision representation for deployment. Depending on the use case, framework, and target, the Model Zoo provides different quantizers and output formats. Quantization may reduce model size and improve inference performance, with accuracy impact depending on the model, data, and settings.

This guide describes the quantization workflow shared by many use cases. Dataset structure, preprocessing, and supported model inputs are described in each use case’s quantization guide; quantizer availability and output formats are summarized below.

1. Configure the YAML file

1.1 Set the model and the operation mode

Set operation_mode: quantization in the YAML configuration. You can also override it on the command line, for example: python stm32ai_main.py operation_mode=quantization.

operation_mode: quantization

model:
   model_path: <path-to-your-model>
   # Alternatively: 
   # model_name: <model-name>
   # input_shape: <model-input-shape>
   # pretrained: True
   # pretrained_dataset_name: <pretraining-dataset>
   # model_precision: <model-precision> example : w8a8_ptq 

1.2 Prepare the dataset

Calibration data is configured in the dataset section. Use representative inputs that match the data expected by the model. The required path field and data layout depend on the use case; follow its dataset and quantization documentation. In image-based workflows, this may look like:

dataset:
   quantization_path: <path-to-calibration-data>
   quantization_split: 0.1  # Optional fraction of the available data

Use a dedicated calibration set or an appropriate subset of training data. Where supported, quantization_split limits the fraction of that data used for calibration. Do not assume that all use cases use quantization_path; some require different path or sample-count fields.

For image workflows that use quantization_path and training_path, the diagram shows how calibration data is selected: quantization_path takes precedence; otherwise, training_path may be used, with the configured split selecting a subset. If neither path is set, the illustrated workflow uses fake quantization. Audio and time-series workflows can use different calibration inputs, such as sample counts or dataset-specific files.

Quantization dataset path selection

Calibration typically uses a representative subset rather than the full dataset. The suitable number of samples depends on the model and use case; verify quantized accuracy with the use-case evaluation workflow when calibration data is available.

1.3 Apply preprocessing

Calibration samples must be transformed in the same way as inputs to the trained model. Configure preprocessing according to the model’s training pipeline and the use-case requirements. Image workflows commonly specify resizing, rescaling, and color format; audio and time-series workflows may use different preprocessing sections.

preprocessing:
   # Image workflows only; use fields required by your use case and model.
   rescaling: { scale: <scale>, offset: <offset> }
   resizing:
      aspect_ratio: <aspect-ratio>
      interpolation: <interpolation>
   color_mode: <color-mode>

1.4 Choose a quantizer and configure the model

Choose one quantization path supported by your use case and model.

TensorFlow Lite quantization

Use TFlite_converter in supported TensorFlow/Keras workflows. These configurations generally quantize a Keras model and produce a .tflite artifact.

operation_mode: quantization

model:
   model_path: <path-to-keras-model>

quantization:
   quantizer: TFlite_converter
   quantization_type: PTQ
   quantization_input_type: uint8
   quantization_output_type: float
   granularity: per_channel
   optimize: false
   export_dir: quantized_models
  • operation_mode — String. Set to quantization to run the Model Zoo quantization workflow.

  • model_path — String. Path to the model to quantize. For this path, provide a Keras model (.keras) when a model path is used; some use cases instead support model-selection fields.

  • quantizer — String. Set to TFlite_converter to convert the trained model’s weights from floating point to integer values. The quantized model is saved in TensorFlow Lite format (.tflite).

  • quantization_type — String. The only option is PTQ (Post-Training Quantization).

  • quantization_input_type — String. Can be int8, uint8, or float; sets the quantization type for the model input. Used only for TFLite.

  • quantization_output_type — String. Can be int8, uint8, or float; sets the quantization type for the model output. Used only for TFLite.

  • granularity — String. Can be per_tensor or per_channel and defines the quantization granularity. If undefined, the default is per-channel.

  • optimize — Boolean. Can be true or false; controls whether the model is optimized before quantization. Used only with TFlite_converter and granularity: per_tensor. If undefined, the default is false.

  • export_dir — String. Directory name in which to save the quantized model. The default is quantized_models.

Example TFLite configurations are provided in each use case’s config_file_examples/ directory.

ONNX quantization

Use Onnx_quantizer in workflows that support ONNX quantization. It consumes a float Keras or ONNX model and produces an ONNX QDQ model. PyTorch workflows export the model to ONNX for quantization.

operation_mode: quantization

model:
   model_path: <path-to-onnx-or-keras-model>

quantization:
   quantizer: Onnx_quantizer
   quantization_type: PTQ
   operating_mode: default  # Optional; default is assumed when undefined.
   granularity: per_channel
   target_opset: 21
   onnx_quant_parameters:
      weightType: Int8
      activType: Int8
      calibrate_method: MinMax
      ChannelZeroingThreshold: 1e-7
   # Optional ONNX-specific fields; configure the relevant block for the
   # selected operating_mode (see the advanced guide for required settings).
   # onnx_extra_options:
   #    WeightSymmetric: true
   # iterative_quant_parameters:
   #    accuracy_tolerance: 1.0
   # calib_dataset_search_parameters:
   #    flex_parameters: false
   #    created_dataset_path: <path-to-created-calibration-data>
   export_dir: quantized_models
  • operation_mode — String. Set to quantization to run the Model Zoo quantization workflow.

  • model_path — String. Path to the model to quantize. Supported file extensions are .onnx and .keras.

  • quantizer — String. Set to Onnx_quantizer to convert the trained model’s weights from floating point to integer values. The quantized model is saved in ONNX QDQ format.

  • quantization_type — String. The only option is PTQ (Post-Training Quantization).

  • operating_mode — String. Can be default, inspection, full_auto_w4w8a8, full_auto_w8a8a16, or calib_dataset_search. With the ONNX quantizer, these modes support debugging, mixed-precision quantization, or construction of an efficient calibration dataset for the specified model. See the advanced ONNX quantization guide for details. If undefined, default is assumed.

  • granularity — String. Can be per_tensor or per_channel and defines quantization granularity. If undefined, the default is per-channel.

  • target_opset — Integer. Target opset for ONNX models; used only with Onnx_quantizer. If undefined, the default is 21. Supported values are 17–21; use 21 for 4-bit or 16-bit quantization. See the advanced ONNX quantization guide for details.

  • export_dir — String. Directory name in which to save the quantized model. The default is quantized_models.

  • onnx_quant_parameters — Field. Optional settings specific to Onnx_quantizer, including weight and activation types, calibration method, channel zeroing threshold, operator/node selection, AdaQuant, and Qmn. Refer to the advanced ONNX quantization guide for supported fields and values.

  • onnx_extra_options — Field. Optional settings specific to Onnx_quantizer, including symmetric quantization, bias quantization, calibration moving average, SmoothQuant, and tensor overrides. See the advanced ONNX quantization guide.

  • iterative_quant_parameters — Field. Used by Onnx_quantizer for inspection, full_auto_w4w8a8, and full_auto_w8a8a16. It includes inspection_split and accuracy_tolerance; accuracy_tolerance is required for the two full-auto modes. See the advanced ONNX quantization guide.

  • calib_dataset_search_parameters — Field. Used by Onnx_quantizer only with calib_dataset_search to construct an optimized calibration dataset rather than selecting samples randomly from the training set. It includes flex_parameters and the required created_dataset_path. See the advanced ONNX quantization guide.

Regardless of the values assigned to quantization_input_type and quantization_output_type, the ONNX QDQ model generated at this stage always has floating-point inputs and outputs.

Example ONNX configurations are provided in the relevant framework config directories.

1.5 Random quantization

When no path is specified in dataset.quantization_path or dataset.training_path, the model is quantized after calibration on random data. There is no interest in evaluating the output in this case. However, this random quantization can be useful to quickly estimate the model footprints on a target after quantization. We will see how to proceed in the next section.

1.6 Hydra and MLflow settings

The mlflow and hydra sections must always be present in the YAML configuration file. The hydra section can be used to specify the name of the directory where experiment directories are saved and/or the pattern used to name experiment directories. With the YAML code below, every time you run the Model Zoo, an experiment directory is created that contains all the directories and files created during the run. The names of experiment directories are all unique as they are based on the date and time of the run.

hydra:
   run:
      dir: ./experiments_outputs/${now:%Y_%m_%d_%H_%M_%S}

The mlflow section is used to specify the location and name of the directory where MLflow files are saved, as shown below:

mlflow:
   uri: ./experiments_outputs/mlruns

2. Run quantization

From the use-case root directory, run the use case’s quantization configuration. For example, if its example is named quantization_config.yaml and is in config_file_examples/:

python stm32ai_main.py --config-path ./config_file_examples/ --config-name quantization_config.yaml

The quantized model can be found in the corresponding experiments_outputs/ folder.

3. Chained services

Chained services let you run multiple Model Zoo operations as one workflow, in a defined sequence, instead of launching each operation separately. A chain can combine steps such as training, evaluation, quantization, benchmarking, and deployment; the chain name indicates which steps are included and their order.

Chained-mode YAMLs are stored with each use case. The examples are in <use_case>/config_file_examples/ and <use_case>/config_file_examples_pt/. Filenames begin with the chain name (for example, chain_eqe_config.yaml). The following chains include quantization:

  • chain_eqe: evaluate the float model, quantize, then evaluate the quantized model.

  • chain_eqeb: chain_eqe followed by benchmarking.

  • chain_qb: quantize, then benchmark.

  • chain_qd: quantize, then deploy.

  • chain_tqe: train, quantize, then evaluate.

  • chain_tqeb: chain_tqe followed by benchmarking.

Run the command from the use-case root directory, substituting the chain YAML’s exact filename. For a TensorFlow example:

python stm32ai_main.py --config-path ./config_file_examples/ --config-name chain_eqe_config.yaml

In case you want to evaluate your quantized model footprints, you can either launch the benchmark operation mode on the generated quantized model (please refer to the benchmarking that describes in detail how to proceed) or you can use chained services like launching the chain_qb example with the command below:

python stm32ai_main.py --config-path ./config_file_examples/ --config-name chain_qb_config.yaml

Chained services work whether you specify a quantization dataset or not (random quantization).