NPU 対応モデルの作り方

NXP i.MX 95 の Neutron NPU で実行できる ONNX モデルの作り方を、ViT-B/16、SAM 2.1 Tiny、Grounding DINO、Depth Anything V2、YOLOX-S を例に説明します。ailia SDK のセットアップは NXP i.MX 95 セットアップガイド を参照してください。

変換方式の選択

Neutron NPU が実行するのは INT8 の行列積です。NPU 用のモデルは、FP32 の ONNX モデルの行列積や畳み込みを、ailia SDK が NPU 化できる標準 ONNX の整数演算 (MatMulNBits、MatMulInteger、ConvInteger) へ変換して作成します。必要な精度とキャリブレーションの有無に応じて、次の 3 つから選択します。

方式MatMul の変換先Conv の変換先キャリブレーション本ページの説明
4 bit (重みのみ)MatMulNBits—不要例 1: ViT-B/16
8 bit (動的量子化)DynamicQuantizeLinear + MatMulIntegerDynamicQuantizeLinear + ConvInteger不要INT8 動的量子化
8 bit (静的量子化)QuantizeLinear + MatMulIntegerQuantizeLinear + ConvInteger必要 (校正データセット)例 2: SAM 2.1 Tiny、例 3: Grounding DINO・Depth Anything V2、例 4: YOLOX-S

4 bit で精度が十分な場合は、キャリブレーション不要の MatMulNBits から始めることを推奨します。Transformer 系モデルの全結合層に適しています。8 bit が必要な場合は MatMulInteger / ConvInteger を使用します。前段の量子化は DynamicQuantizeLinear と QuantizeLinear のどちらでも NPU で実行できるため、精度と速度、校正データの有無に合わせて選択してください。

前段の量子化入力の scale特徴
DynamicQuantizeLinear (動的)推論ごとにテンソル全体の最小値・最大値から計算キャリブレーション不要。DynamicQuantizeLinear 自体は CPU で実行します。scale が定数でないため、ConvInteger の後続の scale・bias・活性化はセグメント内で融合できず、通常の CPU レイヤーとして処理します。
QuantizeLinear (静的)校正データセットで決めた定数校正データが必要。scale が定数なので、ConvInteger の後続の scale・bias・活性化と UINT8 への再量子化を NPU セグメント内で融合でき、FP32 の中間テンソルを作らずに UINT8 で出力できます。CNN の高速化に向いています。

いずれの方式でも、モデル全体を量子化する必要はありません。条件を満たさないノードは自動的に CPU (FP32) で実行されます。

NPU で実行できるレイヤー

ailia SDK と NXP ONNX Runtime (Neutron Execution Provider) が NPU で実行するレイヤーは次のとおりです。いずれも条件を満たさないノードは CPU で実行されます。

ランタイムレイヤー条件
ailia SDKMatMulNBitsINT4、zero point なし、定数重み・scale、K % 16 == 0
MatMulIntegerUINT8 入力、INT8 / UINT8 重み。定数重みと動的重み、scalar zero point、Cast・scale・bias・UINT8 再量子化の融合に対応
ConvInteger1D / 2D、group 1、UINT8 入力、定数 INT8 / UINT8 重み。stride、dilation、auto padding、scalar / channel-wise weight zero point に対応。scale が定数の場合は、後続の scale・bias・活性化 (Swish などの LUT) と UINT8 再量子化を融合
NXP ONNX RuntimeMatMulNBits4 bit、zero point なし、定数重み、K % 16 == 0、N % 128 == 0
MatMulInteger、MatMulIntegerToFloat、QLinearMatMul、QGemm定数重み、N % 16 == 0

FP32 の MatMul や Attention は、サイズにかかわらず FP32 のまま実行し、ランタイムが暗黙に INT8 化することはありません。整数演算で実行するには、モデル内で DynamicQuantizeLinear または QuantizeLinear と MatMulInteger を使って量子化を明示してください。両入力が動的な MatMulInteger は、行列の大きさに応じて NPU か CPU (NEON の整数演算) で実行します。小さい行列や細長い行列は、NPU の起動とパディングの負荷を避けるため CPU で実行します。

ailia SDK の NPU フロントエンドは static QDQ パターン (DequantizeLinear → MatMul / Conv) を直接 NPU 化しません。QDQ モデルを使用する場合は、量子化テンソル、scale、zero point、乗算順序を維持したまま、対象演算を事前に MatMulInteger または ConvInteger へ変換してください (例 2〜例 4 を参照)。条件を満たさないノードは CPU で実行されます。

例 1: ViT-B/16 — INT4 weight-only 量子化 (MatMulNBits)

基本構成: FP32 + NPU (INT8 MMA)

NPU を使う場合も、モデル全体を INT8 に量子化する必要はありません。基本構成は、モデルは FP32 のまま、定数の重みを持つ MatMul (全結合層) だけを MatMulNBits (INT4 重み) に変換する形です。変換した MatMulNBits は NPU で INT8 の積和演算 (MMA) として実行され、それ以外のレイヤーは FP32 のまま CPU で実行されます。

演算モデル内の形式実行先と精度
定数重みの MatMul (Attention の Q/K/V・出力投影、MLP など)MatMulNBits (INT4 重み)NPU: 入力を INT8 に動的量子化し、INT8 × INT8 を INT32 で累積して FP32 に戻す
LayerNorm、Softmax、GELU、残差の AddFP32CPU: FP32
Attention の QK / AV など入力同士の MatMulFP32CPU: FP32

この構成には次の利点があります。

MatMulNBits への変換

変換は PC で ONNX Runtime の MatMulNBitsQuantizer を使って行います。ailia-models の ViT のエクスポートサンプル image_classification/vit/export/export_int4.py が参考になります。MatMulNBits の仕組みについては MatMulNBits : LLM や VLM を ONNX で動かすための 4bit 量子化 を参照してください。

pip3 install onnxruntime onnx numpy
cd ailia-models/image_classification/vit/export
python3 export_int4.py

FP32 モデルをダウンロードし、MatMulNBits へ変換して、ViT-B_16-224-int4.onnx と ailia 用の .prototxt を出力します。変換の中心部分は次のとおりです。

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")
パラメータ値意味
op_types_to_quantize("MatMul",)MatMul だけを変換します。重みが定数でない MatMul (Attention の QK / AV) は自動的に FP32 のまま残ります。
block_size128scale を共有する重みのブロックサイズ
is_symmetricTruezero point なしの対称量子化。NPU は zero point 付きに対応していません。
accuracy_level4入力を INT8 に量子化し、INT32 で累積する
quant_formatQOperatorMatMulNBits ノードとして出力する

ViT-B/16 では、定数重みの MatMul 72 個が MatMulNBits に変換され、Attention の MatMul 24 個と分類ヘッドの Gemm 1 個は FP32 のまま残ります。

変換結果の確認

NPU で実行されるのは、MatMulNBits のうち K が 16 の倍数、N が 128 の倍数で、zero point を持たないものです。条件を満たさないノードは自動的に CPU で実行されるため、エラーにはなりません。変換後のモデルは次のように確認できます。

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")

ailia で読み込むための .prototxt は export-to-onnx の onnx2prototxt.py で生成します (エクスポートサンプルは自動で生成します)。

python3 onnx2prototxt.py ViT-B_16-224-int4.onnx

INT8 動的量子化 (DynamicQuantizeLinear + MatMulInteger / ConvInteger)

4 bit では精度が足りず、校正データも用意しない場合は、動的量子化を使用します。重みを 8 bit に量子化し、入力は推論ごとに DynamicQuantizeLinear で量子化します。ONNX Runtime の quantize_dynamic で MatMul と Conv を量子化すると、標準 ONNX の DynamicQuantizeLinear + MatMulInteger / DynamicQuantizeLinear + ConvInteger 構成のモデルが得られます。

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,
)

Transformer 系のモデルでは MatMul だけを量子化する (op_types_to_quantize=["MatMul"]) こともできます。CNN では、ConvInteger の後続の処理が CPU で実行されるため、速度を重視する場合は例 4 の静的量子化を検討してください。両入力が動的な Attention の MatMul も、両入力それぞれに DynamicQuantizeLinear を付けた MatMulInteger として量子化できます。例 3 の手順 1 で作るモデルがこの構成です。

例 2: SAM 2.1 Tiny — 静的量子化 (MatMulInteger)

校正データセットによる静的量子化の例です。QDQ 形式で量子化した後、量子化テンソルと scale を維持したまま、対象の MatMul を標準 ONNX の MatMulInteger へ変換します。ailia は両入力が動的な MatMulInteger も NPU で実行できるため、Attention の行列積も NPU 化できます。

i.MX 95 のベンチマークで使用した SAM 2.1 Tiny の COCO 校正済みモデルは、ailia-sdk-nxp-demo の scripts/calibrate_sam2.py で生成しています。変換済みモデルは同リポジトリの models/ に同梱されているため、まず動かす場合は変換不要です。自分で生成する場合は、ailia-models の SAM 2 の公開 SAM 2.1 Tiny ONNX と COCO 2017 validation の画像・アノテーションを用意し、ホスト 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

校正は COCO val2017 の全 5,000 画像による Min/Max 方式で、活性値は tensor ごとの UINT8、定数重みはチャネルごとの INT8 に量子化します。Memory Attention の校正には、各画像から生成した 5 フレームの疑似動画を使用します。

生成されるモデルは INT8 / FP32 の混在です。量子化に弱い演算を FP32 に残す点は 例 1 と同じです。

QDQ の MatMul ペアを MatMulInteger へ変換する処理は scripts/convert_qdq_matmul.py として独立しており、自作の QDQ モデルにも適用できます。scale と量子化テンソルを維持したまま変換し、再量子化は行いません。整数累積により浮動小数点の丸めが変わるため、変換後はモデルの出力を検証してから使用してください。

校正の記録 (manifest.json、ranges_*.json、completion.json) は出力先に保存され、中断しても同じコマンドで再開できます。デモに同梱したモデルの校正記録は、リポジトリの calibration/ にあります。このページの例 3・例 4 のスクリプトも同様です。

例 3: Grounding DINO・Depth Anything V2 — MatMul・Attention・畳み込みの静的量子化

Transformer 系の大きなモデルでも、MatMul、Attention、畳み込みを段階的に静的量子化できます。Softmax や LayerNorm などその他の演算は FP32 のままです。デモ同梱のモデルは、COCO val2017 の全 5,000 画像による global Min/Max 方式の校正を、対象ごとに次の順で行っています。

手順対象変換後の構成スクリプト
1定数重みの MatMulQuantizeLinear + MatMulInteger + Cast + Mul (活性値は tensor ごとの UINT8、重みはチャネルごとの INT8)calibrate_grounding.py / calibrate_depth.py
2両入力が動的な MatMul (Attention)両入力の QuantizeLinear + MatMulInteger (両方の zero point を使用) + Cast + 2 つの scale の Mulcalibrate_attention.py --model grounding / --model depth
3畳み込み (Depth Anything V2 のみ)QuantizeLinear + ConvInteger + Cast + scale + biascalibrate_attention.py --model depth-conv

手順 1 の時点では、Attention の MatMul は両入力に DynamicQuantizeLinear を付けた動的量子化の構成になっています。このモデルもそのまま使用できます (INT8 動的量子化を参照)。手順 2 で Attention の活性値の範囲も校正すると、scale が定数になります。固定した範囲は、校正データの分布から外れる入力では値が飽和することがあるため、変換後は出力を検証してください。

各手順は 5,000 画像すべての処理が必要で、中断しても同じコマンドで再開できます。完了した手順だけが出力モデルと completion.json を書き出します。デモ同梱のモデルの校正済みの範囲 (ranges.json) は calibration/ にあるため、COCO を用意せずにモデル変換だけをやり直すこともできます。

Grounding DINO Swin-T (400×599)

ailia-models の Grounding DINO の公開モデル groundingdino_swint_ogc.onnx を変換します。

curl --fail --location --output groundingdino_swint_ogc.onnx \
  https://storage.googleapis.com/ailia-models/groundingdino/groundingdino_swint_ogc.onnx
# 手順 1: 定数重みの MatMul
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
# 手順 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

同梱の校正済みの範囲からモデルだけを再生成する場合は、次のコマンドを使用します。

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)

ailia-models の屋内向け (Hypersim) Small モデルを変換します。

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
# 手順 1: 定数重みの MatMul
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
# 手順 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
# 手順 3: 畳み込み
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

同梱の校正済みの範囲からモデルだけを再生成する場合は、次のコマンドを使用します。

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

例 4: YOLOX-S 320 — 畳み込みの静的量子化 (ConvInteger)

CNN では、畳み込みを標準 ONNX の ConvInteger に変換して NPU で実行します。ailia SDK は 2D の ConvInteger と、その後に続く scale・bias・活性化を NPU セグメント内で融合し、UINT8 の特徴マップを直接出力します。ailia-models の YOLOX-S (yolox_s.opt.onnx) を、COCO val2017 の全 5,000 画像による Min/Max 方式で校正します。

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

COCO val2017 全 5,000 枚での AP は、FP32 (ホスト ORT CPU) の 30.42 に対し、INT8 (ailia NPU) で 29.00 (-1.42 ポイント) です。評価画像は校正データと同じため、独立したテストセットでの精度ではありません。

次のステップ

変換したモデルの実行方法は NXP i.MX 95 セットアップガイド、測定結果は NXP i.MX 95 ベンチマーク を参照してください。

参考資料