1 Parse
A hand-rolled protobuf wire reader builds the graph. Unsupported ops fail loudly; a truncated or over-rank tensor is refused, never quietly reshaped.
C11 · zero dependencies · MIT
A neural-network inference runtime in 222 KB of C11, with zero dependencies.
It parses ONNX protobufs with its own wire parser, plans activation memory with its own lifetime-aware allocator, and runs hand-written kernels. No BLAS. No protobuf library. No SIMD wrapper. Nothing but libc.
The claim
Those numbers are measured, not estimated, and every one of them has a command on this page that reproduces it.
| Ferrite | ONNX Runtime | |
|---|---|---|
| Binary | 222 KB stripped | 18.4 MB onnxruntime.dll |
| Dependencies | none | many |
| MNIST accuracy | 97.52% (9752/10000) | same model, same weights |
| Latency, 1 thread | 2.42 ms | 1.06 ms |
| Agreement | max_abs ≈ 1e-8, 3 of 7 models bit-exact | reference |
Ferrite is not trying to beat ONNX Runtime. It is trying to show how much of a modern inference runtime you can rebuild from first principles and still land on the same numbers.
Proof
A model trained in PyTorch, exported to ONNX, and executed here by C code that shares nothing with PyTorch or ONNX Runtime.
++@@##..
..@@@@@@==
..##@@@@@@==
==##@@@@@@@@**==::
@@@@@@@@@@@@@@@@%%::
**@@@@@@@@@@%%%%@@@@@@
::%%@@@@@@@@++--::++@@@@==
..%%@@@@@@%%++ ..%%@@@@==
..@@@@@@##.. ==@@@@@@..
..@@@@##.. ..##@@@@..
Ferrite says: 0 (100.0% confident) truth: 0 OK
0.286 ms
---------------------------------------------
10/10 correct on the embedded samples
0.286 ms/inference (mean of 10)
model load 0.6 ms
weights 398 KB
activations 1.5 KB peak
dependencies none
1.5 KB of activation memory for the whole forward pass — and that last line is printed by the program itself.
Train, export, run, and score the full 10,000-image test set:
pip install torch # torchvision not required
python tools/train_mnist.py # trains, reports 97.52%, writes tests/mnist.onnx
cmake --build build --target mnist_eval
./build/mnist_eval tests/mnist.onnx build/mnist-data/test_images.bin build/mnist-data/test_labels.bin
Ferrite MNIST accuracy: 97.52% (9752/10000)
0.303 ms/image over the full test set
3300 images/s single-threaded
activations 1.5 KB peak
Ferrite's accuracy matches PyTorch's to the image. That is Ferrite's own measurement over all 10,000 test images — not a number copied from the training script.
Architecture
An .onnx file goes in; a flat array of kernel calls comes out.
A hand-rolled protobuf wire reader builds the graph. Unsupported ops fail loudly; a truncated or over-rank tensor is refused, never quietly reshaped.
Shape inference → simplify → constant-fold → Conv+BN fusion → CSE → dead-code elimination.
Lifetime analysis assigns every activation an offset into one buffer. AcousticLeakNet's 32 MB of weights run in 896 KB of activations, 22% below a naive allocation.
Every node is resolved to a kernel pointer once. A same-shape rerun does zero re-analysis: no dispatch switch, no re-planning, just a walk down a flat array.
Every activation has a birth and a death. The planner walks tensors in order of first use and greedily drops each one into the smallest already-freed slot it fits in, extending the high-water mark only when nothing fits. Tensors whose lifetimes never overlap share the same bytes.
A tensor is a strided view, not a buffer. Transpose and reshape rewrite strides; they never touch the data.
typedef struct {
void *data;
FeDtype dtype;
int ndim;
int shape [FERRITE_MAX_DIMS];
int strides[FERRITE_MAX_DIMS]; /* in elements, not bytes */
size_t nbytes;
bool owns_data;
} FeTensor;
Memory is a bump arena. A weight arena, allocated once at load and never reset. An activation arena, reset after every inference.
typedef struct {
unsigned char *base;
size_t size;
size_t offset; /* current bump pointer */
size_t peak; /* high-water mark */
} FeArena;
There is no malloc on the inference path.
The layers
| Layer | Contents |
|---|---|
core/ | strided tensors, arena allocator, serialization, FP16/BF16, platform seam |
graph/ | computation-graph IR, tensor registry, Kahn topological sort |
ops/ | matmul/linear, elementwise, activations, GEMM, conv1d/conv2d (im2col), norms, pooling, attention |
simd/ | AVX2 tiled matmul + elementwise behind runtime CPUID, scalar fallback |
planner/ | tensor-lifetime analysis + greedy buffer reuse |
optim/ | shape inference, folding, fusion, CSE, DCE |
runtime/ | the engine and its static execution plan |
importer/ | the ONNX protobuf parser |
quantization/ | symmetric INT8/INT16, per-tensor and per-channel, dynamic and static |
compiler/, parallel/ | linear IR; thread pool + row-parallel GEMM (both opt-in) |
Dependencies point downward only.
Constraints
Kernels never malloc. Only fe_conv1d allocates, and it frees its scratch after use.
Transpose and reshape rewrite strides. They never copy data.
Two arenas, two lifetimes. Freeing an inference is a single pointer reset.
The naive matmul is kept deliberately, as the oracle that validates the AVX2 kernel. Don't optimize it away.
The git history shows one subsystem per commit, each with its own test.
An unsupported op, an over-rank tensor, a truncated field — all return an error naming the problem. Nothing is silently dropped, truncated, or skipped.
Zero dependencies. Ferrite links libc and nothing else. A pull request that adds a third-party library — however good — will be declined, because the absence of dependencies is the project. CONTRIBUTING.md
Verification
Being small is worthless if the numbers are wrong.
Ferrite is checked against ONNX Runtime on every push:
pip install onnxruntime onnx numpy
python tools/golden_gen.py
python tools/golden_compare.py --run-model build/run_model
Seven models — MLP, mini-CNN, Conv+BN fusion, LayerNorm MLP, MNIST, and a
real 32 MB 1D-CNN — run through both runtimes with identical seeded input.
Worst observed disagreement is max_abs ≈ 1e-8; three models are
bit-exact.
ASan and UBSan are on by default, and a dedicated CI leg fails the build if they are ever silently dropped.
libFuzzer against the ONNX wire reader with a persistent corpus. Every truncated prefix and random byte flip either loads cleanly or fails loudly — no crash, no hang.
A test deliberately triggers every documented FE_ERR_* path across the public API and asserts outputs are untouched on failure.
A coverage floor and a perf gate diffing against a committed per-CPU baseline, alongside a cross-compile leg that runs the full suite under QEMU.
Measurements
cmake -S . -B build-release -G Ninja -DCMAKE_BUILD_TYPE=Release -DFERRITE_SANITIZE=OFF
cmake --build build-release --target bench_model
./build-release/bench_model
python tools/bench_onnxruntime.py # the same model, same input, same timing
On AcousticLeakNet (AMD Ryzen 5 5600, single-threaded):
| Ferrite | ONNX Runtime | |
|---|---|---|
| Latency | 2.42 ms | 1.06 ms |
| Binary | 222 KB | 18.4 MB |
ONNX Runtime is faster, and that is the expected result — it is a mature runtime with years of kernel tuning behind it. Ferrite's claim is that you can get within ~2.3× of it, numerically identical, in 1/83rd the binary and with no dependencies at all.
Against Ferrite's own scalar reference:
| Kernel | naive | AVX2 | ratio |
|---|---|---|---|
| MatMul 256³ | 6.92 ms | 1.45 ms | 4.78× |
| Elementwise add, 1M floats | 0.75 ms | 0.19 ms | 3.92× |
| GEMM base vs scalar transB | 22.09 ms | 1.41 ms | 15.65× |
On the [1 × 65536 × 128] GEMV in AcousticLeakNet, the tiled
AVX2 kernel is 0.4× — slower than scalar, because a
single output row gives the packing cost nothing to amortize against. The
dispatcher routes M == 1 to scalar for exactly this reason.
Portability
ARMv6 hard-float cross build. The full test suite runs under QEMU in CI — nothing to flash.
cmake -S . -B build-pi -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/raspberry-pi-zero-w.toolchain.cmake
cmake --build build-pi
ctest --test-dir build-pi
An ESP-IDF component compiling the device runtime only: scalar kernels, planner, engine, quantization. The ONNX parser is compiled out.
cd idf/demo
idf.py set-target esp32s3
idf.py build flash monitor
ferrite_compile does the parsing, shape inference, optimization, and
memory planning on your workstation and writes a FEMD artifact: a
self-contained, fully-planned model with its weights inline and its memory plan
already resolved.
ferrite_compile model.onnx model.femd [--in-shape WxHxC] [--emit-header]
[--target esp32] [--max-nodes N]
The device then loads it with fe_model_load and runs it with
fe_model_run — no ONNX parser, no shape inference, no optimizer
on the target. --emit-header writes the artifact as a C byte array
for flash-mapped deployment.
Get started
cmake -S . -B build -G Ninja # GCC or Clang; C11
cmake --build build # 18 test binaries
ctest --test-dir build --output-on-failure # 19 entries
Default flags are -Wall -Wextra -fsanitize=address,undefined, and
sanitizer availability is probed at configure time.
GCC or Clang only — MSVC is a hard configure error, because the
project needs the POSIX clock and the sanitizers. Use MinGW, MSYS2, or WSL.
cmake --build build --target demo_mnist # MNIST, ASCII-art digits
cmake --build build --target demo # AcousticLeakNet, a real 1D-CNN
cmake --build build --target bench_model # latency, per-op profile, memory
cmake --build build --target mnist_eval # full 10k test-set accuracy
Nine options gate the optional halves of the project, so a device build compiles only what it actually runs:
-DFERRITE_ENABLE_IMPORTER=OFF # drop the ONNX parser (device builds)
-DFERRITE_ENABLE_OPTIM=OFF # drop the optimization passes
-DFERRITE_ENABLE_AVX2=OFF # scalar kernels only
-DFERRITE_ENABLE_PROFILER=OFF # drop the timing profiler
Capacities are cache variables too: -DFE_MAX_NODES=,
-DFE_MAX_TENSORS=, -DFERRITE_MAX_DIMS=. Exceeding one is
a loud load-time error naming the knob, never a truncated shape.
*.exe in build/
and copy libwinpthread-1.dll beside themselves. Run through CTest or
from build/.
Trade-offs
Every one of these is a deliberate choice with a cost attached. They are listed here for the same reason they are listed in the README.
FE_ERR_SHAPE — never silently.max(|x|) activation ranges; percentile smoothing is not built.