How to create ONNX models that run on the NXP i.MX 95 Neutron NPU, with examples: ViT-B/16, SAM 2.1 Tiny, Grounding DINO, Depth Anything V2 and YOLOX-S. For setting up ailia SDK, see the NXP i.MX 95 Setup Guide.
The Neutron NPU executes INT8 matrix multiplications. A model for the NPU is created by converting the matrix multiplications and convolutions of an FP32 ONNX model into the standard ONNX integer operators that ailia SDK can offload (MatMulNBits, MatMulInteger and ConvInteger). Choose one of the following three methods depending on the accuracy you need and whether calibration data is available.
| Method | MatMul becomes | Conv becomes | Calibration | On this page |
|---|---|---|---|---|
| 4 bit (weights only) | MatMulNBits | — | Not required | Example 1: ViT-B/16 |
| 8 bit (dynamic quantization) | DynamicQuantizeLinear + MatMulInteger | DynamicQuantizeLinear + ConvInteger | Not required | INT8 Dynamic Quantization |
| 8 bit (static quantization) | QuantizeLinear + MatMulInteger | QuantizeLinear + ConvInteger | Required (calibration dataset) | Example 2: SAM 2.1 Tiny, Example 3: Grounding DINO and Depth Anything V2, Example 4: YOLOX-S |
If 4 bits give enough accuracy, start with MatMulNBits, which needs no calibration. It suits the fully connected layers of Transformer models. If you need 8 bits, use MatMulInteger / ConvInteger. Both DynamicQuantizeLinear and QuantizeLinear work as the preceding quantization step on the NPU, so choose based on accuracy, speed and whether calibration data is available.
| Preceding quantization | Input scale | Characteristics |
|---|---|---|
DynamicQuantizeLinear (dynamic) | Computed at each inference from the minimum and maximum of the whole tensor | No calibration needed. DynamicQuantizeLinear itself runs on the CPU. Because the scale is not constant, the scale, bias and activation after ConvInteger cannot be fused into the segment and run as ordinary CPU layers. |
QuantizeLinear (static) | Constant determined with a calibration dataset | Requires calibration data. Because the scale is constant, the scale, bias, activation and requantization to UINT8 after ConvInteger are fused into the NPU segment, which writes UINT8 output without an FP32 intermediate tensor. Better suited to speeding up CNNs. |
With any method, there is no need to quantize the whole model. Nodes that do not meet the conditions automatically run on the CPU in FP32.
The layers that ailia SDK and NXP ONNX Runtime (Neutron Execution Provider) run on the NPU are listed below. In both, nodes that do not meet the conditions run on the CPU.
| Runtime | Layer | Conditions |
|---|---|---|
| ailia SDK | MatMulNBits | INT4, no zero point, constant weights and scales, K % 16 == 0 |
| MatMulInteger | UINT8 input and INT8 / UINT8 weights. Supports constant and dynamic weights, scalar zero points, and fusion of Cast, scales, bias and UINT8 requantization | |
| ConvInteger | 1D / 2D, group 1, UINT8 input and constant INT8 / UINT8 weights. Supports stride, dilation, automatic padding and scalar / channel-wise weight zero points. When the scale is constant, the following scale, bias, activation (LUT, such as Swish) and UINT8 requantization are fused | |
| NXP ONNX Runtime | MatMulNBits | 4 bit, no zero point, constant weights, K % 16 == 0, N % 128 == 0 |
| MatMulInteger, MatMulIntegerToFloat, QLinearMatMul, QGemm | Constant weights, N % 16 == 0 |
FP32 MatMul and Attention run in FP32 regardless of size; the runtime never implicitly converts them to INT8. To run them as integer arithmetic, express the quantization in the model with DynamicQuantizeLinear or QuantizeLinear and MatMulInteger. MatMulInteger with two dynamic inputs runs on the NPU or on the CPU (NEON integer arithmetic) depending on the matrix size. Small or narrow matrices run on the CPU to avoid NPU setup and padding overhead.
The ailia SDK NPU frontend does not offload static QDQ patterns (DequantizeLinear → MatMul / Conv) directly. When using a QDQ model, convert the target operations offline to MatMulInteger or ConvInteger while preserving the quantized tensors, scales, zero points and multiplication order (see Examples 2 to 4). Nodes that do not meet the conditions run on the CPU.
Using the NPU does not require quantizing the whole model to INT8. The basic configuration keeps the model in FP32 and converts only MatMuls with constant weights (fully connected layers) to MatMulNBits (INT4 weights). The converted MatMulNBits nodes run on the NPU as INT8 multiply-accumulate (MMA), and the other layers stay FP32 and run on the CPU.
| Operation | Format in the model | Where it runs and precision |
|---|---|---|
| MatMul with constant weights (Attention Q/K/V and output projections, MLP, etc.) | MatMulNBits (INT4 weights) | NPU: inputs are dynamically quantized to INT8, INT8 × INT8 is accumulated in INT32 and converted back to FP32 |
| LayerNorm, Softmax, GELU, residual Add | FP32 | CPU: FP32 |
| MatMul between activations, such as Attention QK / AV | FP32 | CPU: FP32 |
This configuration has the following advantages:
Convert on a PC with ONNX Runtime's MatMulNBitsQuantizer. The ViT export sample in ailia-models, image_classification/vit/export/export_int4.py, is a good reference. For how MatMulNBits works, see MatMulNBits: 4-bit quantization for running LLMs and VLMs with ONNX (Japanese).
pip3 install onnxruntime onnx numpy
cd ailia-models/image_classification/vit/export
python3 export_int4.py
It downloads the FP32 model, converts it to MatMulNBits, and writes ViT-B_16-224-int4.onnx and the .prototxt for ailia. The core of the conversion is:
import onnx
from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer
from onnxruntime.quantization.quant_utils import QuantFormat
model = onnx.load("ViT-B_16-224.onnx")
quantizer = MatMulNBitsQuantizer(
model=model,
block_size=128,
is_symmetric=True,
accuracy_level=4,
quant_format=QuantFormat.QOperator,
op_types_to_quantize=("MatMul",),
)
quantizer.process()
onnx.save(quantizer.model.model, "ViT-B_16-224-int4.onnx")
| Parameter | Value | Meaning |
|---|---|---|
op_types_to_quantize | ("MatMul",) | Convert only MatMul. MatMuls without constant weights (Attention QK / AV) automatically stay FP32. |
block_size | 128 | Size of the weight blocks that share a scale |
is_symmetric | True | Symmetric quantization without a zero point. The NPU does not support zero points. |
accuracy_level | 4 | Quantize inputs to INT8 and accumulate in INT32 |
quant_format | QOperator | Output as MatMulNBits nodes |
For ViT-B/16, 72 MatMuls with constant weights become MatMulNBits, while the 24 Attention MatMuls and the classification-head Gemm stay FP32.
MatMulNBits nodes run on the NPU when K is a multiple of 16, N is a multiple of 128, and there is no zero point. Nodes that do not meet these conditions run on the CPU automatically, without errors. You can check the converted model as follows.
import collections, onnx
model = onnx.load("ViT-B_16-224-int4.onnx")
print(collections.Counter(n.op_type for n in model.graph.node))
for node in model.graph.node:
if node.op_type == "MatMulNBits":
a = {x.name: onnx.helper.get_attribute_value(x) for x in node.attribute}
ok = a["bits"] == 4 and a["K"] % 16 == 0 and a["N"] % 128 == 0 and len(node.input) <= 3
print(node.name, a["K"], a["N"], "OK" if ok else "CPU")
Generate the .prototxt that ailia loads with onnx2prototxt.py from export-to-onnx (the export sample generates it automatically).
python3 onnx2prototxt.py ViT-B_16-224-int4.onnx
If 4 bits are not accurate enough and you do not prepare calibration data, use dynamic quantization. Weights are quantized to 8 bits, and inputs are quantized at each inference with DynamicQuantizeLinear. Quantizing MatMul and Conv with ONNX Runtime's quantize_dynamic produces a model with the standard ONNX DynamicQuantizeLinear + MatMulInteger / DynamicQuantizeLinear + ConvInteger form.
from onnxruntime.quantization import quantize_dynamic, QuantType
quantize_dynamic(
"model.onnx",
"model-int8-dynamic.onnx",
op_types_to_quantize=["MatMul", "Conv"],
weight_type=QuantType.QInt8,
)
For Transformer models, you can also quantize only MatMul (op_types_to_quantize=["MatMul"]). For CNNs, the processing after ConvInteger runs on the CPU, so consider static quantization as in Example 4 when speed matters. Attention MatMuls with two dynamic inputs can also be quantized as MatMulInteger with a DynamicQuantizeLinear on each input. The model produced in step 1 of Example 3 has this form.
This is an example of static quantization with a calibration dataset. After quantizing to the QDQ format, convert the target MatMuls to standard ONNX MatMulInteger while preserving the quantized tensors and scales. Because ailia can run MatMulInteger with two dynamic inputs on the NPU, the Attention matrix multiplications are also offloaded.
The COCO-calibrated SAM 2.1 Tiny model used in the i.MX 95 benchmarks is generated with scripts/calibrate_sam2.py in ailia-sdk-nxp-demo. The converted models are bundled in the repository's models/ directory, so no conversion is needed to try them first. To generate them yourself, prepare the published SAM 2.1 Tiny ONNX exports from SAM 2 in ailia-models and the COCO 2017 validation images and annotations, and run on a host PC:
git clone https://github.com/ailia-ai/ailia-sdk-nxp-demo.git
cd ailia-sdk-nxp-demo
python3 -m pip install -r scripts/requirements-calibration.txt
python3 scripts/calibrate_sam2.py \
--source-dir /path/to/ailia-models/image_segmentation/segment-anything-2 \
--download-sources \
--coco-images /path/to/coco/val2017 \
--coco-annotations /path/to/coco/annotations/instances_val2017.json \
--output /path/to/sam2-calibrated \
--workers 2 --threads 2
Calibration uses Min/Max over all 5,000 images of COCO val2017; activations are quantized to tensor-wise UINT8 and constant weights to channel-wise INT8. Memory Attention is calibrated with 5-frame pseudo-videos generated from each image.
The generated models mix INT8 and FP32. As in Example 1, operations that are sensitive to quantization stay FP32.
The step that lowers QDQ MatMul pairs to MatMulInteger is a standalone script, scripts/convert_qdq_matmul.py, and can be applied to your own QDQ models. It preserves the scales and quantized tensors and performs no requantization. Integer accumulation changes floating-point rounding, so validate the model outputs before deploying the converted model.
Calibration records (manifest.json, ranges_*.json and completion.json) are saved in the output directory, and an interrupted conversion resumes when you run the same command again. The calibration records for the models bundled with the demo are in the repository's calibration/ directory. The scripts in Examples 3 and 4 work the same way.
Large Transformer models can also be statically quantized step by step: MatMuls, Attention and convolutions. Other operations such as Softmax and LayerNorm remain FP32. The models bundled with the demo are calibrated with global Min/Max over all 5,000 COCO val2017 images, one target at a time in the following order.
| Step | Target | Converted form | Script |
|---|---|---|---|
| 1 | Constant-weight MatMul | QuantizeLinear + MatMulInteger + Cast + Mul (tensor-wise UINT8 activations, channel-wise INT8 weights) | calibrate_grounding.py / calibrate_depth.py |
| 2 | MatMul with two dynamic inputs (Attention) | QuantizeLinear on both inputs + MatMulInteger (using both zero points) + Cast + Mul by the two scales | calibrate_attention.py --model grounding / --model depth |
| 3 | Convolution (Depth Anything V2 only) | QuantizeLinear + ConvInteger + Cast + scale + bias | calibrate_attention.py --model depth-conv |
After step 1, the Attention MatMuls use dynamic quantization, with a DynamicQuantizeLinear on both inputs. This model can also be used as is (see INT8 Dynamic Quantization). Calibrating the Attention activation ranges in step 2 makes the scales constant. Fixed ranges can saturate inputs outside the calibration distribution, so validate the outputs after conversion.
Each step must process all 5,000 images and resumes when you run the same command again. Only a completed step writes the output model and completion.json. The calibrated ranges (ranges.json) of the bundled models are in calibration/, so you can redo only the model conversion without preparing COCO.
Convert the published groundingdino_swint_ogc.onnx from Grounding DINO in ailia-models.
curl --fail --location --output groundingdino_swint_ogc.onnx \
https://storage.googleapis.com/ailia-models/groundingdino/groundingdino_swint_ogc.onnx
# Step 1: constant-weight MatMuls
python3 scripts/calibrate_grounding.py \
--source groundingdino_swint_ogc.onnx \
--coco-images /path/to/coco/val2017 \
--coco-annotations /path/to/coco/annotations/instances_val2017.json \
--output /path/to/grounding-calibrated \
--workers 3 --threads 3
# Step 2: Attention
python3 scripts/calibrate_attention.py --model grounding \
--source /path/to/grounding-calibrated/models/groundingdino_swint_ogc_400x599_int8.onnx \
--vocab models/grounding_tokenizer/vocab.txt \
--coco-images /path/to/coco/val2017 \
--coco-annotations /path/to/coco/annotations/instances_val2017.json \
--output /path/to/grounding-fixed-attention
MatMulInteger nodes and no FP32 MatMul.groundingdino_swint_ogc_400x599_int8.onnx with external weight files (.dataNN). Keep the ONNX file and the weight files in the same folder.To regenerate only the model from the bundled calibrated ranges, run:
python3 scripts/grounding_convert.py --source groundingdino_swint_ogc.onnx \
--ranges calibration/grounding_dino/ranges.json \
--attention-ranges calibration/grounding_dino/attention/ranges.json \
--output models/groundingdino_swint_ogc_400x599_int8.onnx
Convert the indoor (Hypersim) Small model from ailia-models.
curl -fL https://storage.googleapis.com/ailia-models/depth_anything_v2/depth_anything_v2_metric_hypersim_vits.onnx \
-o /path/to/depth_anything_v2_metric_hypersim_vits.onnx
# Step 1: constant-weight MatMuls
python3 scripts/calibrate_depth.py \
--source /path/to/depth_anything_v2_metric_hypersim_vits.onnx \
--coco-images /path/to/coco/val2017 \
--coco-annotations /path/to/coco/annotations/instances_val2017.json \
--output /path/to/depth-calibrated
# Step 2: Attention
python3 scripts/calibrate_attention.py --model depth \
--source /path/to/depth-calibrated/depth_anything_v2_metric_hypersim_vits_518_int8.onnx \
--coco-images /path/to/coco/val2017 \
--coco-annotations /path/to/coco/annotations/instances_val2017.json \
--output /path/to/depth-fixed-attention
# Step 3: convolutions
python3 scripts/calibrate_attention.py --model depth-conv \
--source /path/to/depth-fixed-attention/depth_anything_v2_metric_hypersim_vits_518_int8.onnx \
--coco-images /path/to/coco/val2017 \
--coco-annotations /path/to/coco/annotations/instances_val2017.json \
--output /path/to/depth-conv-calibrated
To regenerate only the model from the bundled calibrated ranges, run:
python3 scripts/depth_convert.py \
--source /path/to/depth_anything_v2_metric_hypersim_vits.onnx \
--ranges calibration/depth_anything_v2/ranges.json \
--attention-ranges calibration/depth_anything_v2/attention/ranges.json \
--conv-ranges calibration/depth_anything_v2/convolution/ranges.json \
--output models/depth_anything_v2_metric_hypersim_vits_518_int8.onnx
For CNNs, convert convolutions to standard ONNX ConvInteger to run them on the NPU. ailia SDK fuses 2D ConvInteger with the following scale, bias and activation into the NPU segment and writes UINT8 feature maps directly. Calibrate YOLOX-S (yolox_s.opt.onnx) from ailia-models with Min/Max over all 5,000 images of COCO val2017.
curl -L https://storage.googleapis.com/ailia-models/yolox/yolox_s.opt.onnx -o yolox_s.opt.onnx
python3 scripts/calibrate_yolox.py \
--source yolox_s.opt.onnx \
--coco-images /path/to/val2017 \
--coco-annotations /path/to/annotations/instances_val2017.json \
--output models/yolox_s_320_int8.onnx \
--report calibration/yolox/report.json
ConvInteger. Weights are channel-wise INT8 and feature maps are UINT8.On all 5,000 COCO val2017 images, AP is 29.00 for INT8 (ailia NPU) versus 30.42 for FP32 (host ORT CPU), a decrease of 1.42 points. The evaluation images are the same as the calibration data, so this is not accuracy on an independent test set.
For how to run the converted model, see the NXP i.MX 95 Setup Guide. For measurement results, see NXP i.MX 95 Benchmarks.