Skip to content

About

Lightweight C inference engine with AVX2, NEON, and INT8 GEMM kernels, quantization, thread pooling, and single-header amalgamation

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

30 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

InferenceEngine Banner

Setup Math Memory SIMD Tests


⚑ What Is InferenceEngine?

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 static const byte 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 zero malloc() or free() calls inside tight real-time callbacks.

πŸͺœ The GEMM Kernel Ladder

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 ($\sim 80\text{ KB}$ tile) 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.


πŸ›οΈ Architecture & End-to-End Pipeline

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
Loading

πŸ₯Š InferenceEngine vs. The Alternatives

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)

πŸš€ Quickstart: The 30-Second Drop-In

You do not need CMake, Git submodules, build tools, or package managers.

Option A: True STB-Style Single Header (dist/ie.h)

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;
}

Compile Instantly (Single Command):

# Pure C99, zero linking, compiles in milliseconds:
gcc -O3 -std=c99 main.c -lm -o my_app

Option B: Traditional Separate Header + Source (dist/ie.h + dist/ie.c)

If 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.c

πŸŽ›οΈ Zero-Allocation Workspace Mode (Audio DSP & Robotics)

In 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);

Or Use Persistent Context (ie_context_t)

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

🐍 Python Model Exporter & Calibration Bridge

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

The Exporter Automatically:

  • 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.

πŸ“ Mathematical Invariants & Bit-Identical Proof

InferenceEngine guarantees exact numerical reproducibility across architectures through provable non-overflowing integer math.

Inner Dimension Bound Proof ($k \le 132,104$)

Every INT8 matrix multiplication computes dot products: $$\text{Accumulator} = \sum_{p=0}^{k-1} A[i, p] \times B[p, j]$$

Given signed 8-bit inputs $A_{i,p}, B_{p,j} \in [-128, 127]$: $$\max(|A_{i,p} \times B_{p,j}|) = 128 \times 127 = 16,256$$ $$\text{Max Accumulated Sum} = k \times 16,256$$

To mathematically prevent 32-bit signed integer overflow ($\text{INT32_MAX} = 2,147,483,647$): $$k \le \left\lfloor \frac{2,147,483,647}{16,256} \right\rfloor = 132,104$$

Every INT8 kernel enforces $k \le 132,104$ at entry.
Because accumulation occurs in exact integers without overflow, addition is strictly associative ($a + b + c = c + b + a$). Changing cache tile sizes, vector widths, or thread counts cannot alter a single output bit.


🏎️ Hardware SIMD & Cache Budgeting

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

Cache Tiling Parameters ($MC=64, KC=512, NC=64$)

  • 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).

πŸ’‘ Ready-to-Run Demos & Systems Tools

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

🎯 Target Use Cases

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.

πŸ§ͺ Verification & Quality Assurance

InferenceEngine undergoes rigorous automated validation:

  • Bit-Identical Verification: test_all_correctness.c asserts exact bit equality across all execution engines.
  • Persistence Integrity: test_serialization_and_workspace.c validates .iemod roundtrips 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).

πŸ“– In-Depth Technical Manuals

For comprehensive architecture and mathematical specifications, refer to docs/:

  1. 01 β€” Overview: Project mission and capabilities.
  2. 02 β€” Architecture: Deep-dive into memory hierarchy and execution graphs.
  3. 03 β€” Numerics Contract: Mathematical proofs of determinism and quantization invariants.
  4. 04 β€” GEMM Kernels: Hardware vectorization (AVX2/NEON), cache tiling, and threading.
  5. 05 β€” Model Inference: Inference pipeline, zero-alloc workspace mechanics, and .iemod binary specification.
  6. 06 β€” Platform & CPU Detection: Runtime CPUID, cache size discovery, and OS topology probes.
  7. 07 β€” Build System: Modular CMake configuration and single-file usage.
  8. 08 β€” Tools & Benchmarks: Benchmark suites, crossover studies, and profiling utilities.
  9. 09 β€” Testing & Validation: Test harness details and memory safety audits.
  10. 10 β€” Results & RESULTS.md: Architectural design parameters and performance measurements.
  11. 11 β€” Roadmap & History: Technical development history and future directions.

πŸ“„ License

Standard permissive C99 open-source reference implementation. See header files for details.

About

Lightweight C inference engine with AVX2, NEON, and INT8 GEMM kernels, quantization, thread pooling, and single-header amalgamation

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages