Girish Maity

Work / Research

Tensor Forge

A small compiler for tensor expressions: typed graph IR, shape checking, a reference interpreter, five optimisation passes, and real native code via emitted C++ and MSVC, measured honestly against NumPy/OpenBLAS.

  • Research prototype
  • Recorded run
  • compilers
  • tensor IR
  • code generation
  • C++
  • optimisation passes
  • benchmarking

Problem

Turn a small tensor program (matrix multiply, bias, ReLU) into native code that computes exactly what a reference interpreter computes, checked by tests rather than proven, then measure honestly where that code stands against a mature BLAS library.

Result

Grouped horizontal bars on a logarithmic time axis (gridlines every factor of ten, 1 ns at the left to 1 s at the right), one group per M4 benchmark workload from tiny 2x3x2 to elementwise 1024x1024. In each group: grey is the tforge interpreter, blue is tforge-generated C++ with all passes, black is NumPy/OpenBLAS on one thread. Shorter is faster. The black bar is shortest for every matmul except the tiny one, where the blue bar is far shorter.

  • The brief's fixture compiles from 7 IR nodes and 4 temporary buffers to 4 nodes and 0 buffers. One fused loop computes relu(X·W + b) and writes the output directly.
  • Code generation acceptance (run 20261109T133404Z-645b6a): 36/36 programs compiled by MSVC matched the reference interpreter; 35 were byte-identical.
  • Optimisation acceptance (run 20261109T142844Z-7d8bc1): 369 (program, pass configuration) pairs, 0 failures. With all passes, temporary buffers across 41 programs fell from 114 to 38, and from 32,768 to 12,884 bytes.
  • Benchmark (run 20261109T144454Z-6a9742): NumPy/OpenBLAS on one thread is about 190 times faster on a 512³ matmul (3.084 ms vs 585.1 ms). On the tiny fixture shape the fused kernel takes 4.0 ns per call, against 126.1 ns unfused.

The demo on this page is a recording: real compiler output for fixed programs, replayed. It does not compile anything you type.

What was built

  • A strict text language and JSON graph format, with compiler-style diagnostics (file:line:col).
  • A typed graph IR, a shape and bounds checker with overflow-checked arithmetic, and a reference interpreter.
  • A C++ source backend: the IR is lowered to loop nests, and the emitted C++ is compiled by MSVC. It is not LLVM or MLIR.
  • A process runner with no shell. It uses Windows Job Objects for time and memory limits on the compiler and on every generated kernel.
  • Five passes: dead-node elimination, constant folding, common-subexpression elimination, matmul epilogue fusion, and liveness-based buffer reuse.
  • A benchmark harness that times compilation, whole processes and the kernel alone separately, plus a NumPy harness on the same input bytes.

The key idea: fusion that changes no bits

Fusing bias and ReLU into a matmul is usually described as an optimisation. Here it also has to be exact. The unfused program stores y, then computes y + b[j], then clamps at zero. The fused loop performs those same float32 operations in the same order, without storing the intermediate. A faster-looking variant that starts the accumulator at b[j] is algebraically equal but rounds differently, so it is not allowed.

Fusion is only legal when every absorbed value has exactly one reader. In let y = matmul(A, B); return add(relu(y), y);, the pass declines and says why: did not fuse %0 into y: y has 2 consumers.

How correctness was checked

  • Every pass maps a checked graph to a checked graph whose interpreter output is byte-identical. This is tested on 400 random well-typed programs under 9 pass orders, and on every program in the native matrix.
  • Bugs were planted deliberately: fusion ignoring the single-reader rule, and buffer reuse freeing a slot one step early. Both were caught.
  • A negative control miscompiles the summation order on purpose. The comparison harness reports it.
  • A buffer plan shrunk by one float is caught by a checked build: debug heap, /RTC1, exit code 4. AddressSanitizer was not installed, so this is a weaker substitute, and it is labelled as one.
  • MSVC /O2 /fp:precise turned relu(-0) on a compile-time constant into +0, while /Od and /fp:strict kept -0. The project's own constant folding now computes that case by its semantics before MSVC sees it.

Benchmark

Median time per call on AMD Ryzen 7 5800H with Radeon Graphics, on AC power. Generated code and the interpreter are single-threaded. NumPy is shown at 1 thread and at OpenBLAS's default.

WorkloadInterpreterGenerated, no passesGenerated, all passesNumPy, 1 threadNumPy, default threads
tiny_2x3x21.02 µs126.1 ns4.0 ns4.08 µs3.77 µs (16)
square_64196.91 µs149.90 µs121.29 µs13.48 µs14.22 µs (16)
square_25626.8 ms31.0 ms30.2 ms357.95 µs258.55 µs (16)
square_512392.7 ms621.2 ms585.1 ms3.084 ms1.802 ms (16)
tall_4096x64x164.744 ms2.467 ms1.970 ms163.50 µs212.10 µs (16)
deep_k_16x4096x161.158 ms796.25 µs793.00 µs59.45 µs95.75 µs (16)
elementwise_256876.79 µs335.31 µs246.00 µs140.81 µs76.19 µs (16)
elementwise_102413.7 ms5.296 ms4.507 ms4.378 ms4.231 ms (16)

What the table shows:

  • BLAS wins every real matmul. The generated kernel is the textbook triple loop: one serial float32 sum, walking a column of W in large strides. OpenBLAS packs cache-sized blocks, uses 8-wide vector instructions and reorders the sum. The language's exact-order rule forbids that last step.
  • Generated code was slower than the interpreter at 256³ and 512³ (585.1 ms vs 392.7 ms at 512³). The cause has not been established. A cache-conflict and alignment hypothesis is recorded but untested.
  • Fusion and buffer reuse matter where allocation or memory traffic dominates. Tiny: 126.1 ns → 4.0 ns; tall 4096×64×16: 2.467 ms → 1.970 ms.
  • The memory-bound elementwise workload roughly matches NumPy (4.507 ms vs 4.378 ms, with overlapping ranges).
  • The tiny-shape gap against NumPy is a C call against a Python call. It says nothing about larger shapes.
  • OpenBLAS threads only affect the matmul. NumPy's elementwise operations run on one thread either way, so the difference between the two NumPy columns on the elementwise rows is run-to-run variation, not threading.

Method: 3 warm-up calls, then 10-50 timed samples per variant, with each sample batching up to 100,000 calls where the 100 ns clock needs it. All variants read the same input bytes. Compile time (about 1.4-2.9 s per kernel) and whole-process time are measured separately from kernel time.

Limitations

  • Four operations, float32, rank 1-2, fixed shapes. No tiling, vectorisation, threads or GPU.
  • Native compilation is Windows/MSVC only, and every kernel compile takes over a second. There is no compile cache.
  • The passes are tested, not proven equivalent. The random programs use small dimensions.
  • AddressSanitizer was unavailable. The checked build cannot see stale reads inside live memory.
  • Benchmarks come from one laptop and one run, with variants run sequentially and no turbo or temperature control.

Next

Cache tiling and loop interchange for the matmul. This keeps the per-element summation order, and would test the cache-conflict hypothesis directly. A compile cache would follow.

Reproduce

cmake -S . -B build -G "Visual Studio 17 2022" -A x64
cmake --build build --config Release
ctest --test-dir build -C Release
build/Release/tforge.exe opt fixtures/fixture.tf
build/Release/tforge.exe codegen-matrix --preset m3 --seed 1 --out experiments/passes --work artifacts/passes
build/Release/tforge.exe bench --plan experiments/bench/m4.json
python -I experiments/bench/numpy_bench.py experiments/bench/results/<run_id>
python -I tools/export_bundle.py
  • Four operations (matmul, add, row bias, ReLU), float32, rank 1-2, fixed shapes.
  • The backend emits C++ compiled by MSVC on Windows. It is not LLVM or MLIR, and there is no other platform yet.
  • The matmul is an untiled, unvectorised loop. NumPy/OpenBLAS is 10-300 times faster on real matrix sizes.
  • Generated code was slower than the interpreter at 256³ and 512³ in the recorded run, and the cause is not established.
  • Passes are validated by differential and mutation testing, not formally proven. AddressSanitizer was unavailable.
  • Benchmarks come from one laptop, one run, with variants run sequentially.
  • The demo is recorded: it replays compiler output for fixed programs and compiles nothing.
RunRecordedBackendKindCode revision
20261109T144454Z-6a97422026-11-09 14:44 UTCMicrosoft (R) C/C++ Optimizing Compiler Version 19.44.35229 for x64; Windows 10.0.26200; AMD Ryzen 7 5800H with Radeon GraphicsMeasured1c5443a+uncommitted
20261109T142844Z-7d8bc12026-11-09 14:28 UTCMicrosoft (R) C/C++ Optimizing Compiler Version 19.44.35229 for x64; Windows 10.0.26200; AMD Ryzen 7 5800H with Radeon GraphicsMeasured48d9040+uncommitted
20261109T133404Z-645b6a2026-11-09 13:34 UTCMicrosoft (R) C/C++ Optimizing Compiler Version 19.44.35229 for x64; Windows 10.0.26200; AMD Ryzen 7 5800H with Radeon GraphicsMeasuredc3ffa5a+uncommitted
  • 20261109T144454Z-6a9742: M4 benchmark: 8 workloads; interpreter, generated C++ without and with passes, NumPy 2.5.2 at 1 and default threads. All generated outputs byte-identical to the interpreter. Work committed as 9f5f436.
  • 20261109T142844Z-7d8bc1: M3 pass matrix: 41 programs x 9 configurations, release and checked builds; 0 failures. Committed as 1c5443a.
  • 20261109T133404Z-645b6a: M2 code generation matrix: 36/36 matched the interpreter, 35 byte-identical. Committed as 48d9040.