emmtrix ONNX-to-C Code Generator (emx-onnx-cgen) compiles ONNX models to portable, deterministic C code: from tiny networks for deeply embedded systems up to small language models (SLMs) in the billion-parameter range. The generated code runs without operating-system services or external runtimes and can be generated fully allocation-free (large models such as SLMs keep their buffers on the heap, allocated once at load time), making it suitable for safety-critical and resource-constrained targets. Language models keep their KV cache in persistent state buffers across calls, with a bounded context and a runtime sequence length for prefill and decode.
It now targets full standard ONNX opset 26 support based on ONNX v1.21.0 and supports nearly all microsoft ONNX operators based on ONNX Runtime 1.27.0.
Key characteristics:
- Static, compile-time known memory layout for parameters, activations, and temporaries — every buffer size is known when the code is generated; by default no allocator is needed (
--large-temp-storage auto-pool), as long as every runtime dimension has an--input-dim NAME<=Nbound and the temporaries' pool stays below 1 GiB - Large temporaries off the stack: temporaries above 1024 bytes share one pool at offsets planned at generation time, a
staticarray below 1 GiB and a heap buffer from<model>_load()above; temporaries whose uses do not overlap share memory, and runtime-sized ones take the room of their--input-dimbounds.--large-temp-storage malloc-scopedallocates each one on the heap right before its first use and frees it right after its last one instead;--large-temp-threshold 0, or compiling the generated code with-DEMX_LARGE_TEMPS_ON_STACK, keeps all of them on the stack - Memory report:
compileandverifyprint, and the header comment of the generated C file lists, the memory of the weights, the state arrays and the temporaries (heap peak, static, stack) and their total; runtime-sized buffers are counted at the--input-dim NAME<=Nbounds (seedocs/output-format.md) - Deterministic control flow (explicit loops, no hidden dispatch or callbacks)
- No OS dependencies, using only standard C headers (for example,
stdint.handstddef.h) - Single-threaded, non-reentrant execution model: sequence temporaries, Tokenizer buffers, state arrays and, by default (
--large-temp-storage auto-pool) and withstatic-poolorstatic, large temporaries havestaticstorage (withmalloc-pool, and withauto-poolfrom 1 GiB on, the pool is global as well), so a model function must not be entered again while a call of it is running (threads, interrupts, recursion). Calls of different models are independent. Weights loaded with<model>_load()must be loaded before the first call - Bitwise-stable code generation for reproducible builds
- Readable, auditable C code suitable for certification and code reviews
- Generated C output format spec:
docs/output-format.md - Operator-specific implementation notes:
docs/operator-notes.md - Designed for bare-metal and RTOS-based systems, up to embedded Linux and edge devices running SLMs
- Language models: the KV cache (and recurrent state such as convolution or Mamba states) is one persistent buffer per input/output pair (
--state-pair), sized for a bounded context and filled one call at a time; prefill and decode run on a runtime sequence length; weights and state go to the heap by themselves once the static data reaches 1 GiB (--weight-storage auto,--state-storage auto). See Persistent state (KV cache)
Current coverage highlights:
- ONNX opset 26 support for the standard operator set shipped with ONNX 1.21.0
- > 99% operator coverage in the generated support report at
SUPPORT_OPS.md - > 99% official ONNX backend model coverage in
ONNX_SUPPORT.md - > 99% ONNX Runtime-derived artifact coverage in
ONNX_SUPPORT.md - Listed on the official ONNX Backend Scoreboard
- Ten SLMs from 270M to 1.2B parameters compile end to end and are checked against ONNX Runtime: Qwen2.5, Qwen3, SmolLM2, Gemma 3, ERNIE 4.5, LFM2, Granite 4.0 H, TinyLlama and Llama 3.2, as 8-bit quantized exports with attention, convolution and Mamba layers (see the model zoo)
For PyTorch models, see the related project emx-pytorch-cgen.
Goals
- Correctness-first compilation with outputs comparable to ONNX Runtime.
- Deterministic and reproducible C code generation.
- Clean, pass-based compiler architecture (import → normalize → optimize → lower → emit).
- Minimal C runtime with explicit, predictable data movement.
- Scale from microcontroller networks to small language models in the billion-parameter range with the same guarantees: explicit memory, deterministic code, ONNX Runtime parity.
- Serve as the correctness-first ONNX front end for the emmtrix Edge AI Compiler, which takes this C code and optimizes it for a concrete target (see Usage Scenario 4).
Non-goals
- Aggressive performance optimizations in generated C (that is the job of the emmtrix Edge AI Compiler).
- Implicit runtime dependencies or dynamic loading.
- Training/backpropagation support.
Features
- CLI for ONNX-to-C compilation and verification.
- Deterministic codegen with explicit tensor shapes and loop nests.
- Minimal C runtime templates in
src/emx_onnx_cgen/templates/. - ONNX Runtime comparison for end-to-end validation.
- Full standard ONNX opset 26 support on top of ONNX v1.21.0.
- Auto-generated operator and model coverage tracking (see
SUPPORT_OPS.md,ONNX_SUPPORT.md, andONNX_ERRORS.md). - Broad support for ONNX Runtime test artifacts beyond the core standard operator set.
- Model zoo of ten SLMs from Hugging Face (Qwen, Llama, Gemma, Granite, LFM2, ...):
model-zoo/llms/downloads each at a pinned revision and compiles it with one command, up to its full context. - Supported data types:
bfloat16,float16,float,doublefloat8e4m3fn,float8e4m3fnuz,float8e5m2,float8e5m2fnuz,float8e8m0(stored asuint8_twith manual conversion to/fromfloat)float4e2m1(stored asuint8_twith manual conversion to/fromfloat)int2,uint2,int4,uint4(using C23_BitInttypes)int8,uint8,int16,uint16,int32,uint32,int64,uint64boolstring(fixed-size'\0'-terminated C strings; seedocs/output-format.md)sequence(<tensor type>)(fixed-capacity tensor sequences with presence/length metadata; seedocs/output-format.md)optional(<tensor type>)(optional tensors represented via an extra_Bool <name>_presentflag; seedocs/output-format.md)- Not supported:
complex64/complex128, and ONNXmap/sparse_tensor/opaquevalue types.
- Optional support for dynamic dimensions using C99 variable-length arrays (VLAs), when the target compiler supports them.
Usage Scenarios
1. Fully Embedded, Standalone C Firmware
The generated C code can be embedded directly into a bare-metal C firmware or application where all model weights and parameters are compiled into the C source.
Typical characteristics:
- No file system or OS required.
- All weights stored as
static constarrays in flash/ROM. - Deterministic memory usage, with no runtime allocation by default for static shapes and bounded runtime dimensions (large temporaries share one
staticpool;--large-temp-threshold 0or definingEMX_LARGE_TEMPS_ON_STACKkeeps them on the stack). - Suitable for:
- Microcontrollers
- Safety-critical firmware
- Systems with strict certification requirements
This scenario is enabled via --large-weight-threshold 0, forcing all weights to be embedded directly into the generated C code.
2. Embedded or Host C/C++ Application with External Weights
The generated C code can be embedded into C or C++ applications where large model weights are stored externally and loaded from a binary file at runtime.
Typical characteristics:
- Code and control logic compiled into the application.
- Large constant tensors packed into a separate
.binfile. - Explicit, generated loader functions handle weight initialization.
- Suitable for:
- Embedded Linux or RTOS systems
- Applications with limited flash but available external storage
- Larger models where code size must be minimized
This scenario is enabled automatically once the cumulative weight size exceeds --large-weight-threshold (default: 102400 bytes).
3. Small Language Models on Edge Devices
Small language models (SLMs), with up to a few billion parameters, compile to the same kind of C
code: a model function per step, the weights in a .bin file loaded by <model>_load(), and
the KV cache in persistent state buffers that stay valid between calls.
Tested are SLMs from 270M to 1.2B parameters (see the model zoo). Larger models are likely to work as well but are untested.
Typical characteristics:
- One call per token (decode) or per chunk of tokens (prefill,
--input-dim "sequence_length<=64"). - The context is a compile-time bound (
--input-dim "past_sequence_length<=N"); all buffers are sized for it, so memory use is known before the first token. - Once weights, static temporaries and state reach 1 GiB, the weights and the state (KV cache and recurrent
states) go to the heap (
--weight-storage autoand--state-storage auto, the defaults) and are allocated once by<model>_load();<model>_state_reset()starts a new conversation. - 8-bit quantized exports (
MatMulInteger,MatMulNBits,GatherBlockQuantized) and ONNX Runtime contrib attention (GroupQueryAttention,RotaryEmbedding) are supported. - Suitable for:
- Embedded Linux and edge devices with on-device assistants or command interfaces
- Hosts that need a self-contained, auditable C implementation of a language model
The model zoo lists the tested models and their compile arguments.
4. Target-Optimized Code Generation with the emmtrix Edge AI Compiler
In all of the above scenarios, the generated C code can serve as input to the emmtrix Edge AI Compiler, our source-to-source compiler that specializes portable C for a concrete embedded target while preserving functional correctness.
Examples of applied transformations include:
- Kernel fusion and loop restructuring (loop normalization, fusion, simplified control flow)
- Constant propagation, dead code elimination, and pointer resolution
- Memory layout optimization and buffer reuse
- Reduction of internal temporary memory
- Utilization of SIMD / vector instruction sets and dedicated accelerators
- Offloading of large weights to external memory
- Dynamic loading of weights or activations via DMA
Targets supported by the emmtrix Edge AI Compiler include Infineon AURIX TC4x TriCore, Arm Cortex-A (NEON/SVE), x86 (AVX), and RISC-V (RVV), with code emitted for toolchains such as TASKING SmartCode, Synopsys ARC MetaWare, GCC, and Clang.
This workflow allows a clear separation between:
- Correctness-first, deterministic ONNX lowering, and
- Target-specific performance and memory optimization,
while keeping the generated C code readable, auditable, and traceable.
The generated C code is intentionally structured to make such transformations explicit and analyzable, rather than relying on opaque backend-specific code generation.
Installation
Install the package directly from PyPI (recommended):
pip install emx-onnx-cgen
To use the verification workflow with ONNX Runtime, install the verification extra:
pip install "emx-onnx-cgen[verify]"
The pinned verification runtime is:
onnxruntime==1.27.0on Python 3.11+onnxruntime==1.23.2on Python 3.10
Minimum Python version: 3.10.
Standalone binaries and SBOMs
Each GitHub release also
ships standalone bundles that need no Python installation
(emx-onnx-cgen-linux-amd64.tar.gz, emx-onnx-cgen-windows-amd64.zip).
Every release asset comes with a CycloneDX 1.6 SBOM
(software bill of materials):
| Release asset | SBOM |
|---|---|
emx-onnx-cgen-linux-amd64.tar.gz |
emx-onnx-cgen-linux-amd64.cdx.json |
emx-onnx-cgen-windows-amd64.zip |
emx-onnx-cgen-windows-amd64.cdx.json |
emx-onnx-cgen-bundles.tar.gz (both bundles) |
emx-onnx-cgen-bundles.cdx.json |
| PyPI wheel | emx-onnx-cgen-wheel.cdx.json |
emx-onnx-cgen-bundles.tar.gz contains both bundles of the same build, in
emx-onnx-cgen/linux-amd64/ and emx-onnx-cgen/windows-amd64/. Its SBOM
lists each component once, together with the platforms that ship it.
The bundle SBOMs list every file of the bundle with its SHA-256, under the
component it belongs to. The combined archive also carries its SBOM inside, as
emx-onnx-cgen/emx-onnx-cgen.cdx.json. Only the SBOM next to the archive holds
the archive's own hash; the one inside cannot.
tools/verify_bundle.py checks an unpacked bundle
against its SBOM. It needs only the Python standard library:
python tools/verify_bundle.py --sbom emx-onnx-cgen/emx-onnx-cgen.cdx.json --root emx-onnx-cgen
Both bundles are built with the same CPython build from
python-build-standalone,
pinned in tools/release_python.json.
The bundle SBOMs list everything the bundle contains:
- the Python packages
- the CPython interpreter and the libraries compiled into it, such as OpenSSL
- the Microsoft C/C++ runtime on Windows
- the system libraries (as rpm packages) on Linux
- the vendored
stb_image
The asset's SHA-256/SHA-512 hashes are part of the SBOM. See
docs/development.md
for how they are generated.
Development
For local setup, testing, and contributor workflows, see docs/development.md.
Quickstart
Compile an ONNX model into a C source file:
emx-onnx-cgen compile path/to/model.onnx build/model.c
Verify an ONNX model end-to-end against ONNX Runtime (default):
emx-onnx-cgen verify path/to/model.onnx
Models that require extra representative inputs to resolve dynamic shapes are not supported for code generation. Export them with static shapes instead.
--test-data-dir is verification input/output data only. It does not change the
generated C code.
Use emx-onnx-cgen as an importable ONNX backend:
import onnx
from onnx.backend import prepare
import emx_onnx_cgen.onnx_backend as emx_backend
model = onnx.load("path/to/model.onnx")
rep = prepare(model, backend=emx_backend)
outputs = rep.run(inputs)
The backend module is emx_onnx_cgen.onnx_backend. It compiles the ONNX model
to C on demand, builds a temporary executable, and runs that executable through
the standard ONNX backend interface.
You can also call it directly without onnx.backend.prepare:
import onnx
from emx_onnx_cgen.onnx_backend import run_model
model = onnx.load("path/to/model.onnx")
outputs = run_model(model, inputs)
CLI Reference
emx-onnx-cgen provides two subcommands: compile and verify.
Common options
These options are accepted by both compile and verify:
-
--model-base-dir: Base directory for resolving the model path (and related paths). -
--color: Colorize CLI output (auto,always,never; default:auto). -
--verbose/-v: Enable verbose logging (includes codegen timing). -
--truncate-weights-after: Truncate inline weight initializers afterNvalues and insert...placeholders. -
--large-weight-threshold: Store weights in a binary file once the cumulative byte size exceeds this threshold (default:102400; set to0to disable). -
--weight-storage: Storage of the weights in the binary file:auto(default),static(global arrays) ormalloc(global pointers to heap buffers that<model>_load()allocates and fills and<model>_unload()frees, for weights above the 2 GB of static data a Windows executable can hold).autoisstatic, ormalloconce the static data (weights, static temporaries and state) reaches 1 GiB. Weights written into the C source stayconstarrays. Heap weights exist only after<model>_load(); without it the model function returns without computing. -
--large-temp-threshold: Move buffers larger than this byte threshold off the stack: model temporaries are heap-allocated (viamalloc/free) or, with--large-temp-storage staticorstatic-pool,staticif their size is fixed; sequence temporaries and testbench input/output buffers becomestatic; smaller buffers stay on the stack (default:1024; set to0to keep all buffers on the stack). The generated code keeps the stack variant of every such buffer behind#ifdef EMX_LARGE_TEMPS_ON_STACK, so compiling it with-DEMX_LARGE_TEMPS_ON_STACKhas the same effect as--large-temp-threshold 0. -
--large-temp-storage: Storage of model temporaries above--large-temp-threshold:auto-pool(default;static-pool, ormalloc-poolwhen the pool reaches 1 GiB, so that large models need no gigabytes of static data;<model>_unload()exists either way),static-pool(onestaticarray reserved for the whole program run, no allocator; temporaries are pointers to offsets in it planned at generation time, temporaries whose uses do not overlap share memory, and a runtime-sized one gets the room of its--input-dim NAME<=Nbounds),malloc-pool(the same pool, allocated once by<model>_load()and freed by<model>_unload()),malloc-scoped(every temporary is allocated right before its first use and freed right after its last one, so the peak is the largest set of temporaries alive at the same time),malloc(all of them allocated at the start of every call and released before it returns, so the peak is their sum) orstatic(onestaticarray each, no allocator needed for static shapes). Seetests/golden/large_temp_<storage>_model.cfor the same model in each storage. Outside the pools, runtime-sized temporaries above the threshold usemalloc, measured at their--input-dim NAME<=Nbounds; without a bound their size is unknown and they always do (with--large-temp-threshold 0they stay on the stack as VLAs). Sequence temporaries and testbench buffers staystatic. -
--restrict-arrays/--no-restrict-arrays: Enable or disablerestrictqualifiers on generated array parameters. Whatrestrictpromises, what it is worth (about 5x in one TinyLlama decode measurement with gcc; some compilers ignore it) and which compilers act on it: The restrict Keyword (emmtrix Wiki). -
--share-node-functions identical|off:identical(default) lets nodes whose kernel code is the same (apart from the node comment and the function name) call one shared node function,offemits one function per node. Seedocs/node-functions.md. -
--inline-node-functions auto|always|none|noinline: whether the node functions are declaredinline(always), without an inline specifier (none, the compiler decides) or withEMX_NOINLINE, the compiler's noinline attribute (noinline), so that gcc does not merge all kernels of a large model into one huge model function.auto(default) isalwaysbelow 1000 nodes (the ops of the lowered model, after constant folding and inlined subgraphs) andnoinlinefrom there on. Seedocs/node-functions.md. -
--fp32-accumulation-strategy: Accumulation strategy for float32 inputs (simpleuses float32,fp64uses double; default:simple). -
--fp16-accumulation-strategy: Accumulation strategy for float16 inputs (simpleuses float16,fp32uses float; default:fp32). -
--explicit-padding off|internal|all: Move the padding ofConv,FusedConv,ConvIntegerandQLinearConvinto an explicitPadin front of the operator, so that the convolution kernel runs on the padded tensor without a bounds check in its innermost loop. The generated code is usually faster (compilers unroll and vectorize the kernel), at the cost of one additional temporary per padded convolution.alldoes this for every padded convolution,internalonly for convolutions whose input the model computes: the padded copy of a graph input is an extra buffer that no later step can avoid, since the caller owns the input.offkeeps the padding (default). -
--replicate-ort-bugs: Compatibility switch for verification/debugging. Enables emulation of known behavior differences of the ONNX Runtime version pinned inrequirements-ci.txt. -
--sequence-element-shape: Declare rank and per-axis maxima for sequence inputs with variable element shapes. -
--image-decoder-libs: Comma-separated priority list of decoding libraries backing theImageDecoderoperator (default:stb). The generated C code detects the image format at runtime via magic bytes and dispatches to the decoder assigned to that format; the first listed library that supports a format wins. Known libraries:stb(bundledstb_image.h, emitted next to the generated C file; supportsbmp,jpeg,png,pnm),libjpeg-turbo(jpeg, bit-exact with the ONNX reference outputs — stb's JPEG decoder is not),libwebp(webp),libtiff(tiff), andopenjpeg(jpeg2000). Non-stb libraries require their system development packages and add linker flags to the build (for example-ljpeg);verifyapplies them automatically,compilereports them. Inputs in a format without a configured decoder produce a zero-filled output tensor at runtime. -
--input-value NAME=VALUE: Pin a graph input to a constant (a number, or[v0,v1,...]for a static shape), e.g.--input-value num_logits_to_keep=1for LFM2, whose logits are sliced by that value. The input gets the value as its ONNX default, so the model function no longer takes it and shapes that depend on it become static; dims named after a pinned integer scalar take its value.verifychecks that the test data holds the same value. Repeatable. -
--input-dim: Pin a dynamic input dimension to a fixed value so the generated code uses a static array extent instead of a runtime parameter. Repeatable. Use a dim-parameter name (--input-dim batch=1) to fix every axis carrying that name across the graph, or an input position (--input-dim images:0=1) to fix a single axis.--input-dim NAME<=Nkeeps a dimension dynamic but declares an upper bound (see Dynamic shapes).--input-dim NAME>=Nor--input-dim N<=NAME<=Madds a lower bound (e.g.1<=sequence_length<=64, so thathidden[:, -1:]of a prefill has length 1); the model function returns early below it.--input-dim NAME=EXPRESSIONstates that a dimension is an expression of other dynamic input dimensions, e.g.--input-dim total_sequence_length=past_sequence_length+1for an ORT GenAI decode step, or just another dim name (total_sequence_length=sequence_lengthfor a prompt without past); every axis with that name gets the expression. The CLI prints the model's dynamic input dimensions as part of the model report; a fixed dimension is shown inline asin0[0]=batch -> 4.Pinning happens immediately after the model is loaded and before shape inference, so the fixed value propagates through the rest of the graph. This has three consequences worth knowing:
- Avoiding C99 VLAs: by default a dynamic dimension is emitted as a runtime parameter and the buffers become C99 variable-length arrays (e.g.
const float in[batch][3][4]). Some targets cannot use these — MSVC does not support VLAs at all, C11 makes them optional (__STDC_NO_VLA__), and safety-critical guidelines such as MISRA C forbid them because their stack usage is unbounded and not statically analyzable. Pinning the dimension with--input-dimturns the extent into a compile-time constant, so the generated code is plain fixed-size arrays portable to any C compiler. - Resolving dynamic-shape problems: if a model otherwise fails to generate static C because an input dimension is symbolic or unknown (
tensor 'X' has dynamic dimensions), pinning that input makes it concrete and lets shape inference derive the dependent intermediate and output shapes. (This only helps for dimensions derived from the input dimension; shapes computed from runtime tensor values, e.g.AffineGrid'ssize, are recovered separately and are unaffected by--input-dim.) - Possible inconsistencies:
--input-dimonly checks that the target is a dynamic input dimension; it does not validate that the chosen value is consistent with the rest of the graph. Contradictory or partial pinning can therefore make a model that previously stayed dynamic fail during shape inference or lowering — for example pinning two operands of anAddto incompatible extents (--input-dim a:0=3 --input-dim b:0=5→ "Broadcasting mismatch"), or pinning only one of two axes that an operator requires to be equal. Such failures are reported as a normal error, not a crash. Nameddim_params are always pinned graph-wide, so--input-dim batch=Nstays consistent by construction; the risk is mainly with the positional form on unnamed (?) axes.
- Avoiding C99 VLAs: by default a dynamic dimension is emitted as a runtime parameter and the buffers become C99 variable-length arrays (e.g.
-
--state-pair INPUT=OUTPUT: Short-circuit a graph input with a graph output of the same shape and dtype, e.g. a KV cache (--state-pair past_k_0=new_k_0). A cache that grows byConcatorcom.microsoft.GroupQueryAttention(past[..., n, ...] -> present[..., n + 1, ...], orn + sfor a prefill with--input-dim s<=S) is supported too whennhas an upper bound (--input-dim n<=N); its buffer then has capacityN + 1(N + S). Repeatable or comma-separated. A pair with*is a pattern:--state-pair "past_key_values.*=present.*"pairs every graph input that matches with the output that gets the same*parts (each*matches one or more characters, also dots;*is reserved for patterns, a tensor name with a literal*cannot be paired), in graph input order. Replaces the pairs from the model metadata keyemx_onnx_cgen.state_pairs(same syntax). See Persistent state (KV cache). -
--no-state-pairs: Ignore the state pairs declared in the model metadata and keep separate input/output buffers. -
--state-storage: Storage of the state arrays:auto(default),static(global arrays) ormalloc(global pointers to zeroed heap buffers that<model>_load()allocates and<model>_unload()frees, for states too large for static data, e.g. a KV cache above the 2 GB a Windows executable can hold).autoisstatic, ormalloconce the static data (weights, static temporaries and state) reaches 1 GiB. Heap state exists only after<model>_load(); without it the model function returns without computing, also for a model without a weight file. See Persistent state (KV cache). -
--state-steps: Number of consecutive model calls the testbench of a model with state pairs runs (default:3). Only affects the testbench.
Persistent state (KV cache)
Step-wise models (e.g. a decoder step) take their state as a graph input and
return the updated state as a graph output. With --state-pair, both share
one buffer that persists across calls instead of being copied in and out on
every call:
emx-onnx-cgen compile decoder_step.onnx decoder_step.c \
--state-pair past_k_0=new_k_0 --state-pair past_v_0=new_v_0
The paired input and output disappear from the entry point; each pair becomes
a global state array <model>_state_<input>:
float model_state_past_k_0[4][128][24]; /* state: past_k_0 -> new_k_0 */
float model_state_past_v_0[4][128][24]; /* state: past_v_0 -> new_v_0 */
void model_state_reset(void); /* zero-fills the state */
void model(const int64_t pos[restrict 1], ...);
A cache that grows by one entry per call (present = Concat(past, new), as in
the Qwen2.5 ONNX exports) gets a buffer with a fixed capacity on the growing
axis; give the length an upper bound:
emx-onnx-cgen compile model.onnx --input-dim batch_size=1 --input-dim sequence_length=1 --input-dim "past_sequence_length<=255" --state-pair "past_key_values.*=present.*"
The caller passes the current length (int past_sequence_length) as before;
the state array is float model_state_past_key_values_0_key[1][2][256][64] and each
call only writes the new row. See docs/state-aliasing.md.
ORT GenAI exports (e.g. onnx-community/Qwen3-0.6B-ONNX) append in
GroupQueryAttention and give present its own length total_sequence_length;
state that it is the past length plus the new token:
emx-onnx-cgen compile model.onnx --input-dim batch_size=1 --input-dim sequence_length=1 --input-dim "past_sequence_length<=255" --input-dim "total_sequence_length=past_sequence_length+1" --state-pair "past_key_values.*=present.*"
For a prefill (several prompt tokens per call), keep sequence_length a
runtime dimension with a bound; the capacity is then the sum of both bounds
([255 + 64]) and the model function takes int sequence_length as well:
emx-onnx-cgen compile model.onnx --input-dim batch_size=1 --input-dim "sequence_length<=64" --input-dim "past_sequence_length<=255" --input-dim "total_sequence_length=past_sequence_length+sequence_length" --state-pair "past_key_values.*=present.*"
Some exports branch between a decode step and a prompt with an
If(sequence_length == 1) (the Mamba layers of Granite 4.0 H). The import keeps
only the branch that the dims decide: sequence_length=1 picks decode, a lower
bound of 2 or more picks the prompt branch. Granite's prompt branch starts from
an empty state and pads the prompt to chunks of 256, so it is compiled on its own
with --input-dim "4<=sequence_length<=256" --input-dim total_sequence_length=sequence_length (within these bounds every padded length
is 256; from 4 tokens on, the conv state needs no padding).
model_state_reset(); /* start of a sequence */
for (int64_t pos = 0; pos < n; ++pos) {
model(...); /* reads and updates model_state_past_k_0 */
}
The state arrays are static globals unless the static data gets large. A
state too large for static data (Qwen3-0.6B with its full 40960-token context
has 9.4 GB of KV cache, more than the 2 GB of static data a Windows executable
can hold, even with -mcmodel=large) goes on the heap: by default
(--state-storage auto) once weights, static temporaries and state together
reach 1 GiB, or always with --state-storage malloc. Each
state is then a restrict global pointer, indexed like the array,
float (*restrict model_state_past_key_values_0_key)[8][40960][128];, that
model_load() points at a zeroed allocation and model_unload() frees.
Call model_load() before model_state_reset() and the first call; without
it the model function returns without doing anything. Indexing the state works
as before, but sizeof(model_state_x) is now the size of a pointer; one state
takes rows * sizeof(*model_state_x) bytes, the rows being the first extent of
the array type that the comment of the declaration gives. Because of
restrict, access the state through the global and keep no copy of the
pointer across calls.
The state has static storage, so a model with state pairs is not
reentrant: one program runs one sequence of it at a time, and calls must not
overlap (threads, interrupts). The arrays are ordinary globals: place them with
the linker, e.g. in large slow memory instead of the small vector memory (with
-fdata-sections, each array has its own section .bss.model_state_past_k_0).
The pairs are never inferred from names. The compiler checks that both sides
have the same static shape and dtype, and that no node reads the old state
after the new state was written (same-index elementwise updates and
TensorScatter writing its own past_cache are fine). Otherwise it stops with
an error naming the node; it never falls back to a copy. A TensorScatter on a
state buffer only writes the updated rows (no full-cache copy). verify runs
the original model --state-steps times, feeding the state outputs back as
inputs, and compares every step against the generated code running on the
shared buffer. Design notes: docs/state-aliasing.md.
compile
emx-onnx-cgen compile <model.onnx> [output.c] [options]
Options:
--model-name: Override the generated model name (default: output file stem).--emit-testbench: Emit a JSON-producingmain()testbench for validation.--testbench-output-format: Choose the generated testbench output format (json,txt,txt-emmtrix, ortxt-emmtrix:<float>).--testbench-file: Emit the testbench into a separate C file at the given path (implies--emit-testbench). If not set, the testbench is embedded in the main output C file (legacy behavior).--emit-data-file: Emit constant data arrays into a companion_dataC file.--shape-inference-json: Write a JSON report of the shape inference results to the given path. For every named tensor of the model — inputs, outputs, and internal node outputs — the report contains the shape declared in the model file (model, withdim_paramnames andnullfor unknown dims) and the shape computed by the compiler (inferred). Weight initializers and compiler-internal temporary names are excluded, so the file is stable across runs and can be used as a shape reference. Shapes reflect the model after--input-dimpinning. See the golden test referencetests/golden/mixed_ops_dynamic_batch_shapes.jsonfor an example report.
verify
emx-onnx-cgen verify <model.onnx> [options]
Options:
--cc: Explicit C compiler command for building the testbench binary.--sanitize: Enable sanitizer instrumentation when compiling the verification binary (-fsanitize=address,undefined). IfEMX_ENABLE_SANITIZEis set, it overrides this flag.--per-node-accuracy: Also compare intermediate tensor outputs and print max error per node.--test-data-dir: Seed verification inputs frominput_*.pbfiles instead of generating random testbench inputs.--test-data-inputs-only: Read onlyinput_*.pbfrom--test-data-dirand still compare outputs against the selected runtime.--max-ulp: Maximum allowed ULP distance for floating outputs (default:100).--atol-eps: Absolute tolerance as a multiple of machine epsilon for floating outputs (default:1.0).--runtime: Runtime backend for verification (onnxruntimeoronnx-reference, default:onnxruntime).--expected-checksum: Exit early withCHECKSUMwhen the generated C checksum matches the expected SHA-256.--replicate-ort-bugs: Verification-only compatibility mode to reproduce known behavior differences of the ONNX Runtime version pinned inrequirements-ci.txt.--temp-dir-root: Root directory in which to create a temporary verification directory (default: system temp dir).--temp-dir: Exact directory to use for temporary verification files (default: create a temporary directory).--keep-temp-dir: Keep the temporary verification directory instead of deleting it.
How verification works:
- Compile with a testbench: the compiler is invoked with
--emit-testbench, generating a C program that runs the model and prints inputs/outputs as JSON. - Build and execute: the testbench is compiled with the selected C compiler
(
--cc,CC, or a detectedcc/gcc/clang) and executed in a temporary directory. - Run runtime backend: the JSON inputs from the testbench are fed to the
selected runtime (
onnxruntimeoronnx-reference) using the same model. The compiler no longer ships a Python runtime evaluator. - Compare outputs: floating outputs are compared by maximum ULP distance. Floating-point verification first ignores very small differences up to --atol-eps × machine epsilon of the evaluated floating-point type, treating such values as equal. For values with a larger absolute difference, the ULP distance is computed, and the maximum ULP distance is reported; non-floating outputs must match exactly. Missing outputs or mismatches are treated as failures.
- ORT unsupported models: when using
onnxruntime, if ORT reportsNOT_IMPLEMENTED, verification is skipped with a warning (exit code 0).
Troubleshooting
Common problems and how to resolve them.
Dynamic shapes and shape-inference failures
A model whose inputs have dynamic dimensions (a symbolic dim_param such as
batch, or a fully unknown axis) is compiled with those axes as C99
variable-length-array runtime parameters by default, e.g.
void model(int batch, const float in[batch][3][4], ...). The model report
lists what is dynamic:
Dynamic input dimensions (1): in[0]=batch
Avoiding VLAs: even when the dynamic build succeeds, the runtime-parameter
form relies on C99 variable-length arrays. If your toolchain cannot use them —
MSVC has no VLA support, C11 makes them optional (__STDC_NO_VLA__), and
MISRA C / safety-critical guidelines forbid them due to unbounded stack usage —
pin the dimensions with --input-dim (below) so the generated code uses plain
fixed-size arrays instead.
Dynamic input dimensions are also the root cause of a whole family of failures, because the code generator (and ONNX shape inference itself) often cannot resolve the rest of the graph while an input axis is still symbolic. These surface in several different ways, for example:
Code generation requires static shapes. Reason: tensor 'X' has dynamic dimensions ...— a dynamic dimension reaches a place that needs a concrete size (a buffer, a reshape, ...).ONNX shape inference failed— inference cannot make progress with the unresolved input shapes.- Operator-specific lowering errors that mention
-1/dynamic extents, unresolvedReshape/MatMul/broadcast shapes, or a shape that "could not be inferred".
The general fix is to make the input shapes concrete before shape inference
runs, by pinning the dynamic dimensions with --input-dim.
Because pinning happens before inference, the fixed values propagate through the
graph and usually let inference resolve everything downstream:
# Fix every axis named "batch" graph-wide:
emx-onnx-cgen compile model.onnx --input-dim batch=1
# Or fix a single axis positionally (use this for unnamed "?" axes):
emx-onnx-cgen compile model.onnx --input-dim images:0=1
Caveats:
--input-dimonly helps for dimensions derived from the pinned input dimension. Shapes computed from runtime tensor values (e.g.AffineGrid'ssize) are recovered automatically and are not affected by--input-dim.- It is a sharp tool:
--input-dimonly checks that the target is a dynamic input dimension, not that the chosen value agrees with the rest of the graph. Contradictory or partial choices can therefore introduce shape-inference or lowering failures (e.g. pinning two operands of anAddto incompatible extents reports a "Broadcasting mismatch"). Nameddim_params are pinned graph-wide and stay consistent by construction; the risk is mainly the positional form on unnamed (?) axes.
Named dimensions that pass through shape values: decoder exports such as
Qwen2.5 compute shapes from values (Range(0, Shape(mask)[1]),
Slice(x, 0, Shape(x)[1]), Where(shape == -1, 1, shape) for Expand).
ONNX shape inference loses the named dimension there; the compiler evaluates
this shape arithmetic symbolically and keeps the input's dim_param, so such
models compile with the dimension as a runtime parameter. A dim_param that is
an expression of another one (past_sequence_length + 1) is no parameter of
its own but the C expression (past_sequence_length + 1); the same holds for
dims derived inside the graph (Reshape(x[1, s, 2048], [0, -1, 128]) has
(16*s) rows). A dim whose name is also a kernel's local variable (n, s,
p, batch, ...) is called <name>_dim in C. When the arithmetic
contains a Min/Max that depends on the size, e.g. a 32768-row rotary table
sliced to the current length, declare the largest size:
emx-onnx-cgen compile model.onnx --input-dim batch_size=1 --input-dim sequence_length=1 --input-dim "past_sequence_length<=32767"
The generated code relies on the bound: the model function returns early
without writing its outputs when a runtime dimension is negative or above its
declared bound. See docs/dynamic-dim-params.md for the design.
Data-dependent output lengths: an output whose length depends on the input
values (e.g. the unique count of Unique, declared as an unknown axis) is
emitted as a buffer of the static upper bound plus an idx_t *<output>__dim_<axis>
parameter that receives the actual length at runtime; see
docs/output-format.md.
This works for graph outputs; a node that consumes such a tensor inside the
graph is rejected.
Sparse tensor inputs: a sparse_tensor graph input (currently for
com.microsoft.SparseToDenseMatMul) is passed in COO form as <name>_values,
<name>_indices and the entry count <name>_nnz; see
docs/output-format.md.
"Code generation requires explicit ragged-sequence bounds"
A sequence input with variable element shapes needs explicit per-axis maxima.
Declare them with --sequence-element-shape, e.g.
--sequence-element-shape boxes=[<=100,4].
"No C compiler found" (verify)
verify builds and runs a testbench, so it needs a C compiler. Provide one via
--cc, the CC environment variable, or install a cc/gcc/clang on PATH.
Official ONNX test coverage
emx-onnx-cgen tracks support using generated coverage reports checked into the repository and is listed on the official ONNX Backend Scoreboard.
-
Standard ONNX operator support:
SUPPORT_OPS.mdconsistently reports > 99% verified operator coverage. The remaining unsupported entry is the non-standard contrib operatorcom.microsoft::SparseToDenseMatMul. -
Official ONNX backend models:
ONNX_SUPPORT.mdreports > 96% verified ONNX file coverage against ONNX 1.23.2. -
ONNX Runtime artifact corpus:
ONNX_SUPPORT.mdalso reports > 99% verified coverage for the exported ONNX Runtime artifact set. -
ONNX_SUPPORT.md: overview of ONNX models and their current verification status. -
ONNX_ERRORS.md: summary of the most common verification outcomes and failure reasons. -
SUPPORT_OPS.md: list of ONNX operators and whether they are currently supported, with links to operator-specific implementation notes and relevant CLI options.
Related Projects
- emmtrix Edge AI Compiler
Source-to-source compiler that turns the portable C generated here into target-optimized C for embedded processors (kernel fusion, SIMD/vector intrinsics, memory-footprint reduction).
https://www.emmtrix.com/tools/emmtrix-edge-ai-compiler - emx-pytorch-cgen
A PyTorch-to-C compiler following the same design principles as emx-onnx-cgen, but operating directly on PyTorch models instead of ONNX graphs.
https://github.com/emmtrix/emx-pytorch-cgen - onnx2c
An ONNX-to-C code generator with a different design focus and code generation approach.
https://github.com/kraiskil/onnx2c
Supporting Projects
- emx-regex-cgen
A regex-to-C code generator used to implement the ONNXRegexFullMatchoperator in emx-onnx-cgen.
https://github.com/emmtrix/emx-regex-cgen - emx-ort-test-artifacts
Repository containing exported ONNX test artifacts (*.onnx/*.pbfiles) produced by the ONNX Runtime test infrastructure.
https://github.com/emmtrix/emx-ort-test-artifacts
Maintained by
This project is maintained by emmtrix Technologies GmbH.
Metadata
Release files for emx-onnx-cgen 1.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| emx_onnx_cgen-1.5.0.tar.gz | 2.2 MB | With provenance | Details for emx_onnx_cgen-1.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| emx_onnx_cgen-1.5.0-py3-none-any.whl | Python 3 | none | any | Details for emx_onnx_cgen-1.5.0-py3-none-any.whl |
Total release size: 3.0 MB
Release files / emx_onnx_cgen-1.5.0.tar.gz
| Download URL | emx_onnx_cgen-1.5.0.tar.gz |
|---|---|
| Size | 2.2 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e716eeda73ddc2545aa6e00d789118f8c575302dc6bda5c7ba02b053c9f96407
|
|
BLAKE2b-256 checksum How to use checksums |
5a0946ac3c984872719fa1b9a2f88fc56ca436ed40f919bd969eabcfeb031503
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logRelease files / emx_onnx_cgen-1.5.0-py3-none-any.whl
| Download URL | emx_onnx_cgen-1.5.0-py3-none-any.whl |
|---|---|
| Size | 818.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
062207e922392290dd062b450e4731874e498f6479e4006ee53db3d8bea501df
|
|
BLAKE2b-256 checksum How to use checksums |
a4d1ad445146b4c85e36c1552650bab32aade91febb287b0ee7369a635445618
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logSecurity for emx-onnx-cgen 1.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for emx_onnx_cgen-1.5.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.