Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(qwen36): derive the default expert-cache cap from host RAM instead of a hardcoded 16
Jaapjan Tinbergenfca88a819d02
diff --git a/c/Makefile b/c/Makefileindex 42442964..25bdb85f 100644--- a/c/Makefile+++ b/c/Makefile@@ -1590,6 +1590,10 @@ tests/test_qwen36_encode_oom$(EXE): tests/test_qwen36_encode_oom.c qwen36.c $(QWtests/test_qwen36_slot_int8$(EXE): tests/test_qwen36_slot_int8.c qwen36.c $(QWEN36_TIER_OBJ) $(CUDA_OBJ) $(VK_OBJ)$(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_OBJ) $(CUDA_OBJ) $(VK_OBJ) -o $@ $(QWEN36_LDFLAGS)+# qwen36_cap_for_ram(): the cap<=0 "auto" sentinel's RAM-derived slot count.+tests/test_qwen36_cap_precedence$(EXE): tests/test_qwen36_cap_precedence.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)+ $(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)+# the dense trunk's integer path: quantizer contract, int4 planar packing, dispatch.tests/test_qwen36_dense_idot$(EXE): tests/test_qwen36_dense_idot.c qwen36.c $(QWEN36_TIER_OBJ) $(CUDA_OBJ) $(VK_OBJ)$(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_OBJ) $(CUDA_OBJ) $(VK_OBJ) -o $@ $(QWEN36_LDFLAGS)diff --git a/c/qwen36.c b/c/qwen36.cindex f6072fd5..80673482 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -902,6 +902,9 @@ static void pilot_prefetch(Model *m, int lnext, const float *x, int S);static void *pilot_worker(void *arg);static void ensure_pilot_worker_started(Model *m);static void slot_ensure_allocated(Model *m, Slot *s);+static int qwen36_cap_for_ram(double resident_gb, double avail_gb, double ram_gb_override,+ int hidden, int inter, int n_experts, int n_active_layers,+ int is_int4, double *slot_gb_out, double *budget_gb_out);#ifdef COLI_CACHE_INDEX_TESTstatic uint64_t g_slot_index_probes;@@ -989,6 +992,8 @@ static double rss_gb(void) { struct rusage r; getrusage(RUSAGE_SELF, &r); return#elsestatic double rss_gb(void) { struct rusage r; getrusage(RUSAGE_SELF, &r); return r.ru_maxrss / (1024.0*1024.0); }#endif+/* same wrapper convention as colibri.c/olmoe.c/inkling.c/kimi_k3.c/deepseek_v4.c */+static double mem_available_gb(void) { return compat_mem_available_gb(); }/* ---- M-PROF (R2): per-phase wall-clock accumulators, COLI_TIMERS=1 ---- */static int g_timers = -1;@@ -2237,6 +2242,31 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,if (quantize_dense)fprintf(stderr, "[dense-i8] %d matrices %s during load, %.1f GB f32 freed\n", qcount,dense_bits() == 16 ? "kept in f16" : "quantized", qfreed/1073741824.0);+ if (cap <= 0) {+ /* cap<=0 sentinel: derive from host RAM, same "0 = auto" convention as+ * colibri.c/olmoe.c. rss_gb() here reflects all dense weights resident+ * (this loop just finished) but not yet DN_rec/DN_conv/m->cache+ * themselves (allocated below) -- a known, small underestimate left+ * inside the 12% margin rather than reordering allocation here.+ * xf_mode(m) is resolvable at this point (st_init/active_of already+ * ran) but is memoized process-globally, not per-Model* -- a+ * pre-existing, unrelated bug if this process ever builds two models+ * with different container formats (out of scope here). */+ double resident = rss_gb();+ double avail = mem_available_gb();+ const char *ram_env = getenv("RAM_GB");+ double ram_override = ram_env ? atof(ram_env) : 0.0;+ int n_active = layer_end - layer_begin;+ double slot_gb = 0.0, budget_gb = 0.0;+ cap = qwen36_cap_for_ram(resident, avail, ram_override,+ c->hidden, c->inter, c->n_experts, n_active,+ xf_mode(m), &slot_gb, &budget_gb);+ fprintf(stderr, "[qwen36] cache auto-sized: %d slots/layer of %d experts "+ "(%.1f GB budget via %s, %.1f GB dense resident, %.0f MB/slot)\n",+ cap, c->n_experts, budget_gb,+ ram_override > 0.0 ? "RAM_GB" : "88% of available RAM",+ resident, slot_gb * 1000.0);+ }m->cache = calloc((size_t)c->n_layers, sizeof(LCache));for (int i = layer_begin; i < layer_end; i++) {m->cache[i].cap = cap;@@ -2285,6 +2315,31 @@ static int64_t scale_count_gu(const Cfg *c){ return c->expert_gs ? (int64_t)c->istatic int down_gs_of(const Cfg *c){ return c->expert_down_bits ? c->expert_down_gs : c->expert_gs; }static int64_t scale_count_d (const Cfg *c){ int gs = down_gs_of(c); return gs ? (int64_t)c->hidden * ((c->inter + gs - 1) / gs) : c->hidden; }+/* Pure: no Model pointer, no globals, no I/O, same testability contract as+ * coli_resolve_cap / k3_cap_for_ram. cap<=0 sentinel ("auto") resolves to+ * this. Mirrors olmoe.c's cap<=0 budget block (resident + avail*0.88, same+ * margin as colibri.c's cap_for_ram), extended with the int4/xf_mode slot-size split that+ * slot_ensure_allocated() above uses (half the int8 bytes) and with+ * n_active_layers instead of always c->n_layers, for the Segment/Edge+ * partial-model layer-range builds. Approximates the scale-float block the+ * same way olmoe.c does (ignores expert_gs grouping precision) -- this is a+ * budget estimate under a safety margin, not exact accounting. */+static int qwen36_cap_for_ram(double resident_gb, double avail_gb, double ram_gb_override,+ int hidden, int inter, int n_experts, int n_active_layers,+ int is_int4, double *slot_gb_out, double *budget_gb_out) {+ double budget = ram_gb_override > 0.0 ? ram_gb_override : resident_gb + avail_gb * 0.88;+ if (budget_gb_out) *budget_gb_out = budget;+ double room = budget - resident_gb;+ double per_expert = (double)hidden * inter * (is_int4 ? 1.5 : 3.0);+ double slot_gb = (per_expert + (double)(inter * 2 + hidden) * sizeof(float)) / 1e9;+ if (slot_gb_out) *slot_gb_out = slot_gb;+ int layers = n_active_layers < 1 ? 1 : n_active_layers;+ int derived = room > 0.0 && slot_gb > 0.0 ? (int)(room / slot_gb / (double)layers) : 0;+ if (derived < 1) derived = 1;+ if (n_experts > 0 && derived > n_experts) derived = n_experts;+ return derived;+}+static void slot_ensure_allocated(Model *m, Slot *s) {if (s->g || s->pw) return;Cfg *c = &m->c;@@ -5232,12 +5287,16 @@ int main(int argc, char **argv) {if (getenv("OPENAI")) g_openai = 1; /* OpenAI-compatible output */const char *mv = getenv("MODEL"); if (mv && *mv) g_model = mv;int hot_n = getenv("HOT") ? atoi(getenv("HOT")) : 0;- int cap = argc > 1 ? coli_arg_int(argv[1], "cache/layer") : 16;+ int cap = argc > 1 ? coli_arg_int(argv[1], "cache/layer") : 0;int bits = argc > 2 ? coli_arg_int(argv[2], "expert bits") : 4;- /* cap < 1 leaves every layer cache empty, so expert_get finds no slot to- * evict and waits for a publish that can never come. The old lru=0 fallback- * turned that into a heap OOB instead; neither is a failure mode to ship. */- if (cap < 1) { fprintf(stderr, "cache/layer must be >= 1 (got %d)\n", cap); return 1; }+ /* cap<=0 (explicit 0, or bare omission above) is the "auto-size from host+ * RAM" sentinel resolved later in model_init_range, once dense weights are+ * resident and xf_mode is known -- see qwen36_cap_for_ram(). The invariant+ * that a cap<1 must never reach the per-layer calloc (expert_get would+ * then find no slot to evict and wait for a publish that can never come;+ * the old lru=0 fallback turned that into a heap OOB instead) still holds,+ * just enforced there instead of only here for the auto path. */+ if (cap < 0) { fprintf(stderr, "cache/layer must be >= 0 (0 = auto; got %d)\n", cap); return 1; }if (bits < 2 || bits > 8) { fprintf(stderr, "quant_bits must be 2..8 (got %d)\n", bits); return 1; }const char *refpath = argc > 3 ? argv[3] : "ref.json";@@ -5247,8 +5306,11 @@ int main(int argc, char **argv) {/* #1376: every capacity knob announced itself here except the one that* refuses requests. The context ceiling surfaced only in the* CONTEXT_EXCEEDED line, i.e. after a request had already failed. */- fprintf(stderr, "== qwen36 Phase-2 engine | cache=%d/layer bits=%d ctx=%d pilot=%d wide=%d hot=%d smooth=%.2f conf=%.2f ==\n",- cap, bits, qwen36_max_ctx(), g_pilot, g_wide, hot_n, smooth, conf);+ char cap_disp[16];+ if (cap > 0) snprintf(cap_disp, sizeof cap_disp, "%d", cap);+ else snprintf(cap_disp, sizeof cap_disp, "auto");+ fprintf(stderr, "== qwen36 Phase-2 engine | cache=%s/layer bits=%d ctx=%d pilot=%d wide=%d hot=%d smooth=%.2f conf=%.2f ==\n",+ cap_disp, bits, qwen36_max_ctx(), g_pilot, g_wide, hot_n, smooth, conf);int is_ref = 0;@@ -5739,7 +5801,9 @@ static int qwen36_segment_engine_open("Qwen3.6 Segment range exceeds model");}int range_layers = (int)(options->layer_end - options->layer_begin);- int cap = 16;+ int cap = 0; /* sentinel: model_init_range derives it from host RAM,+ * honoring memory_limit_bytes==0's own doc comment ("uses+ * the adapter's ordinary automatic budget") */if (options->memory_limit_bytes) {uint64_t weights = (uint64_t)config.hidden * config.inter * 3u;uint64_t per_slot = weights +diff --git a/c/tests/test_qwen36_cap_budget.py b/c/tests/test_qwen36_cap_budget.pynew file mode 100644index 00000000..1dbd8851--- /dev/null+++ b/c/tests/test_qwen36_cap_budget.py@@ -0,0 +1,109 @@+"""qwen36 sizes its expert cache from the RAM budget when no explicit cap is+given, instead of the old hardcoded default of 16.++Before this change, bare omission of argv[1] (and the Segment API's+memory_limit_bytes==0 path) reached the engine as a constant that knew+nothing about the model or the machine. cap<=0 (explicit "0" or bare+omission) is now the sentinel that makes model_init_range derive a budget+from host RAM instead (qwen36_cap_for_ram(), see test_qwen36_cap_precedence.c+for the pure-function unit tests of the arithmetic itself).++What is asserted here is the contract, not a speed: the sentinel makes the+engine choose, an explicit cap is left alone, and the choice is bounded by+the budget it was given. The engine prints the derivation, so the assertions+read the line it prints rather than guessing at behaviour. Mirrors+test_olmoe_cap_budget.py's approach for the sibling engine.++Needs a converted tiny Qwen3.6 container and a built engine; set+COLI_QWEN36_FIXTURE to the container directory (same fixture convention as+test_qwen36_dashboard.py).+"""+import os+import re+import subprocess+import unittest+from pathlib import Path++HERE = Path(__file__).resolve().parent.parent+ENGINE = HERE / ("qwen36.exe" if os.name == "nt" else "qwen36")+FIXTURE = Path(os.environ.get("COLI_QWEN36_FIXTURE", ""))+CACHE_LINE = re.compile(r"^\[qwen36\] cache auto-sized: (\d+) slots/layer of (\d+) experts", re.M)++# The tiny toy fixture (make_qwen36_tiny.py's default qwen36-35b geometry:+# hidden=64, inter=32, 8 experts) has a per-slot cost of only a few KB, so a+# RAM_GB comfortably below a real model's floor (e.g. 0.4, as the sibling+# OLMoE test uses) still clamps this fixture's derived cap at n_experts+# instead of flooring at 1. Use a value tiny enough to underflow even this+# toy geometry's floor.+BELOW_FLOOR_RAM_GB = 0.000001+++def derived_cap(ram_gb=None, cap="0"):+ """Run the engine far enough to print its cache line, then stop it."""+ environment = {**os.environ, "SNAP": str(FIXTURE), "SERVE": "1"}+ if ram_gb is not None:+ environment["RAM_GB"] = str(ram_gb)+ else:+ environment.pop("RAM_GB", None)+ finished = subprocess.run([str(ENGINE), cap, "8"], input=b"",+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,+ env=environment, timeout=120)+ match = CACHE_LINE.search(finished.stderr.decode("utf-8", "replace"))+ return (int(match.group(1)), int(match.group(2))) if match else (None, None)++[email protected](ENGINE.exists(), "qwen36 engine is not built")[email protected](FIXTURE.name and (FIXTURE / "config.json").is_file(),+ "COLI_QWEN36_FIXTURE not set to a converted Qwen3.6 container")+class Qwen36CapBudgetTest(unittest.TestCase):+ def test_an_explicit_cap_is_never_second_guessed(self):+ cap, _ = derived_cap(ram_gb=64, cap="4")+ self.assertIsNone(cap, "the engine re-derived a cap the caller had chosen")++ def test_a_generous_budget_holds_every_expert(self):+ cap, experts = derived_cap(ram_gb=64)+ self.assertIsNotNone(cap, "the sentinel produced no cache line")+ self.assertEqual(cap, experts,+ "a budget with room for the whole expert set should hold it")++ def test_a_budget_below_the_floor_still_runs(self):+ """Not an error: one slot per layer is slow, refusing to start is worse."""+ cap, experts = derived_cap(ram_gb=BELOW_FLOOR_RAM_GB)+ self.assertEqual(cap, 1)+ self.assertGreater(experts, 1)++ def test_the_budget_bounds_the_choice(self):+ small, _ = derived_cap(ram_gb=BELOW_FLOOR_RAM_GB)+ large, _ = derived_cap(ram_gb=64)+ self.assertLess(small, large,+ "the derived cap ignored the budget it was given")++ def test_without_a_budget_it_still_decides(self):+ cap, experts = derived_cap(ram_gb=None)+ self.assertIsNotNone(cap, "no RAM_GB must mean 'measure', not 'give up'")+ self.assertGreaterEqual(cap, 1)+ self.assertLessEqual(cap, experts)++ def test_bare_omission_matches_explicit_zero(self):+ """The user's ask: the bare-CLI default (argv[1] omitted) must be the+ same sentinel as an explicit cap=0, not the old hardcoded 16. qwen36's+ argv is purely positional (no flags), so bits can only be given+ explicitly alongside an explicit cap -- the true bare invocation+ (argc==1) also leaves bits at its own default (4), so the equivalent+ explicit form is "0 4", not "0 8"."""+ environment = {**os.environ, "SNAP": str(FIXTURE), "SERVE": "1", "RAM_GB": "8"}+ bare = subprocess.run([str(ENGINE)], input=b"",+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,+ env=environment, timeout=120)+ explicit = subprocess.run([str(ENGINE), "0", "4"], input=b"",+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,+ env=environment, timeout=120)+ bare_match = CACHE_LINE.search(bare.stderr.decode("utf-8", "replace"))+ explicit_match = CACHE_LINE.search(explicit.stderr.decode("utf-8", "replace"))+ self.assertIsNotNone(bare_match, "bare argv[1] omission produced no auto-sized line")+ self.assertIsNotNone(explicit_match, "explicit cap=0 produced no auto-sized line")+ self.assertEqual(bare_match.group(0), explicit_match.group(0))+++if __name__ == "__main__":+ unittest.main()diff --git a/c/tests/test_qwen36_cap_precedence.c b/c/tests/test_qwen36_cap_precedence.cnew file mode 100644index 00000000..338f461a--- /dev/null+++ b/c/tests/test_qwen36_cap_precedence.c@@ -0,0 +1,105 @@+/* qwen36_cap_for_ram(): the cap<=0 ("auto") sentinel derives the expert-cache+ * slots/layer from host RAM instead of the old hardcoded default of 16+ * (bare CLI omission) / 16 (Segment API's memory_limit_bytes==0 fallback).+ * Pure function -- no Model*, no globals, no I/O -- same testability+ * contract as k3_cap_for_ram/coli_resolve_cap (test_k3_ram_budget.c,+ * test_cap_precedence.c). An explicit cap>0 never reaches this function at+ * all (main()/qwen36_segment_engine_open() only call it when cap<=0), so+ * "explicit cap always wins" is verified at the integration level+ * (test_qwen36_cap_budget.py), not here. Likewise, RAM_GB parsing itself+ * (getenv/atof) happens in model_init_range, not this function -- an+ * unparseable or negative RAM_GB reaches this function as ram_gb_override<=0+ * (atof's own behavior on garbage input), which is exactly what the+ * "override<=0 falls back to the computed budget" case below exercises. */+#define main qwen36_main_unused+#include "../qwen36.c"+#undef main++static int fails = 0;+#define CHECK(c) do { if (!(c)) { fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)++/* Roughly qwen36-i4-gs64 shape: hidden=2048 inter=512 n_experts=256. */+enum { HIDDEN = 2048, INTER = 512, N_EXPERTS = 256 };++int main(void) {+ /* RAM_GB override wins over the resident+avail*0.88 computed budget:+ * same resident/avail, only the override differs -> different cap. The+ * outparams (slot_gb, budget_gb) are threaded through rather than+ * recomputed by any caller, so budget_gb must equal the override+ * exactly when one is given. */+ {+ double slot_gb_a = 0, slot_gb_b = 0, budget_a = 0, budget_b = 0;+ int cap_computed = qwen36_cap_for_ram(4.83, 20.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, &slot_gb_a, &budget_a);+ int cap_override = qwen36_cap_for_ram(4.83, 20.0, 64.0, HIDDEN, INTER, N_EXPERTS, 40, 0, &slot_gb_b, &budget_b);+ CHECK(cap_override > cap_computed);+ CHECK(slot_gb_a == slot_gb_b); /* override changes the budget, not the per-slot size */+ CHECK(budget_a == 4.83 + 20.0 * 0.88);+ CHECK(budget_b == 64.0);+ }++ /* A negative or zero override (e.g. RAM_GB unset, or set to garbage that+ * atof() parses as 0, or set to a negative number) is not an error --+ * it must fall back to the computed budget exactly as if RAM_GB had+ * never been read, not propagate a negative/zero budget. */+ {+ double budget_unset = 0, budget_negative = 0, budget_zero = 0;+ int cap_unset = qwen36_cap_for_ram(4.83, 20.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, &budget_unset);+ int cap_negative = qwen36_cap_for_ram(4.83, 20.0, -5.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, &budget_negative);+ int cap_zero = qwen36_cap_for_ram(4.83, 20.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, &budget_zero);+ CHECK(cap_unset == cap_negative && cap_unset == cap_zero);+ CHECK(budget_unset == budget_negative && budget_unset == budget_zero);+ }++ /* int4 (xf_mode) halves the per-slot byte cost of int8, so for identical+ * budget/geometry it derives a cap at least as large, strictly larger in+ * the constrained-budget middle of the range (not floored, not clamped+ * at n_experts on either side). */+ {+ double slot_gb_int8 = 0, slot_gb_int4 = 0;+ int cap_int8 = qwen36_cap_for_ram(4.83, 3.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, &slot_gb_int8, NULL);+ int cap_int4 = qwen36_cap_for_ram(4.83, 3.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 1, &slot_gb_int4, NULL);+ CHECK(slot_gb_int4 < slot_gb_int8);+ CHECK(cap_int4 >= cap_int8);+ CHECK(cap_int4 > 1 && cap_int4 < N_EXPERTS);+ CHECK(cap_int8 > 1 && cap_int8 < N_EXPERTS);+ CHECK(cap_int4 > cap_int8);+ }++ /* A budget at or below the resident floor still returns a usable cap>=1+ * -- never 0, which would leave every layer's cache empty (expert_get+ * would then find no slot to evict and hang; see the comment above the+ * cap<0 CLI check in main()). */+ {+ int cap = qwen36_cap_for_ram(4.83, 0.0, 4.83, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, NULL);+ CHECK(cap == 1);+ int cap_neg_room = qwen36_cap_for_ram(4.83, 0.0, 1.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, NULL);+ CHECK(cap_neg_room == 1);+ }++ /* A huge budget clamps at n_experts, never runs past it. */+ {+ int cap = qwen36_cap_for_ram(4.83, 1000.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, NULL);+ CHECK(cap == N_EXPERTS);+ }++ /* n_active_layers scales the derived cap: the same total budget spread+ * over twice as many layers yields roughly half the per-layer slots+ * (Segment/Edge partial-model builds pass layer_end-layer_begin here,+ * not always the model's full n_layers). */+ {+ int cap_40 = qwen36_cap_for_ram(4.83, 3.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, NULL);+ int cap_80 = qwen36_cap_for_ram(4.83, 3.0, 0.0, HIDDEN, INTER, N_EXPERTS, 80, 0, NULL, NULL);+ CHECK(cap_80 < cap_40);+ CHECK(cap_80 >= cap_40 / 2 - 1 && cap_80 <= cap_40 / 2 + 1);+ }++ /* Degenerate inputs don't crash and still return a floored cap. */+ {+ CHECK(qwen36_cap_for_ram(4.83, 3.0, 0.0, HIDDEN, INTER, N_EXPERTS, 0, 0, NULL, NULL) >= 1);+ CHECK(qwen36_cap_for_ram(4.83, 3.0, 0.0, HIDDEN, INTER, N_EXPERTS, -1, 0, NULL, NULL) >= 1);+ CHECK(qwen36_cap_for_ram(0.0, 0.0, 0.0, HIDDEN, INTER, N_EXPERTS, 40, 0, NULL, NULL) >= 1);+ }++ printf(fails ? "test_qwen36_cap_precedence: FAIL (%d)\n" : "test_qwen36_cap_precedence: PASS\n", fails);+ return fails != 0;+}