Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fix(trunk): guard mmap views in segment/edge destroy; gate the knob to the full-model load
SebaWagda908216052f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4f6ddc20..0e2887a0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -649,6 +649,25 @@ jobs:tests.test_inefficiency.TinyEfficiencyTest.test_profile_phases_present_and_nonneg \tests.test_inefficiency.TinyEfficiencyTest.test_disk_wait_not_dominant \tests.test_inefficiency.TinyEfficiencyTest.test_cpu_vs_cpu_determinism+ - name: Generate the quantized trunk fixture for #826+ # TRUNK_RESIDENT_LAYERS views only tensors that carry an on-disk int4+ # companion (`name.qs`), so the bf16 glm_tiny above cannot exercise the+ # view path -- every dense tensor would fall back to resident and+ # `resident dense` would never drop. Convert the oracle to int4 so the+ # knob has something to stream. Run AFTER the bf16 assertions: --fp8+ # rewrites glm_tiny in place.+ run: |+ cd c+ python3 tools/make_glm_oracle.py --fp8+ python3 tools/convert_fp8_to_int4.py --indir glm_tiny --outdir glm_tiny_i4 --ebits 4 --io-bits 4+ # The converter copies config.json but not ref_glm.json; the engine+ # needs the ref to enter validation mode.+ cp ref_glm.json glm_tiny_i4/ref_glm.json+ - name: TRUNK_RESIDENT_LAYERS opt-in contract (#826)+ # Identical tokens + lower `resident dense`: the knob trades RAM for page+ # faults, never answers. Keeps the next loader refactor from silently+ # breaking -- or silently no-op'ing -- the view path.+ run: cd c && python3 -m unittest -v tests.test_trunk_resident_layers# The token-exact parity gate from #7 (c/tests/test_cluster_sharding.py): the# engine's local CPU run must already reproduce the transformers oraclediff --git a/c/colibri.c b/c/colibri.cindex bb8631b2..4b80ba35 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -2208,10 +2208,10 @@ static QT qt_load(Model *m, const char *name, int O, int I, int bits){#endifreturn t;}-/* TRUNK_RESIDENT_LAYERS: carga UN QT del trunk como vista mmap si mmap_ok y el- * tensor es mmap-able (cuantizado + alineado); si no, path residente clasico.- * El flag mmap_view del QT resultante distingue ambos casos para planarize,- * contabilidad y free paths. */+/* TRUNK_RESIDENT_LAYERS: carica UN QT del trunk come vista mmap se mmap_ok e il+ * tensore e' mmap-abile (quantizzato + allineato); altrimenti path residente+ * classico. Il flag mmap_view del QT risultante distingue i due casi per+ * planarize, contabilita' e free paths. */static QT qt_load_ex(Model *m, const char *name, int O, int I, int bits, int mmap_ok){if(mmap_ok){QT t;@@ -2347,7 +2347,7 @@ static void metal_fmt_gate_notice(Model *m){static void model_init_range(Model *m, const char *snap, int cap,int ebits, int dbits, int layer_begin,int layer_end, int load_boundaries, int load_mtp,- int init_telemetry){+ int init_telemetry, int allow_trunk_mmap){memset(m,0,sizeof(*m)); m->ebits=ebits; m->dbits=dbits;load_cfg(&m->c,snap);{ const char *xd=getenv("COLI_MODEL_DIRS"); /* SPLIT: model shards spread across N drives */@@ -2402,10 +2402,14 @@ static void model_init_range(Model *m, const char *snap, int cap,m->kv_start=m->kv->kv_start=calloc(NR,sizeof(int));for(int i=layer_begin;i<layer_end;i++){Layer *l=&m->L[i];- /* TRUNK_RESIDENT_LAYERS: top-N residente. Las capas fuera del top-N- * (i < n_layers - g_trunk_resident) cargan sus tensores densos como- * vistas mmap si el tensor lo permite; el resto, residente clasico. */- int mmap_ok = (g_trunk_resident < c->n_layers)+ /* TRUNK_RESIDENT_LAYERS: top-N residente. Le layer fuori dal top-N+ * (i < n_layers - g_trunk_resident) caricano i tensori densi come vista+ * mmap se il tensore lo permette; il resto, residente classico.+ * Solo il path full-model puo' produrre viste (allow_trunk_mmap): un+ * range/segment load resta residente, cosi' i suoi destroy non liberano+ * puntatori interni di una mappa di shard (review #1399). */+ int mmap_ok = allow_trunk_mmap+ && (g_trunk_resident < c->n_layers)&& (i < c->n_layers - g_trunk_resident);l->trunk_mmap = mmap_ok;#define P(s) (snprintf(nm,sizeof(nm),"model.layers.%d." s,i),nm)@@ -2575,7 +2579,7 @@ static void model_init_range(Model *m, const char *snap, int cap,static void model_init(Model *m, const char *snap, int cap,int ebits, int dbits){- model_init_range(m,snap,cap,ebits,dbits,0,0,1,1,1);+ model_init_range(m,snap,cap,ebits,dbits,0,0,1,1,1,1); /* #826: full-model path may mmap the trunk */}/* embed: dequantizza la riga del token (scala per-riga) in x[hidden] */@@ -11557,6 +11561,10 @@ typedef struct {static void glm_segment_qt_destroy(QT *tensor) {if (!tensor) return;+ /* #826: a file-backed mmap view (mmap_view=1) holds interior pointers into a+ * shard mapping; free() on q8/q4/s would abort. Segment loads are gated to the+ * resident path, but keep this guard so the mmap_view contract holds here too. */+ if (tensor->mmap_view) return;free(tensor->qf); free(tensor->q8); free(tensor->q4); free(tensor->s);memset(tensor, 0, sizeof(*tensor));}@@ -11748,7 +11756,7 @@ static int glm_segment_engine_open(}model_init_range(&engine->model, options->model_dir, cap, ebits, dbits,(int)options->layer_begin, (int)options->layer_end,- 0, 0, 0);+ 0, 0, 0, 0); /* #826: range load stays resident (never a mmap view) */engine->base_kv = engine->model.kv;memset(capabilities, 0, sizeof(*capabilities));@@ -11993,6 +12001,10 @@ typedef struct {static void glm_edge_qt_destroy(QT *tensor) {if (!tensor) return;+ /* #826: never free() a file-backed mmap view (interior pointers into a shard+ * mapping). Edge loads embed/lm_head via the resident path today; this guard+ * keeps the mmap_view contract true if that ever changes. */+ if (tensor->mmap_view) return;free(tensor->qf); free(tensor->q8); free(tensor->q4); free(tensor->s);memset(tensor, 0, sizeof(*tensor));}diff --git a/c/tests/test_trunk_resident_layers.py b/c/tests/test_trunk_resident_layers.pynew file mode 100644index 00000000..b065d7ef--- /dev/null+++ b/c/tests/test_trunk_resident_layers.py@@ -0,0 +1,182 @@+"""TRUNK_RESIDENT_LAYERS=N (#826, PR #1399): opt-in mmap streaming of the dense trunk.++The two conditions the maintainer required before merging, asserted here:++ 1. Opt-in only. With TRUNK_RESIDENT_LAYERS unset the resident path is unchanged,+ and a value >= n_layers is a no-op (all layers stay resident).+ 2. RAM traded for page faults, never tokens. TRUNK_RESIDENT_LAYERS=0 must decode+ the SAME token ids as the resident baseline while reporting a LOWER+ `resident dense` footprint -- if the knob silently changed the tokens, or+ failed to hand the trunk pages to mmap, this fails.++Why a QUANTIZED fixture: qt_load_mmap() only views tensors that carry an on-disk+int4 companion (`name.qs`). On the bf16 `glm_tiny` oracle every dense tensor falls+back to the resident path, `resident_bytes` never drops, and the test would pass+vacuously. CI therefore converts the oracle to int4 (tools/convert_fp8_to_int4.py)+and points this test at that container -- see the `efficiency` job in+.github/workflows/ci.yml.++Gated: skips (never fails) when the engine or the quantized fixture is absent, the+same contract as the rest of the tiny-model suite -- `make check` is+dependency-free (#140), so a clean host must skip rather than fail.+"""+import json+import os+import re+import struct+import unittest+from pathlib import Path++from tools.efficiency import run_engine++HERE = Path(__file__).resolve().parent+C_DIR = HERE.parent++# The engine was renamed glm -> colibri; resolve whichever name is built.+ENGINE = next((p for p in (C_DIR / "colibri", C_DIR / "colibri.exe") if p.exists()),+ C_DIR / "colibri")++# Quantized fixture (gitignored, generated by CI / locally). Override with+# GLM_TINY_I4 to point at a different int4 container.+QUANT = Path(os.environ.get("GLM_TINY_I4", str(C_DIR / "glm_tiny_i4")))++# "GLM C engine : 1783 1729 6792 ..." -- the greedy ids the engine produced.+ENGINE_IDS_RE = re.compile(r"GLM C engine\s*:\s*([0-9]+(?:\s+[0-9]+)*)")+++def _ref_path():+ """The oracle ref the engine reads in validation mode.++ convert_fp8_to_int4.py copies config.json but NOT ref_glm.json, so accept+ either the ref next to the fixture or the repo-root ref the oracle writes.+ """+ for p in (QUANT / "ref_glm.json", C_DIR / "ref_glm.json"):+ if p.exists():+ return p+ return None+++def _safetensors_keys(path):+ """Tensor names in a single-file .safetensors, without loading any data.++ Format: u64-LE header length, then that many bytes of JSON. Used only to+ confirm the fixture carries `.qs` sidecars (i.e. it is actually quantized).+ """+ with open(path, "rb") as f:+ (n,) = struct.unpack("<Q", f.read(8))+ header = json.loads(f.read(n))+ return header.keys()+++def _quantized_fixture_present():+ """True iff the fixture dir exists AND its shards hold an int4 container.++ A bf16/f32 container (no `.qs` keys) would make the mmap path fall back to+ resident for every tensor, turning the assertion into a vacuous pass -- so+ treat it as "not usable" and skip instead of asserting.++ Naming: convert_fp8_to_int4.py writes `out-NNNNN.safetensors` (the loader+ scans every `*.safetensors`, st.h), a full checkpoint ships `model.safetensors`+ or `model-...-of-...safetensors`, so glob rather than assume one name.+ """+ if not (QUANT / "config.json").exists():+ return False+ shards = sorted(QUANT.glob("*.safetensors"))+ if not shards:+ return False+ try:+ return any(k.endswith(".qs") for k in _safetensors_keys(shards[0]))+ except Exception:+ return False+++def _skip_reason() -> str:+ """Name exactly which prerequisite is missing, so the skip is actionable."""+ if not ENGINE.exists():+ return "colibri not built (run: make -C c colibri)"+ if not _quantized_fixture_present():+ return (f"quantized trunk fixture absent or not int4: {QUANT} "+ f"(run: tools/make_glm_oracle.py --fp8 && "+ f"tools/convert_fp8_to_int4.py --indir glm_tiny "+ f"--outdir glm_tiny_i4 --ebits 4 --io-bits 4)")+ if _ref_path() is None:+ return (f"oracle ref absent (expected {QUANT}/ref_glm.json or "+ f"{C_DIR}/ref_glm.json)")+ return ""++[email protected](not _skip_reason(), _skip_reason() or "quantized glm_tiny_i4 required")+class TrunkResidentLayersTest(unittest.TestCase):+ """The opt-in contract of TRUNK_RESIDENT_LAYERS on the quantized tiny model."""++ def _run(self, **overlay):+ env = {"COLI_TEMP": "0", "REF": str(_ref_path())} # greedy + fixture oracle+ env.update(overlay)+ return run_engine(env, engine=str(ENGINE), snap=str(QUANT))++ def _ids(self, proc):+ m = ENGINE_IDS_RE.search(proc.stdout or "")+ self.assertIsNotNone(+ m, f"no 'GLM C engine' id line in stdout:\n{proc.stdout}\n{proc.stderr}")+ return [int(x) for x in m.group(1).split()]++ def _resident_mb(self, telemetry):+ self.assertIn("load", telemetry["parsed"],+ f"load banner missing (no `resident dense` line):\n"+ f"{telemetry.get('stderr', '')}")+ return telemetry["load"]["resident_dense_mb"]++ def test_zero_layer_keep_tokens_and_lower_resident(self):+ """TRUNK_RESIDENT_LAYERS=0 vs unset: identical tokens, lower resident dense.++ This is the load-bearing assertion. The mmap view points at the SAME+ quantized bytes the resident path would have copied, so the decode must+ be identical; the only difference is *where* the trunk lives (pageable+ file-backed pages instead of wired qalloc slabs). A dropped resident+ number with different tokens would mean the view path reads the wrong+ bytes; identical tokens with an unchanged resident number would mean the+ knob did nothing."""+ base_t, base_p = self._run() # knob UNSET+ optin_t, optin_p = self._run(TRUNK_RESIDENT_LAYERS="0") # trunk all mmap++ for name, t in (("baseline", base_t), ("opt-in", optin_t)):+ self.assertEqual(t["returncode"], 0,+ f"{name} exited non-zero:\n{t.get('stderr', '')}")++ ids_base, ids_optin = self._ids(base_p), self._ids(optin_p)+ self.assertTrue(ids_base, "baseline produced no tokens")+ self.assertEqual(+ ids_base, ids_optin,+ "TRUNK_RESIDENT_LAYERS changed the decoded tokens -- the mmap view "+ "path must be byte-identical to the resident path")++ rb, ro = self._resident_mb(base_t), self._resident_mb(optin_t)+ self.assertLess(+ ro, rb,+ f"`resident dense` did not drop ({rb} -> {ro} MB): the trunk pages "+ f"were not actually handed to mmap (knob set but no effect)")++ def test_unset_and_above_nlayers_are_noops(self):+ """Unset and >= n_layers both change nothing (condition 1 of the review).++ Reloading the whole model at each layer count would be wasteful, so this+ checks the boundary value only: a knob above the layer count must leave+ both the tokens and the resident footprint exactly as the unset path."""+ base_t, base_p = self._run()+ self.assertEqual(base_t["returncode"], 0, f"baseline failed:\n{base_t.get('stderr', '')}")+ n_layers = base_t["load"]["layers"]++ high_t, high_p = self._run(TRUNK_RESIDENT_LAYERS=str(n_layers + 2))+ self.assertEqual(high_t["returncode"], 0, f"above-N run failed:\n{high_t.get('stderr', '')}")++ self.assertEqual(+ self._ids(base_p), self._ids(high_p),+ "TRUNK_RESIDENT_LAYERS >= n_layers changed the decoded tokens")+ self.assertEqual(+ self._resident_mb(base_t), self._resident_mb(high_t),+ "TRUNK_RESIDENT_LAYERS >= n_layers changed `resident dense` "+ "(must be a no-op above the layer count)")+++if __name__ == "__main__":+ unittest.main()