Creating Models for the NPU

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.

Choosing a Conversion Method

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.

MethodMatMul becomesConv becomesCalibrationOn this page
4 bit (weights only)MatMulNBits—Not requiredExample 1: ViT-B/16
8 bit (dynamic quantization)DynamicQuantizeLinear + MatMulIntegerDynamicQuantizeLinear + ConvIntegerNot requiredINT8 Dynamic Quantization
8 bit (static quantization)QuantizeLinear + MatMulIntegerQuantizeLinear + ConvIntegerRequired (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 quantizationInput scaleCharacteristics
DynamicQuantizeLinear (dynamic)Computed at each inference from the minimum and maximum of the whole tensorNo 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 datasetRequires 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.

Layers That Run on the NPU

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.

RuntimeLayerConditions
ailia SDKMatMulNBitsINT4, no zero point, constant weights and scales, K % 16 == 0
MatMulIntegerUINT8 input and INT8 / UINT8 weights. Supports constant and dynamic weights, scalar zero points, and fusion of Cast, scales, bias and UINT8 requantization
ConvInteger1D / 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 RuntimeMatMulNBits4 bit, no zero point, constant weights, K % 16 == 0, N % 128 == 0
MatMulInteger, MatMulIntegerToFloat, QLinearMatMul, QGemmConstant 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.

Example 1: ViT-B/16 — INT4 Weight-Only Quantization (MatMulNBits)

Basic Configuration: FP32 + NPU (INT8 MMA)

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.

OperationFormat in the modelWhere 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 AddFP32CPU: FP32
MatMul between activations, such as Attention QK / AVFP32CPU: FP32

This configuration has the following advantages:

Converting to MatMulNBits

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")
ParameterValueMeaning
op_types_to_quantize("MatMul",)Convert only MatMul. MatMuls without constant weights (Attention QK / AV) automatically stay FP32.
block_size128Size of the weight blocks that share a scale
is_symmetricTrueSymmetric quantization without a zero point. The NPU does not support zero points.
accuracy_level4Quantize inputs to INT8 and accumulate in INT32
quant_formatQOperatorOutput 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.

Checking the Converted Model

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

INT8 Dynamic Quantization (DynamicQuantizeLinear + MatMulInteger / ConvInteger)

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.

Example 2: SAM 2.1 Tiny — Static Quantization (MatMulInteger)

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.

Example 3: Grounding DINO and Depth Anything V2 — Static Quantization of MatMuls, Attention and Convolutions

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.

StepTargetConverted formScript
1Constant-weight MatMulQuantizeLinear + MatMulInteger + Cast + Mul (tensor-wise UINT8 activations, channel-wise INT8 weights)calibrate_grounding.py / calibrate_depth.py
2MatMul with two dynamic inputs (Attention)QuantizeLinear on both inputs + MatMulInteger (using both zero points) + Cast + Mul by the two scalescalibrate_attention.py --model grounding / --model depth
3Convolution (Depth Anything V2 only)QuantizeLinear + ConvInteger + Cast + scale + biascalibrate_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.

Grounding DINO Swin-T (400×599)

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

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

Depth Anything V2 Metric Depth Small (518×518)

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

Example 4: YOLOX-S 320 — Static Quantization of Convolutions (ConvInteger)

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

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.

Next Steps

For how to run the converted model, see the NXP i.MX 95 Setup Guide. For measurement results, see NXP i.MX 95 Benchmarks.

References