Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fp8: end-to-end test, real repack tool -> real C loader

monotophic633013f266b4
diff --git a/c/tests/test_fp8_e2e_loader.c b/c/tests/test_fp8_e2e_loader.c
new file mode 100644
index 00000000..c2ee9884
--- /dev/null
+++ b/c/tests/test_fp8_e2e_loader.c
@@ -0,0 +1,86 @@
+/* fp8 passthrough END-TO-END loader harness.
+ *
+ * Neither test_fp8_load.c (hand-built wire-format C fixtures -- proves the
+ * LOADER's own disambiguation logic in isolation, but the container bytes
+ * are hand-authored, not tool-produced) nor test_fp8_repack.py (proves the
+ * WRITER's Python-side output shape -- never invokes the C loader at all)
+ * exercises the REAL round trip: a container the REAL
+ * tools/repack_fp8_passthrough.py actually produced, fed into the REAL
+ * st_init/qt_from_disk. This binary is the C-side half of that round trip;
+ * tests/test_fp8_e2e_repack_load.py drives it end to end (builds a synthetic
+ * FP8 checkpoint via tools/glm_fp8_emit.py, repacks it with the real tool
+ * via subprocess -- the actual CLI, not a reimplementation -- then invokes
+ * this binary against the real output directory).
+ *
+ * Usage: test_fp8_e2e_loader <container_dir> [name O I]...
+ * For every (name,O,I) triple, calls the REAL qt_from_disk (the identical
+ * function every model load uses) and asserts:
+ * (a) fmt==7 resolved (native fp8-e4m3-passthrough, via byte-arithmetic
+ * inference alone -- this PR's repack tool writes no container
+ * metadata stamp, see repack_fp8_passthrough.py's module docstring);
+ * (b) the weight (q8) and scale (s) buffers are non-NULL;
+ * (c) every dequantized value (e4m3_decode(byte) * block scale) is finite
+ * -- catches a decode-table or block-index bug a pure byte-count
+ * check wouldn't. */
+#define main coli_glm_main_unused
+#include "../colibri.c"
+#undef main
+
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <stdlib.h>
+
+int main(int argc, char **argv){
+ if(argc < 2){ fprintf(stderr,"usage: %s <dir> [name O I]...\n", argv[0]); return 2; }
+ if((argc-2) % 3 != 0){
+ fprintf(stderr,"args after <dir> must come in (name,O,I) triples (got %d)\n", argc-2);
+ return 2;
+ }
+ const char *dir = argv[1];
+ int ntensors = (argc-2)/3;
+ if(ntensors == 0){ fprintf(stderr,"no (name,O,I) triples given -- nothing to check\n"); return 2; }
+
+ static Model gm; memset(&gm,0,sizeof gm);
+ st_init(&gm.S, dir);
+
+ int fails = 0;
+ for(int i=0;i<ntensors;i++){
+ const char *name = argv[2+i*3];
+ int O = atoi(argv[3+i*3]);
+ int I = atoi(argv[4+i*3]);
+
+ QT t; memset(&t,0,sizeof t);
+ qt_from_disk(&gm, name, O, I, 8, 0, &t); /* THE REAL LOADER PATH -- not mocked */
+
+ if(t.fmt != 7){
+ printf("FAIL %s: fmt=%d, expected 7 (native fp8-e4m3 passthrough)\n", name, t.fmt);
+ fails++; continue;
+ }
+ if(!t.q8 || !t.s){
+ printf("FAIL %s: fmt=7 but q8=%p s=%p (expected both non-NULL)\n",
+ name, (void*)t.q8, (void*)t.s);
+ fails++; continue;
+ }
+ int64_t nblkI = fp8_nblk(I);
+ int64_t bad = -1;
+ for(int64_t o=0; o<O && bad<0; o++){
+ int64_t blkO = o/FP8_BLOCK;
+ const float *scl = t.s + blkO*nblkI;
+ for(int64_t ii=0; ii<I; ii++){
+ int64_t bi = ii/FP8_BLOCK;
+ float v = e4m3_decode(t.q8[o*(int64_t)I+ii]) * scl[bi];
+ if(!isfinite(v)){ bad = o*(int64_t)I+ii; break; }
+ }
+ }
+ if(bad >= 0){
+ printf("FAIL %s: non-finite dequantized value at flat index %lld\n", name, (long long)bad);
+ fails++; continue;
+ }
+ printf("ok %s: fmt=7 O=%d I=%d, weights+scale loaded through the real loader, all-finite\n",
+ name, O, I);
+ }
+ if(fails){ printf("fp8 e2e repack->load: %d/%d tensor(s) FAILED\n", fails, ntensors); return 1; }
+ printf("fp8 e2e repack->load: ok (%d tensor(s))\n", ntensors);
+ return 0;
+}
diff --git a/c/tests/test_fp8_e2e_repack_load.py b/c/tests/test_fp8_e2e_repack_load.py
new file mode 100644
index 00000000..4cd5e8e5
--- /dev/null
+++ b/c/tests/test_fp8_e2e_repack_load.py
@@ -0,0 +1,160 @@
+"""End-to-end: REAL tools/repack_fp8_passthrough.py output fed into the REAL
+C loader (st_init/qt_from_disk in colibri.c) via a small C harness.
+
+Neither test_fp8_load.c (hand-built wire-format C fixtures -- proves the C
+loader's OWN logic, but the container bytes are hand-authored, not
+tool-produced) nor test_fp8_repack.py (proves the Python tool's OUTPUT
+shape, but never invokes the C loader at all) covers this round trip. This
+test does, end to end:
+
+ 1. build a synthetic FP8 checkpoint with tools/glm_fp8_emit.py (the same
+ fixture-generation helper test_fp8_repack.py uses -- not reimplemented
+ here, imported directly);
+ 2. repack it with the REAL tools/repack_fp8_passthrough.py, invoked as a
+ subprocess exactly as a user would run it from the command line (not
+ imported and called as a library, so the CLI entry point is exercised
+ too, not just the importable functions);
+ 3. compile tests/test_fp8_e2e_loader.c -- production flags mirroring the
+ Makefile's own CFLAGS, asserted to produce zero warnings -- into a
+ temp binary;
+ 4. run that binary against the REAL repacked output directory, asserting
+ every selected tensor loads fmt=7 through the real qt_from_disk with
+ finite dequantized values (byte-arithmetic inference alone -- this PR's
+ repack tool writes no container metadata stamp).
+
+Hermetic: everything (checkpoint, repacked output, compiled harness binary)
+lives under one TemporaryDirectory; nothing is left behind.
+"""
+import glob, json, os, shutil, struct, subprocess, sys, tempfile, unittest
+
+try:
+ import torch
+except ImportError as e:
+ raise unittest.SkipTest(f"torch not installed: {e}")
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+C_DIR = os.path.normpath(os.path.join(HERE, ".."))
+sys.path.insert(0, os.path.join(C_DIR, "tools"))
+from glm_fp8_emit import save_fp8_safetensors # reuse: real fp8 block-quantize, not reimplemented
+
+
+def _cc_flags():
+ """Mirror the Makefile's CFLAGS closely enough to compile colibri.c
+ cleanly: -O3 + the same warning flags, plus libomp on macOS if present
+ (falls back to single-threaded -- exactly like the Makefile's own
+ OMPDIR probe -- if it's not, rather than failing the build). Returns
+ (cc, cflags, ldflags) or (None, None, None) if no compiler is found."""
+ cc = shutil.which("cc") or shutil.which("clang") or shutil.which("gcc")
+ if not cc:
+ return None, None, None
+ cflags = ["-O3", "-Wall", "-Wextra", "-Wno-unused-parameter",
+ "-Wno-misleading-indentation", "-Wno-unused-function"]
+ ldflags = ["-lm"]
+ if sys.platform == "darwin":
+ try:
+ prefix = subprocess.run(["brew", "--prefix", "libomp"], capture_output=True,
+ text=True, timeout=10).stdout.strip()
+ except (OSError, subprocess.TimeoutExpired, FileNotFoundError):
+ prefix = ""
+ inc, lib = os.path.join(prefix, "include"), os.path.join(prefix, "lib")
+ if prefix and os.path.exists(os.path.join(inc, "omp.h")):
+ cflags += ["-Xclang", "-fopenmp", "-I", inc]
+ ldflags += ["-L", lib, "-lomp"]
+ return cc, cflags, ldflags
+
+
+class Fp8RepackLoadE2ETest(unittest.TestCase):
+ """The real tools/repack_fp8_passthrough.py -> the real C loader, once."""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.indir = os.path.join(self.tmp.name, "fp8src")
+ os.makedirs(self.indir)
+ self.outdir = os.path.join(self.tmp.name, "out")
+ self.shard = os.path.join(self.indir, "model-00001-of-00001.safetensors")
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_real_repack_output_loads_through_real_c_loader(self):
+ D, I_ = 256, 384 # non-degenerate shapes: nblkO*nblkI never coincides with O (no
+ # THE DESIGN LANDMINE ambiguity here -- that boundary is
+ # test_fp8_load.c's job, this test's job is the round trip)
+ torch.manual_seed(7)
+ sd = {
+ "model.layers.0.self_attn.o_proj.weight": torch.randn(D, D) * 0.02,
+ "model.layers.0.self_attn.q_a_proj.weight": torch.randn(D, D) * 0.02,
+ "model.layers.0.mlp.shared_experts.gate_proj.weight": torch.randn(D, I_) * 0.02,
+ "model.layers.0.mlp.gate_proj.weight": torch.randn(D, I_) * 0.02,
+ # routed expert: must NOT be selected (stays int4-g64 path) -- included
+ # as a negative control so this test also proves the real tool's selection
+ # logic held on the real round trip, not just in test_fp8_repack.py's own suite.
+ "model.layers.0.mlp.experts.0.gate_proj.weight": torch.randn(I_, D) * 0.02,
+ "model.layers.0.input_layernorm.weight": torch.randn(D), # f32: must NOT be selected
+ }
+ # (O, I) exactly as the engine/repack tool see them -- known here because this
+ # test authored the checkpoint; the real C loader never gets told this by us,
+ # only by the container it reads (st_init parses shape from the file itself;
+ # O/I are qt_from_disk's own [O,I] contract, same as every real model load).
+ shapes = {
+ "model.layers.0.self_attn.o_proj.weight": (D, D),
+ "model.layers.0.self_attn.q_a_proj.weight": (D, D),
+ "model.layers.0.mlp.shared_experts.gate_proj.weight": (D, I_),
+ "model.layers.0.mlp.gate_proj.weight": (D, I_),
+ }
+ save_fp8_safetensors(sd, self.shard)
+
+ tool = os.path.join(C_DIR, "tools", "repack_fp8_passthrough.py")
+ rc = subprocess.run([sys.executable, tool, "--indir", self.indir,
+ "--outdir", self.outdir, "--n-layers", "5"],
+ capture_output=True, text=True)
+ self.assertEqual(rc.returncode, 0, f"real repack tool failed:\nSTDOUT:\n{rc.stdout}\nSTDERR:\n{rc.stderr}")
+
+ outs = glob.glob(os.path.join(self.outdir, "out-fp8pass-*.safetensors"))
+ self.assertEqual(len(outs), 1, "expected exactly one repacked output shard")
+
+ # Sanity-check the real tool's own selection BEFORE asking the C harness to load
+ # it: if this fails, the bug is in the tool, not the loader, and running the
+ # harness anyway would only muddy which side broke. This PR's repack tool writes
+ # NO container metadata stamp (that's a separate, follow-up PR -- see the tool's
+ # own module docstring), so selection is checked by tensor presence instead of a
+ # stamp's tensor-name set, and the stamp's ABSENCE is itself asserted below: a
+ # regression guard that this PR's tool really stays out of that scope.
+ with open(outs[0], "rb") as f:
+ hlen = struct.unpack("<Q", f.read(8))[0]
+ hdr = json.loads(f.read(hlen))
+ for name in shapes:
+ self.assertIn(name, hdr, f"{name}: expected tensor missing from repacked output")
+ self.assertIn(name + ".qs", hdr, f"{name}.qs: expected scale sidecar missing")
+ self.assertNotIn("model.layers.0.mlp.experts.0.gate_proj.weight", hdr)
+ self.assertNotIn("model.layers.0.input_layernorm.weight", hdr)
+ self.assertNotIn("__metadata__", hdr,
+ "this PR's repack tool must not write a container metadata stamp "
+ "(stamp writer is a separate, follow-up PR)")
+
+ cc, cflags, ldflags = _cc_flags()
+ if not cc:
+ raise unittest.SkipTest("no C compiler found on PATH")
+
+ harness_src = os.path.join(HERE, "test_fp8_e2e_loader.c")
+ harness_bin = os.path.join(self.tmp.name, "test_fp8_e2e_loader")
+ build = subprocess.run([cc] + cflags + [harness_src, "-o", harness_bin] + ldflags,
+ capture_output=True, text=True, cwd=C_DIR)
+ self.assertEqual(build.returncode, 0, f"e2e harness build failed:\n{build.stderr}")
+ self.assertEqual(build.stderr.strip(), "",
+ f"e2e harness build produced warnings (production flags require zero):\n{build.stderr}")
+
+ args = [harness_bin, self.outdir]
+ for name, (O, I) in shapes.items():
+ args += [name, str(O), str(I)]
+ run = subprocess.run(args, capture_output=True, text=True)
+ self.assertEqual(run.returncode, 0,
+ f"e2e harness (real loader) failed:\nSTDOUT:\n{run.stdout}\nSTDERR:\n{run.stderr}")
+ self.assertNotIn("FAIL", run.stdout)
+ for name in shapes:
+ self.assertIn(f"ok {name}:", run.stdout)
+ self.assertIn("fp8 e2e repack->load: ok", run.stdout)
+
+
+if __name__ == "__main__":
+ unittest.main()