Inference and performance¶
How to run models fast from Python, and what carries over to C, C++ and Rust.
Load once, call many times¶
model = from_onnx("model.onnx", precision="fp16", input_shapes={"images": (8, 3, 640, 640)}) # or munet.load("model.mnet")
model(warmup_batch) # first call compiles (seconds; cached on disk after the first time)
for batch in batches:
out = model(batch) # replays a recorded GPU command buffer
detections = out.numpy()
What a call does:
- Weights and intermediates stay on the GPU. A call uploads the inputs as part of the same GPU submission, runs
every kernel, and reads back only the outputs you
.numpy(). - Compiling is the expensive part. Keep the program object alive, and don't rebuild it per request.
.mnetloads faster than ONNX import. It skips the ONNX parsing and graph optimization, and is what C, C++ and Rust load (ONNX).- Threads. One program serializes its own calls. For parallel requests, load one program per thread or per GPU. Calls release the GIL.
Kernel cache¶
Compiled kernels (SPIR-V), driver pipeline caches and autotune results live in MUNET_CACHE_DIR (default
~/.cache/munet-next). Python, C, C++ and Rust share it.
- Copy the directory to deployment machines to skip compilation there.
- A read-only directory disables caching; programs still run.
Precision¶
precision= |
Matmul / conv arithmetic | Speed | Accuracy |
|---|---|---|---|
"fp32" |
float32 | 1x | exact reference |
"mixed" (default) |
fp16 inputs, fp32 accumulation, on tensor / matrix cores | ~2-3x fp32 | relative error ~1e-3; safe default |
"mixed_safe" |
as "mixed", plus rescaled matmul gradients |
as "mixed" |
training only: use it when training stalls or diverges in "mixed" |
"bf16" |
bf16 inputs and storage, fp32 accumulation | as "mixed" |
relative error ~3e-3; no fp16 overflow; fp32 on GPUs without bf16 matrix cores |
"fp16" |
fp16 inputs and accumulation | faster than "mixed" on GPUs with fast fp16 accumulation, same as "mixed" elsewhere |
validate per model |
- Everything outside matmuls and convolutions (activations, normalization, softmax) computes in fp32 in every mode.
- On GPUs without cooperative-matrix support,
"mixed"runs fp32 kernels."fp16"runs portable fp16 kernels where shaders have fp16 arithmetic, and fp32 kernels elsewhere.
Start with "fp16" for inference. If outputs differ too much from "fp32", use "mixed".
examples/python/infer_onnx.py --compare checks against ONNX Runtime.
Autotuning¶
Autotuning times kernel tile candidates on your GPU once per shape and caches the fastest. It typically gains 5-10% on large models and is off by default, because the first compile of each new shape takes longer.
model = from_onnx("model.onnx", input_shapes=..., precision="fp16", autotune=True)
model(example) # tunes during this call (default budget: 30 s per program)
How it works, what it gains and costs, and how to deploy tuned kernels: tuning.md.
Device probe¶
A few kernel choices depend on the GPU and driver (GPU vendors). The probe measures them on the GPU itself instead of relying on the built-in rules.
The first compile or load on a GPU and driver with no stored profile runs the probe automatically (a few seconds,
once). MUNET_AUTO_PROBE=0 turns this off. To probe ahead of time or again:
import munet as mu
profile = mu.probe_device() # a few seconds; C: munet_probe_device(0), Rust: munet::probe_device(0)
print(profile["gemm_vec_staging"], profile.get("direct_conv_tier"), profile.get("acc16_wide_tiles"), profile.get("conv_wide_tiles"))
- Correctness first. Each choice runs small convolutions and matmuls and is compared with the CPU reference executor. A choice that returns wrong results on this GPU is never selected.
- Then speed. The correct choices are timed against each other on the GPU. A built-in choice is replaced only on clear evidence; for wide fp16 tiles, only when it loses on every timed shape.
- Stored per GPU and driver. The result is saved as
device-<vendor>-<device>-<driver>-probe-v2.jsonin the kernel cache. Later compiles and loads use it instead of the built-in rules. A driver update gets a new profile. - Overrides win.
MUNET_CONV_DIRECT,MUNET_GEMM_VEC_STAGING,MUNET_ACC16_WIDEandMUNET_CONV_WIDE_TILEStake precedence over the profile; unset them before probing. - Once per device. A failed automatic probe prints a warning, keeps the built-in rules and is not retried in that process. The probe is separate from autotuning, which picks tile sizes per matrix shape.
mu.device_profile() returns the stored profile ({} if the GPU was never probed). complete is false and notes
says why when a check failed or the device was lost; restart the process in that case.
Batching¶
Per-call overhead is fixed, and GPUs need parallel work. Batching several images per call raises throughput, especially for small models.
- Static batch size. The batch size is part of the program. Import or
.mnet-export one program per batch size you serve, e.g.b1for latency andb8for throughput. - Several GPUs: one program per GPU, see Multiple GPUs.
- High-resolution frames: split them into tiles and run the tiles as one batch. The C/C++/Rust frame pipeline does this on the GPU (Zero copy and video).
int8 and int4¶
CNN convolutions can run in int8 after calibration. The gain depends on model size: large convolutions gain most, tiny models little. Check accuracy on your validation set.
Linear layers and int4 ONNX models (MatMulNBits, int4 QDQ) keep int4 weights on the GPU: a quarter of fp16's
memory, and faster when decoding one row at a time.
How to calibrate and choose layers: Quantization. Runnable example: examples/python/quantize_int8.py.
Measure¶
model.stats()["gpu_ms"] # GPU time of the last call (compute only)
model.stats() # kernels, memory (arena_bytes), upload/download bytes, compile times, int8 kernel counts, device
For a per-kernel breakdown, compile with profile=True. It serializes the kernels, so use it to find hot spots, not
to measure throughput:
model = from_onnx("model.onnx", input_shapes=..., precision="fp16", profile=True)
model(x)
for k in sorted(model.describe(), key=lambda k: -k["gpu_ms"])[:10]:
print(f"{k['gpu_ms']:.3f} ms {k['path']:24s} {k['names'][:3]}")
MUNET_PIPELINE_STATS=1 prints each kernel's register and spill counts from the driver.
When timing:
- Warm up first. Some GPUs (Intel Arc especially) idle at low clocks. Run for about a second before timing, and use the minimum of several runs.
- The first call includes compilation. Exclude it.
- End-to-end time = upload +
gpu_ms+ readback. For big inputs, upload dominates on small models. The Vulkan zero-copy path in C/C++/Rust removes it (Zero copy and video).
Checklist¶
- Fix shapes with
input_shapes. Don't use symbolic shapes in production. - Use
precision="fp16"(or"mixed"if accuracy needs it). - Run
autotune=Trueonce on each GPU model you deploy to (tuning.md). - Batch requests. Export one program per batch size.
- For CNNs, try int8 and measure accuracy.
- Keep programs alive. Use
.mnetfor fast loading and for C/C++/Rust. - Read back only the outputs you need, as late as possible.
- For video, use the GPU frame pipeline and zero copy (Zero copy and video).
GPU-specific settings: GPU vendors.
Example: object detection end to end¶
examples/python/detect_yolo.py covers the whole path for a YOLO model:
- letterbox pre-processing;
- GPU inference;
- decoding and NMS in NumPy;
- drawing the boxes;
- saving a
.mnet.
curl -LO https://github.com/jamjamjon/assets/releases/download/yolo/v11-n-det.onnx
python examples/python/detect_yolo.py v11-n-det.onnx street.jpg --precision fp16
DETR-style detectors (RT-DETR, D-FINE, DEIM) output labels, boxes, scores directly and need no NMS. Take
scores > threshold.