InferenceEngine is the stb_image / sqlite3 of INT8 neural inference: a single-header, zero-dependency ANSI C99 micro-runtime for running quantized neural networks (MLPs, feed-forward models, sensor classifiers, and audio DSP blocks) with provable numerical determinism and zero dynamic memory allocations in the hot path.
While the industry builds multi-gigabyte GPU runtimes for Large Language Models, the vast majority of real-world deployed edge systemsβin microcontrollers (ESP32/STM32), audio VST/AU plugins, robotics, game physics, and automotive ECUsβrequire the exact opposite:
-
The STB-Style Single Header (
dist/ie.h): Drop#define IE_IMPLEMENTATION \n #include "ie.h"into exactly one C/C++ file. Compiles in under 1 second with any standard C99 compiler (gcc main.c -O3 -lm). Zero build configurations, zero submodules, zero package managers. -
Flash ROM Direct Execution (
model_load_from_memory): Execute directly against staticconstbyte arrays embedded in Flash ROM (.rodata). Zero disk reads, zero file-system calls, zero RAM footprint for weights. -
Provable Bit-Identical Determinism: Mathematical inner-dimension bound guards (
$k \le 132,104$ ) guarantee that$128 \times 127 \times k$ fits in a signed 32-bit integer without overflow. All execution paths (Scalar, Cache-Blocked, AVX2, ARM NEON, Threaded) yield bit-identical output tensors down to the exact bit. -
Zero-Allocation Execution (
model_infer_workspace): Pre-sizes all activation buffers and INT8 quantization scratchpads into a caller-allocated arena, guaranteeing zeromalloc()orfree()calls inside tight real-time callbacks.
A central pillar of InferenceEngine is its rigorous, multi-tier execution ladder. All tiers produce 100% bit-identical INT8 output, allowing developers and students to measure and understand modern CPU cache hierarchy and vectorization first-hand (verified via tools/gemm_tuner.c on AMD Ryzen 3 5300U):
| Ladder Level | Implementation Strategy | Hardware Bottleneck Target | Measured Latency (256x256x512) | Throughput (GOPS) | Relative Speedup |
|---|---|---|---|---|---|
| Level 1 | Scalar Reference | DRAM / Memory Bandwidth ($O(N^3)$) | 405.48 ms | 0.17 GOPS | 1.0x (Baseline) |
| Level 2 | GotoBLAS L2 Cache-Blocked | L2 Cache Resident ( |
4.26 ms | 15.75 GOPS | 92.6x π |
| Level 3 | AVX2 256-bit Vector SIMD | CPU Register Tiling (32 MACs/cycle) | 3.92 ms | 17.10 GOPS | 100.5x π |
| Level 4 | Multithreaded Blocked (4T) | Multi-Core Hardware Parallelism | 2.35 ms | 28.51 GOPS | 167.7x π |
The Cache Insight: Moving from Level 1 to Level 2 requires zero vector instructionsβsimply tiling matrix chunks to remain hot in CPU L2 cache delivers an immediate 92x speedup, proving that memory locality, not raw FLOPs, is the dominant factor in modern CPU execution.
flowchart LR
A["PyTorch / NumPy\n(Model Training)"] -->|"ie_export.py\n(PTQ Calibration)"| B["Native Binary\n(.iemod + FNV-1a)"]
B -->|"model_load_from_binary()"| C["InferenceEngine Core\n(C99 Runtime)"]
subgraph Execution ["Dual Execution Modes"]
C --> D["Standard Mode\n(Dynamic Caching)"]
C --> E["Workspace Mode\n(0 Malloc / Real-Time)"]
end
subgraph Compute ["Hardware SIMD Kernels"]
E --> F["x86-64 AVX2\n(256-bit SIMD)"]
E --> G["ARM NEON\n(128-bit DotProd)"]
E --> H["Cache-Blocked\n(L1/L2 Tiled)"]
end
F --> I["Bit-Identical\nOutput Logits"]
G --> I
H --> I
| Feature / Metric | InferenceEngine | ONNX Runtime | TensorFlow Lite Micro | llama.cpp |
|---|---|---|---|---|
| Primary Focus | Dense Edge MLPs / DSP / Embedded | General Vision / NLP | Microcontrollers | LLMs / Generative AI |
| Drop-in Single File | Yes (dist/ie.h + dist/ie.c) |
No (Multi-MB C++ binary) | No (Complex CMake) | No (C++ codebase) |
| External Dependencies | Zero (Pure C99) | Protobuf, C++ STL, Libs | FlatBuffers, Tooling | C++ STL, OpenMP |
| Hot-Path Allocations | Zero (model_infer_workspace) |
Dynamic Heap | Arena Pool | Dynamic Heap |
| Cross-HW Determinism | 100% Bit-Identical (int32) |
Non-Deterministic Float | Architecture Dependent | Non-Deterministic |
| Compilation Time | < 1 Second | Several Minutes | Several Minutes | ~30-45 Seconds |
| RAM Footprint | ~80 KB L2-resident working set | > 30-100 MB | Tens of KB | Multi-GB (Weights) |
You do not need CMake, Git submodules, build tools, or package managers.
Drop dist/ie.h into your project and define IE_IMPLEMENTATION in exactly one source file:
#include <stdio.h>
#define IE_IMPLEMENTATION
#include "ie.h"
int main(void) {
// 1. Load model directly from Flash ROM / static memory (Zero disk I/O)
// Or from file via: model_load_from_binary("model.iemod");
extern const uint8_t g_model_data[];
extern const size_t g_model_data_len;
model_t *model = model_load_from_memory(g_model_data, g_model_data_len);
if (!model) return 1;
// 2. Query required SRAM scratchpad (e.g. 548 bytes)
size_t ws_bytes = model_get_workspace_size(model, 1);
uint8_t workspace[1024];
// 3. Prepare inputs and run inference (0 mallocs, 0 frees, bit-exact INT8)
int shape[2] = {1, model->input_size};
tensor_t *in = tensor_create(DTYPE_FLOAT32, 2, shape);
tensor_t *out = tensor_create(DTYPE_FLOAT32, 2, shape);
model_infer_workspace(model, in, out, workspace, sizeof(workspace), 1);
printf("Inference Result: %.4f\n", ((float *)out->data)[0]);
tensor_free(in);
tensor_free(out);
model_free(model);
return 0;
}# Pure C99, zero linking, compiles in milliseconds:
gcc -O3 -std=c99 main.c -lm -o my_appIf your project uses standard multi-file compilation:
# GCC or Clang (Linux, macOS, WSL)
gcc -O3 main.c dist/ie.c -lpthread -lm -o my_app
# MSVC (Windows)
cl.exe /O2 main.c dist/ie.cIn 44.1 kHz audio callbacks (VST/AU plugins), robotics control loops (1,000 Hz), or game physics ticks, calling malloc() or free() causes OS priority inversions, context switching, audio dropouts, and non-deterministic frame pacing.
InferenceEngine provides a guaranteed zero-heap-allocation inference API:
#include "ie.h"
// ---------------------------------------------------------
// Initialization (Run ONCE at startup)
// ---------------------------------------------------------
size_t ws_bytes = model_get_workspace_size(model, 1 /* batch size */);
void *workspace = malloc(ws_bytes); // Pre-allocated scratchpad memory
// ---------------------------------------------------------
// Live Real-Time Callback (Runs at 44,100 Hz or 1,000 Hz)
// ---------------------------------------------------------
void on_audio_process_block(tensor_t *live_input, tensor_t *live_output) {
// Guaranteed ZERO malloc/free calls inside this function:
model_infer_workspace(model, live_input, live_output, workspace, ws_bytes, 1);
}
// ---------------------------------------------------------
// Teardown (Run ONCE at shutdown)
// ---------------------------------------------------------
free(workspace);To completely eliminate thread spawn overhead when using multi-threading:
// Pre-spawns long-lived condition-wait worker threads and allocates workspace
ie_context_t *ctx = ie_context_create(model, batch_size, num_threads);
// Fast inference: wakes persistent workers with zero thread spawn latency
ie_context_infer(ctx, input, output);
// Cleanup
ie_context_free(ctx);Train in PyTorch, quantize, and export to .iemod with automated activation range calibration:
import torch
import torch.nn as nn
from ie_export import export_pytorch_sequential
# 1. Define and train your PyTorch model
model = nn.Sequential(
nn.Linear(8, 16),
nn.ReLU(),
nn.Linear(16, 16),
nn.ReLU(),
nn.Linear(16, 10)
)
model.eval()
# 2. Export with automated activation range calibration
sample_batch = torch.randn(100, 8)
export_pytorch_sequential(
model,
sample_batch,
filepath="classifier.iemod",
model_name="audio_classifier"
)- Symmetrically quantizes weight matrices:
$\text{scale}_W = \max(|W|) / 127.0$ . - Instruments forward hooks to capture real activation distributions from
sample_batch, preventing clipping distortion. - Computes and embeds an FNV-1a 32-bit checksum trailer to prevent corrupted model execution.
InferenceEngine guarantees exact numerical reproducibility across architectures through provable non-overflowing integer math.
Every INT8 matrix multiplication computes dot products:
Given signed 8-bit inputs
To mathematically prevent 32-bit signed integer overflow (
Every INT8 kernel enforces
Because accumulation occurs in exact integers without overflow, addition is strictly associative (
========================================================================================
Benchmark: 192 x 192 x 192 INT8 Matrix Multiplication (Ryzen / Intel x86-64)
========================================================================================
Scalar FP32 Reference: 0.16 GOPS
Scalar INT8 Reference: 0.16 GOPS
Cache-Blocked INT8 (L1/L2): 11.43 GOPS (71x speedup over scalar)
AVX2 256-bit Vector SIMD: 11.16 GOPS (Bit-identical to scalar)
----------------------------------------------------------------------------------------
Inference Accuracy vs. FP32: 98.7% (Within <1.3% quantization budget)
Accumulator Guard: k <= 132,104 (Provable non-overflowing integer math)
========================================================================================
-
A Tile:
$64 \times 512 \times 1\text{ B} = 32\text{ KB}$ (Fits L1 Data cache) -
B Tile:
$512 \times 64 \times 1\text{ B} = 32\text{ KB}$ (Fits L1 Data cache) -
Accumulator Tile:
$64 \times 64 \times 4\text{ B} = 16\text{ KB}$ (L1 Data cache resident) -
Active Working Set:
$\sim 80\text{ KB}$ (Comfortably fits standard 512 KB per-core L2 caches).
The repository includes standalone, self-contained examples and tools that run without complex toolchains:
| Directory / Tool | Focus Domain | Key Capability Demonstrated | Command to Run |
|---|---|---|---|
examples/single_header_demo/ |
Universal STB Drop-In | #define IE_IMPLEMENTATION dual-mode header usage in a single file with zero dependencies. |
gcc -O3 -Idist examples/single_header_demo/main.c -lm && ./a.out |
examples/embedded_sensor_anomaly/ |
IoT / Microcontrollers | Real-time 3-axis vibration autoencoder executing directly from Flash ROM in < 16 KB RAM. | gcc -O3 -Iinclude -mavx2 src/*.c examples/embedded_sensor_anomaly/main.c -lm && ./a.out |
examples/audio_dsp_saturator/ |
Real-Time Audio DSP | Fast rational Tanh polynomial neural tape/tube saturation on 512-sample audio blocks at 48kHz. | gcc -O3 -Iinclude -mavx2 src/*.c examples/audio_dsp_saturator/main.c -lm && ./a.out |
tools/gemm_tuner.c |
HPC / Architecture | Live CPU feature detection & benchmark across the 4 levels of the GEMM Kernel Ladder. | gcc -O3 -Iinclude -mavx2 src/*.c tools/gemm_tuner.c -lm && ./a.out |
python/ie_export.py |
PyTorch Bridge | Forward-hook activation calibration, INT8 symmetric quantization, and C-header/ROM export. | python python/ie_export.py |
| Industry / Application | Why InferenceEngine Is Chosen |
|---|---|
| Audio DSP & VST Plugins | Neural guitar amp modeling, noise reduction, and synth filters. Zero malloc in the audio thread prevents buffer underruns. |
| Robotics & Embedded IoT | Anomaly detection and sensor fusion on low-power Intel Atom, Raspberry Pi, and ARM Cortex chips with tiny flash memory. |
| Lockstep Multiplayer Games | Deterministic AI policy nets and physics evaluators. Bit-identical math guarantees zero client-server desync. |
| Safety-Critical Avionics & Auto | Bounded memory usage, static memory footprint, and mathematical overflow proofs simplify DO-178C / ISO 26262 compliance. |
| Systems & Architecture Education | Clean, readable, thoroughly documented C99 codebase for studying GEMM, cache tiling, and SIMD intrinsics. |
InferenceEngine undergoes rigorous automated validation:
- Bit-Identical Verification:
test_all_correctness.casserts exact bit equality across all execution engines. - Persistence Integrity:
test_serialization_and_workspace.cvalidates.iemodroundtrips and zero-allocation execution. - Sanitizer Matrix: Validated clean under AddressSanitizer (ASan), UndefinedBehaviorSanitizer (UBSan), and Valgrind.
- Compiler Warnings: Zero warnings under
-Wall -Wextra -Wpedantic -Werror(GCC/Clang) and/W4 /WX(MSVC).
For comprehensive architecture and mathematical specifications, refer to docs/:
- 01 β Overview: Project mission and capabilities.
- 02 β Architecture: Deep-dive into memory hierarchy and execution graphs.
- 03 β Numerics Contract: Mathematical proofs of determinism and quantization invariants.
- 04 β GEMM Kernels: Hardware vectorization (AVX2/NEON), cache tiling, and threading.
- 05 β Model Inference: Inference pipeline, zero-alloc workspace mechanics, and
.iemodbinary specification. - 06 β Platform & CPU Detection: Runtime CPUID, cache size discovery, and OS topology probes.
- 07 β Build System: Modular CMake configuration and single-file usage.
- 08 β Tools & Benchmarks: Benchmark suites, crossover studies, and profiling utilities.
- 09 β Testing & Validation: Test harness details and memory safety audits.
- 10 β Results & RESULTS.md: Architectural design parameters and performance measurements.
- 11 β Roadmap & History: Technical development history and future directions.
Standard permissive C99 open-source reference implementation. See header files for details.