Quantization¶
| You have | Do this |
|---|---|
| An ONNX CNN (YOLO, ResNet, RT-DETR...) | calibrate and import with int8 convolutions |
| An ONNX model and a validation metric, and you want the best speed/accuracy trade-off | autoquantize |
An already-quantized ONNX model (QDQ, QLinear, int4 MatMulNBits) |
import it as is |
A MuNet model with Linear layers (MLPs, transformers, LLM-style decode) |
munet.quantize |
| Accuracy loss to recover | quantization-aware training |
All int8 and int4 programs save to .mnet with their scales. C, C++ and Rust load them quantized with no extra setup.
int8 for ONNX models¶
from munet.quantization import calibrate_onnx
from munet.interop import from_onnx
import munet
calib = [(load_image(p),) for p in calibration_paths] # 50-500 inputs like those you serve, as model input tuples
scales = calibrate_onnx("model.onnx", calib) # {conv name: activation scale}
model = from_onnx("model.onnx", input_shapes={"images": (1, 3, 640, 640)}, precision="fp16", int8=scales)
munet.save(model, "model-int8.mnet")
calibrate_onnx(path, batches, *, observer="minmax", min_snr_db=20, device="vulkan", bins=2048, native=False) runs the
model in fp32 and returns {layer name: scale}. Observers are "minmax" (default), "mse" and "mean_max". Layers
whose quantized input keeps less than min_snr_db dB of signal-to-noise ratio are left out and stay fp16; pass
min_snr_db=0 to quantize every eligible layer. native=True uses the
engine's C++ importer, the same code as C's munet_calibrate_onnx and Rust's munet::calibrate_onnx.
- Which convolutions run in int8. Those with constant weights, a spatial kernel (not 1x1), and a multiple of 32
channels per group. The rest stay fp16.
model.stats()["int8_conv_kernels"]counts the int8 ones. - How values are quantized. Weights per output channel, activations per tensor, both symmetric int8.
- Calibration data matters more than its amount. Use real inputs from your domain.
- Observers.
"mse"clips rare large activations to resolve the common ones better. That can help CNNs, but transformer MLP outputs carry signal in those large values: DINOv2-B fell to cos 0.42 against fp32 with"mse"."minmax"with the SNR filter keeps 0.99 there and matches"mse"on ResNet-50 and ConvNeXt. - Check accuracy on your validation set with your task metric before shipping.
- Partial selection. Pass a subset of
scalesto quantize only some layers. Sensitive layers are often the first convolution and a few encoder layers.
Each layer you quantize saves time and costs some accuracy. Measure both on your model.
Runnable: examples/python/quantize_int8.py (calibrate, compare with fp16, time, save).
Pick layers automatically¶
autoquantize measures each candidate layer's speed gain and accuracy cost on your GPU. It keeps the largest set of
layers whose combined accuracy stays within a tolerance:
from munet.quantization import autoquantize
def metric(reference, candidate): # lower is better; lists of per-batch output tuples
return 1.0 - my_map50(candidate) # e.g. detection AP against ground truth (ignore reference)
result = autoquantize("model.onnx", calibration_batches, validation_batches, metric=metric, tolerance=0.005)
result.save("int8-selection.json")
model = result.compile("model.onnx", precision="fp16") # = from_onnx(path, int8=result.int8)
Signature: autoquantize(model, calibration, validation=None, *, metric=None, tolerance=0.01, device="vulkan",
autotune=True, ...).
- Candidates are convolutions and MatMul/Gemm layers with constant weights.
- Default metric: without
metric, the relative error against fp32 outputs. - Runtime: minutes to tens of minutes for a large model. Save the result and reuse it.
Pre-quantized ONNX models¶
QDQ graphs (QuantizeLinear / DequantizeLinear around Conv/MatMul) and QLinear operators (QLinearConv,
QLinearMatMul, MatMulInteger, ConvInteger) import directly:
model = from_onnx("model-qdq.onnx", input_shapes=...)
- int8 kernels: symmetric int8 QDQ
MatMuls run on the int8 GEMM. - int4 weights: int4 / uint4
DequantizeLinear(includingblock_size) andcom.microsoftMatMulNBitsfeeding aMatMulrun on packed int4 weights, with zero points. - Typical int4 sources: ONNX Runtime GenAI, Olive and Optimum weight-only exports (
MatMulNBits), and QDQ models with int4DequantizeLinearweights. Both importers (Python and native C/C++/Rust) read them. - Float path: other quantized operators run as quantize → float op → dequantize. This is exact but not faster than fp16.
Quantize MuNet Linear layers¶
import munet as mu
model.eval()
mu.quantize(model, scheme="w8a8_dynamic") # in place: Linear -> QuantLinear
program = mu.compile(model)
Signature: mu.quantize(model, calib_data=None, *, scheme="w8a8_dynamic", observer="minmax", group_size=128,
device="cpu"). Note the default observer here is "minmax", not "mse".
| Scheme | Weights | Activations | Best for |
|---|---|---|---|
w8a8_dynamic |
int8 per channel | int8 per row, computed at run time | large batches (prefill, big MLPs) |
w8a8 |
int8 per channel | int8 per tensor, calibrated (pass calib_data) |
same, slightly cheaper |
w8 |
int8 per channel | fp16 | batch 1-8 (decode): memory-bound |
w4 |
int4, groups of 128 | fp16 | batch 1-8, memory-limited |
Weight-only schemes save memory (half for w8, a quarter for w4). Above 8 rows they run about as fast as fp16.
to_onnx exports w4 weights as int4 DequantizeLinear with block_size, so onnxruntime and from_onnx load them
as int4.
Check accuracy with mu.quantization.compare(fp32_program, quantized_program, inputs). It returns the cosine,
max error and relative error.
Quantization-aware training¶
Quantized layers train like normal ones: gradients pass straight through the rounding. Quantize, then fine-tune with a low learning rate:
mu.quantize(model, calib_batches, scheme="w8a8")
model.train()
# ... the usual compiled train step and loop (training.md), a few epochs at lr ~1e-5 ...
Limits¶
- What stays fp16: 1x1 convolutions, asymmetric (zero-point) activation ranges, and batched right-hand matmul operands. Weight zero points are fine: int4 and int8 weights keep them.
- int4 ONNX limits:
MatMulNBitswith 4 or 8 bits, integer zero points and nog_idx. Blocked int4 weights that don't feed a 2-DMatMul(axis 0,Ka multiple ofblock_size) are dequantized at import and run in fp16. - Accuracy without a GPU. The quantize-dequantize arithmetic also runs on CPU and fp32 plans, so you can check a selection's accuracy on any machine.
- Export.
to_onnxexports quantized programs as QDQ (ONNX). - Turn int8 off.
MUNET_NO_INT8=1runs quantized layers in fp16 (Environment variables).