Ferrite

C11 · zero dependencies · MIT

Ferrite

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.

  • 222 KBstripped binary
  • 0dependencies
  • 97.52%MNIST accuracy
  • 1.5 KBpeak activations

The claim

83× smaller. 2.3× slower. Numerically identical.

Those numbers are measured, not estimated, and every one of them has a command on this page that reproduces it.

FerriteONNX Runtime
Binary222 KB stripped18.4 MB onnxruntime.dll
Dependenciesnonemany
MNIST accuracy97.52% (9752/10000)same model, same weights
Latency, 1 thread2.42 ms1.06 ms
Agreementmax_abs ≈ 1e-8, 3 of 7 models bit-exactreference

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

See it work

A model trained in PyTorch, exported to ONNX, and executed here by C code that shares nothing with PyTorch or ONNX Runtime.

./build/demo_mnist
                        ++@@##..
                      ..@@@@@@==
                    ..##@@@@@@==
                  ==##@@@@@@@@**==::
                  @@@@@@@@@@@@@@@@%%::
                **@@@@@@@@@@%%%%@@@@@@
              ::%%@@@@@@@@++--::++@@@@==
            ..%%@@@@@@%%++      ..%%@@@@==
            ..@@@@@@##..          ==@@@@@@..
            ..@@@@##..            ..##@@@@..

    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.

Reproduce it end to end

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

How it works

An .onnx file goes in; a flat array of kernel calls comes out.

  1. .onnx
  2. 1 Parse
  3. 2 Optimize
  4. 3 Plan
  5. 4 Execute
  6. kernel calls

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.

2 Optimize

Shape inference → simplify → constant-fold → Conv+BN fusion → CSE → dead-code elimination.

3 Plan

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.

4 Execute

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.

The memory planner, in one picture

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.

Lifetime-aware activation packing Five activation tensors with non-overlapping lifetimes are packed into three reused offsets inside a single buffer, instead of five separate allocations. node 0 execution order → node 7 offset 0 +256 B +512 B t0 t3 · reused t1 t4 · reused t2 high-water mark — the entire allocation
Five activations, three offsets, one buffer. Reset the arena and the next inference reuses all of it.

Two structs carry the whole design

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

Eleven libraries, pointing one way

LayerContents
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

The rules the code is held to

No allocation in hot paths

Kernels never malloc. Only fe_conv1d allocates, and it frees its scratch after use.

Views over copies

Transpose and reshape rewrite strides. They never copy data.

Arenas over per-tensor malloc

Two arenas, two lifetimes. Freeing an inference is a single pointer reset.

Correctness first, speed second

The naive matmul is kept deliberately, as the oracle that validates the AVX2 kernel. Don't optimize it away.

One test per subsystem

The git history shows one subsystem per commit, each with its own test.

Fail loudly

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

Correctness

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.

Sanitizers, mandatory

ASan and UBSan are on by default, and a dedicated CI leg fails the build if they are ever silently dropped.

Fuzzing the parser

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.

An error contract

A test deliberately triggers every documented FE_ERR_* path across the public API and asserts outputs are untouched on failure.

Gates that bite

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

Performance, honestly

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

FerriteONNX Runtime
Latency2.42 ms1.06 ms
Binary222 KB18.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.

Where the hand-written SIMD pays off

Against Ferrite's own scalar reference:

KernelnaiveAVX2ratio
MatMul 256³6.92 ms1.45 ms4.78×
Elementwise add, 1M floats0.75 ms0.19 ms3.92×
GEMM base vs scalar transB22.09 ms1.41 ms15.65×

And where it does not

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

It runs on hardware you have lying around

Raspberry Pi Zero W

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

ESP32

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

Compile the model, not on the device

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

Build and test

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.

Run the demos

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

Turn subsystems off

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.

Windows / MinGW: binaries land as *.exe in build/ and copy libwinpthread-1.dll beside themselves. Run through CTest or from build/.

Trade-offs

Honest limitations

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.

  • ONNX Runtime is ~2.3× faster. Ferrite trades speed for size and simplicity.
  • The ONNX surface is the 20+ mapped ops. Anything else fails loudly with FE_ERR_SHAPE — never silently.
  • AVX2 only. No NEON, no AVX-512. NEON waits for a Pi Zero 2 W+ target.
  • Capacities are fixed but configurable: 512 nodes / 1024 tensors / 8 dims by default.
  • The engine hot path is deliberately single-threaded. The thread pool and the linear IR compiler exist and are tested, but are opt-in.
  • Calibration collects raw max(|x|) activation ranges; percentile smoothing is not built.
  • ESP32 hardware validation is a documented manual step; CI is a compile gate.