Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
clef: f16 trunk when the planner's budget holds it, context 16384 by default
JustVugg65a2574b2295
diff --git a/c/coli b/c/coliindex c20f51a7..8c4060ed 100755--- a/c/coli+++ b/c/coli@@ -795,8 +795,12 @@ def cuda_binary(engine=None):return Falsedef resource_request(a, env):- family=resolve_model(a.model).descriptor if getattr(a,"model",None) else family_by_id("glm")- ctx=a.ctx or int(env.get(family.limits.context_env,family.limits.default_context))+ from family_registry import default_context+ resolved=resolve_model(a.model) if getattr(a,"model",None) else None+ family=resolved.descriptor if resolved else family_by_id("glm")+ # a Clef checkpoint plans for its own 16384 (family_registry.default_context)+ fallback=default_context(resolved) if resolved else family.limits.default_context+ ctx=a.ctx or int(env.get(family.limits.context_env,fallback))if ctx<1 or ctx>family.limits.max_context:raise ValueError(f"--ctx must be between 1 and {family.limits.max_context} "f"for {family.display_name}")diff --git a/c/family_registry.py b/c/family_registry.pyindex cd575597..79c56e5f 100644--- a/c/family_registry.py+++ b/c/family_registry.py@@ -196,13 +196,21 @@ class DecisionHead:model_id: str# (geometry, display_scale): the backbone sizes the head ships onscales: tuple = ()+ # The context a checkpoint with this head gets when nothing asks for another:+ # the head's own input budget (Clef's encode_record max_length). 0 = the family's.+ default_context: int = 0+ # COLI_DENSE_BITS the gateway sets when the planner's RAM budget holds the+ # trunk at that width (docs/clef.md: int8 moves Clef's probabilities by up to+ # 0.22, f16 by 0.012). 0 = the engine's own default.+ precise_dense_bits: int = 0DECISION_HEADS = (DecisionHead("clef", "qwen36", ("joint_head_config.json", "joint_head.safetensors"),"Clef", "clef",scales=(((("num_hidden_layers", 64), ("hidden_size", 5120),- ("intermediate_size", 17408)), "27B"),)),+ ("intermediate_size", 17408)), "27B"),),+ default_context=16384, precise_dense_bits=16),)@@ -214,6 +222,15 @@ def decision_head_of(resolved):return None+def default_context(resolved):+ """The context a resolved checkpoint runs at when none is asked for: its+ decision head's own budget (Clef: 16384), else the family's default."""+ head = decision_head_of(resolved)+ if head and head.default_context:+ return head.default_context+ return resolved.descriptor.limits.default_context++def checkpoint_decides(resolved):"""True when the checkpoint answers POST /v1/systemone natively: a decisionfamily (Laya), or a text family with a decision head (Clef)."""diff --git a/c/openai_server.py b/c/openai_server.pyindex 2494c857..165eb73a 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -4761,6 +4761,49 @@ def cap_for_arch(arch, cap, env=None, model=None):return family_by_id(arch).limits.implicit_cap+def decision_head_env(env, model):+ """The dense trunk's width for a checkpoint with a decision head (Clef), when+ the operator set none: the head's precise width (f16) if the planner's RAM+ budget holds the trunk at that size, the engine's int8 otherwise. Measured on+ Clef against its reference in bf16 (docs/clef.md): int8 moves a probability+ by up to 0.22, f16 by 0.012, at 2.3x the time. Returns the line it printed,+ or None when it had nothing to decide."""+ if env.get("COLI_DENSE_BITS"):+ return None+ from family_registry import decision_head_of, default_context+ try:+ resolved = resolve_model(model)+ except Exception: # not a checkpoint this can read: nothing to decide+ return None+ head = decision_head_of(resolved)+ if not head or not head.precise_dense_bits:+ return None+ try:+ from resource_plan import build_plan+ limits = resolved.descriptor.limits+ context = int(env.get(limits.context_env) or default_context(resolved))+ ram = env.get("RAM_GB", "0")+ plan = build_plan(model, ram_gb=0 if ram in ("", "auto") else float(ram), context=context,+ gpu_indices=[])+ except Exception as error: # the engine's own default stands+ line = f"[{head.id}] dense trunk left at the engine's default (no plan: {error})"+ print(line, file=sys.stderr)+ return line+ tier = plan["tiers"]["ram"]+ need = (tier["dense_bytes"] + tier["runtime_bytes"] + tier["sequence_state_bytes"]+ + tier["fixed_state_bytes"])+ gib = 1 << 30+ if need <= tier["budget_bytes"]:+ env["COLI_DENSE_BITS"] = str(head.precise_dense_bits)+ line = (f"[{head.id}] dense trunk in f16: {need / gib:.1f} GiB fit the {tier['budget_bytes'] / gib:.1f} "+ f"GiB budget (COLI_DENSE_BITS=8 for int8, faster and less exact)")+ else:+ line = (f"[{head.id}] dense trunk in int8: f16 would need {need / gib:.1f} GiB, the budget is "+ f"{tier['budget_bytes'] / gib:.1f} GiB (COLI_DENSE_BITS=16 to force it)")+ print(line, file=sys.stderr)+ return line++def tune_child_env(env, arch):"""Apply the engine-local defaults that a direct server launch otherwise misses.@@ -5118,6 +5161,7 @@ class Engine:child_env = dict(env or os.environ, SNAP=str(model), SERVE="1", SERVE_BATCH="1",NGEN=str(max_tokens), KV_SLOTS=str(kv_slots))tune_child_env(child_env, arch)+ decision_head_env(child_env, model)resolved_cap = cap_for_arch(arch, cap, child_env, model=model)child_env.pop("COLI_PROFILE_CAP", None)child_env.pop("COLI_PLAN_CAP", None)diff --git a/c/qwen36.c b/c/qwen36.cindex 1dc6bbfc..f6072fd5 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -47,10 +47,14 @@/* Effective ceiling: Q36_MAXT if set and sane, the conservative default* otherwise; never above the hard limit. */+/* A Clef checkpoint raises the default to its own input budget, 16384 (clef_head.h):+ * the KV rows are allocated as a request needs them, so the ceiling costs nothing+ * until a record that long arrives (2 GiB of f32 rows on the 27B at 16384). */+static int g_q36_default_ctx = QWEN36_DEFAULT_MAX_CTX;static int qwen36_max_ctx(void) {const char *e = getenv("Q36_MAXT");- int v = (e && *e) ? atoi(e) : QWEN36_DEFAULT_MAX_CTX;- if (v < 1) v = QWEN36_DEFAULT_MAX_CTX;+ int v = (e && *e) ? atoi(e) : g_q36_default_ctx;+ if (v < 1) v = g_q36_default_ctx;return v > QWEN36_ATTN_MAX_CTX ? QWEN36_ATTN_MAX_CTX : v;}#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)@@ -4822,6 +4826,7 @@ static void q36_clef_load(Model *m, const char *snap){if (g_clef_max_len < 1) { fprintf(stderr, "[clef] COLI_CLEF_MAX_LEN must be positive\n"); exit(1); }}g_clef = 1;+ if (g_clef_max_len > g_q36_default_ctx) g_q36_default_ctx = g_clef_max_len;fprintf(stderr, "[clef] decision head: %d routing + %d decoder layers, width %d, %d heads; ""a record reads up to %d tokens (the engine's context is %d)\n",h->routing_layers, h->layers, h->width, h->heads, g_clef_max_len, qwen36_max_ctx());@@ -4839,8 +4844,9 @@ static int q36_clef_decide(Model *m, const DecideRecord *rec, DecideAnswer *answif (in.n > max_ctx) {int n = in.n;clef_input_free(&in);- return decide_fail(err, cap, "record: %d tokens do not fit this engine's context of %d "- "(Q36_MAXT; Clef itself reads up to %d)", n, max_ctx, g_clef_max_len);+ return decide_fail(err, cap, "record: %d tokens do not fit this engine's context of %d, "+ "set by Q36_MAXT (Clef itself reads up to %d; unset, the context is that)",+ n, max_ctx, g_clef_max_len);}float *hidden = (float *)malloc((size_t)in.n * c->hidden * sizeof(float));double **logits = (double **)calloc((size_t)in.n_q, sizeof(double *));diff --git a/c/tests/test_decision_serve.py b/c/tests/test_decision_serve.pyindex f2f519b0..32a2d53b 100644--- a/c/tests/test_decision_serve.py+++ b/c/tests/test_decision_serve.py@@ -633,6 +633,21 @@ class ClefTinyEndToEnd(unittest.TestCase):self.assertEqual(second["answers"], first["answers"])self.check("model_card_systemone", second)+ def test_the_gateway_keeps_clefs_trunk_in_f16_when_the_budget_holds_it(self):+ """int8 moves Clef's probabilities by up to 0.22 on the real checkpoint, f16 by+ 0.012 (docs/clef.md): the gateway picks f16 when the planner's RAM budget+ holds it, int8 otherwise, and an operator's own COLI_DENSE_BITS wins."""+ env = {}+ openai_server.decision_head_env(env, str(CLEF_CONTAINER))+ self.assertEqual(env.get("COLI_DENSE_BITS"), "16")+ env = {"RAM_GB": "0.001"}+ self.assertIn("int8", openai_server.decision_head_env(env, str(CLEF_CONTAINER)))+ self.assertNotIn("COLI_DENSE_BITS", env)+ env = {"COLI_DENSE_BITS": "4"}+ self.assertIsNone(openai_server.decision_head_env(env, str(CLEF_CONTAINER)))+ self.assertEqual(env, {"COLI_DENSE_BITS": "4"})+ self.assertIsNone(openai_server.decision_head_env({}, str(HERE / "laya_tiny")))+def test_a_schema_past_the_budget_is_a_422(self):"""COLI_CLEF_MAX_LEN is the reference's max_length: past it the schema alonedoes not fit and the request is the caller's 422, not a 500."""diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex fbd9e5b3..34739a87 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -457,14 +457,14 @@ and the CPU/GPU execution split.| `COLI_DENSE_I8` | `1` (on) | Quantize resident dense matrices to per-row int8 at startup. `=0` keeps the f32 reference path for quality A/Bs. || `COLI_DENSE_IDOT` | `1` (on) | The dense trunk's GEMVs (DeltaNet projections and out_proj, attention q/k/v/o, shared expert, lm_head) quantize the activation to int8 once per call and run integer dot products (maddubs on AVX2, vpdpbusd on AVX-VNNI / AVX-512 VNNI) instead of converting every int8 weight to f32. Not bit-identical to the f32 path; measured +1.0% perplexity, lm_head 12.6 to 10.2 ms/token. `=0` restores the f32-activation kernel. || `QWEN_EXPERT_ACT` | `i8` | The routed experts' activation quantized to int8 once per row (expert_ffn.h mode 1). Measured +0.1% perplexity, expert compute 22.7 to 15.9 ms/token. `=f32` restores f32 activations and the bit-identical contract with the pair kernels. |-| `COLI_DENSE_BITS` | `8` | `=4` stores the dense trunk as int4 in blocks of 64 with one scale per block (the K1b planar layout, half the bytes), served by the grouped integer kernel; implies the integer dot. Opt-in: on the 35B it costs +10% perplexity on the whole trunk, +2.4% on lm_head alone (see `COLI_DENSE_INT4`). |+| `COLI_DENSE_BITS` | `8` (a Clef checkpoint under the gateway: `16` when the planner's RAM budget holds it, docs/clef.md) | `=4` stores the dense trunk as int4 in blocks of 64 with one scale per block (the K1b planar layout, half the bytes), served by the grouped integer kernel; implies the integer dot. Opt-in: on the 35B it costs +10% perplexity on the whole trunk, +2.4% on lm_head alone (see `COLI_DENSE_INT4`). qwen36 `=16` keeps the container's f16 values, no quantization, twice int8's RAM: on Clef it moves a probability by 0.012 where int8 moves it by 0.22. || `Q36_MAX_IMAGE_TOKENS` | the checkpoint's preprocessor ceiling | Gateway, qwen36 containers with a vision tower (Qwen3.8-27B): ceiling on the tokens one image costs. The image is shrunk, not cropped. Without one a 1080p photo is about 2000 tokens of tower and prefill on the CPU. || `COLI_DENSE_KEEP_I8` | `0` (off) | qwen36: a matrix that got its int4 copy (`COLI_DENSE_BITS=4`) frees its int8 copy, which only the CUDA placer reads; `=1` keeps both. With `COLI_CUDA=1` both are kept anyway. Measured on Qwen3.8-27B: 42.4 GB resident with both copies, 18.8 GB without. || `COLI_DENSE_INT4` | all components | With `COLI_DENSE_BITS=4`, a comma list of the components that take int4: `lmhead`, `dnproj`, `dnout`, `attn`, `shexp`, `router`. Measured on the 35B: `lmhead` +2.4% perplexity for 254 MB less per token; `lmhead,dnproj,dnout` +5.6%; everything +10%. || `QWEN_EXPERT_KERNEL` | `1` (on) | Routed experts run through the shared `expert_ffn.h` kernel: the int4 stays packed in RAM (planar layout, half the expert-cache RSS of the int8 unpack), gate+up are one pass, and a layer is two OpenMP regions over (expert, row-chunk) items instead of 3 x top-k GEMV regions. Takes effect on an int4 gs=64 container whose hidden and expert widths are multiples of 64, and not under the CUDA expert tier. `=0` restores the unpack-to-int8 path; the two produce the same tokens (1024-token decode on the real container byte-identical; pinned on the tiny int4 fixture in CI), only the f32 accumulation order inside a dot differs. Measured at cap 256 on the real container: 12.8 -> 15.7 tok/s, peak RSS 29 -> 17 GB. || `QWEN_DENSE_BATCH` | `1` (on) | On AVX2/FMA, reuse each dense-int8 weight decode across two prompt rows. `=0` restores one GEMV call per row. Decode `S=1` is unchanged. || `QWEN_SHARED_BATCH` | bounded by 32 MiB scratch | Batch the CPU shared expert across prompt rows. `=0` restores scalar calls; a positive integer caps rows per chunk. The CUDA-tier overlap path is unchanged. |-| `Q36_MAXT` | conservative engine default | Lower the served/context capacity; it cannot raise the model's compiled safety ceiling. |+| `Q36_MAXT` | conservative engine default (16384 for a Clef checkpoint, its own `max_length`) | Lower the served/context capacity; it cannot raise the model's compiled safety ceiling. || `COLI_VULKAN` | `0` | `VK=1` build: the dense trunk on the Vulkan device, and the routed experts on the shared expert tier (`COLI_VK_TIER*`, `COLI_VK_DENSE`, see [Vulkan](#vulkan-any-gpu-with-a-vulkan-12-driver)). With the tier on, the engine keeps the expert history `COLI_USAGE` (default `<snap>/.coli_usage`), saved at every run and serve turn end; it keeps none otherwise. || `Q36_DN_GPU` | `0` (off) | CUDA expert tier: a decode token runs every DeltaNet layer whose in_proj and out_proj sit on one card end to end on that card (conv, recurrence, gated norm; state resident in VRAM). Measured on the 35B, 3070, trunk in VRAM: DeltaNet 16.2 -> 10.8 ms/token, the token 39.4 -> 33.3 ms. See [qwen36-cuda-tier.md](qwen36-cuda-tier.md#the-deltanet-layer-on-the-card-q36_dn_gpu1). || `QT_HOME` | `expert` | CUDA expert tier on two or more cards: `layer` homes every expert of a layer on one card (layer ranges weighted by allowance / probed dense-GEMV time per card, `QT_LAYER_SPLIT=<n>` layers on the first card overrides), with the layer's trunk and, for the last layer, lm_head alongside -- a pipeline instead of a per-layer join. See [qwen36-cuda-tier.md](qwen36-cuda-tier.md#two-cards-as-a-pipeline-qt_homelayer). |diff --git a/docs/clef.md b/docs/clef.mdindex b90b1efc..fcf52615 100644--- a/docs/clef.md+++ b/docs/clef.md@@ -73,8 +73,30 @@ Each step follows the checkpoint's own `joint_schema_model.py` (revision| head | `JointSchemaHead.forward` | `clef_head_forward`: LayerNorm over the hidden states, span means for the instructions and the options, lexical option vectors from the LM head's rows (read at the container's precision, not the int8 copy), two evidence routing layers (options attending to the whole sequence), the option summary per question, four decoder layers over the fields, then `prior + sigmoid(gate) * (scale * cosine + residual)` || answer | `systemone` | a softmax per question; the gateway shapes the Jev reply (`choice`, `score` as the expected level, `noul` as P(true)) |-The head runs in f32 (512 MB). The backbone runs as Qwen3.8-27B does here:-int8 by default (`COLI_DENSE_BITS=4` for int4).+The head runs in f32 (512 MB). The backbone runs at one of three widths,+`COLI_DENSE_BITS`:++| width | RAM (measured RSS) | accuracy vs the reference | speed |+|---|---|---|---|+| f16 (`16`): the container's own values | 55.4 GB | max \|dp\| 0.012 | 47.4 s per request |+| int8 (`8`) | 29 GB | max \|dp\| 0.22 | 20.4 s |+| int4 (`4`) | 19 GB | max \|dp\| 0.22 | 30.2 s |++**Which one runs.** If you set `COLI_DENSE_BITS`, that one. Otherwise `coli+serve`, `coli web` and `coli chat` ask the planner (`coli plan` shows the same+numbers): when its RAM budget holds the trunk at its stored size plus the+runtime and the KV state of 16384 tokens, Clef runs in f16, the width that+answers like the release; when it does not, int8, and the gateway says which on+start-up:++```+[clef] dense trunk in int8: f16 would need 58.9 GiB, the budget is 53.3 GiB (COLI_DENSE_BITS=16 to force it)+```++The planner's margins are its usual ones: on the 61 GB test box f16 ran at+55.4 GB, but the planner keeps it to int8 there. A box with about 72 GB free+gets f16 by default. The engine started by hand (`SERVE=1 ./qwen36`) stays at+int8 unless told otherwise.## Checked against the reference@@ -94,17 +116,19 @@ int8 by default (`COLI_DENSE_BITS=4` for int4).20-intent choice, nine questions in one record) against the release's codein bf16, its own precision:-| engine backbone | input ids | decisions | max \|dp\| |-|---|---|---|---|-| int8 (default) | 15/15 identical | 39/39 | 0.22 |-| int4 (`COLI_DENSE_BITS=4`) | 15/15 identical | 39/39 | 0.22 |+| engine backbone | input ids | decisions | max \|dp\| | requests under 0.01 |+|---|---|---|---|---|+| f16 (`COLI_DENSE_BITS=16`) | 15/15 identical | 39/39 | 0.012 | 14/15 |+| int8 | 15/15 identical | 39/39 | 0.22 | 8/15 |+| int4 (`COLI_DENSE_BITS=4`) | 15/15 identical | 39/39 | 0.22 | 9/15 |- The two largest differences, 0.22 and 0.21 in int8, are a code-review- verdict where the reference puts 0.955 on "request changes" and the- nine-question invoice record; both keep the reference's decision, and 8 of- the 15 requests stay under 0.01. A reference in f32 has not been run (the 27B in f32- does not fit the 61 GB of the box), so how much of the gap is the engine's- int8 and how much the reference's bf16 is not separated.+ The gap is the int8 trunk, not the rendering or the head: with the same+ rendering, the same head code and the container's f16 weights the largest+ difference falls from 0.22 to 0.012 (the nine-question invoice record), and+ the code-review verdict that moved by 0.22 in int8 moves by 0.0008. What+ is left at f16 is the reference computing in bf16 where the engine computes+ in f32. On the tiny fixture, where both sides run f32, f16 weights give+ max |dp| 2.5e-6 and int8 5.0e-2.## Speed@@ -112,23 +136,24 @@ Measured on the same box, 8 threads, every request from a cold state:| | per request ||---|---|-| engine, int8, median over the 15 requests (150 to 779 tokens) | 20.4 s |+| engine, f16, median over the 15 requests (150 to 779 tokens) | 47.4 s |+| engine, int8, the same requests | 20.4 s || engine, int4, the same requests | 30.2 s || reference, bf16, transformers 5.17 on the CPU, 28 of 64 layers read from disk | 10.8 s |-| `coli serve`, the request above (300 tokens), at the client | 20.6 s, of which 1.4 ms gateway |+| `coli serve`, int8, the request above (300 tokens), at the client | 20.6 s, of which 1.4 ms gateway |-The time is the backbone's prefill, about 15 tokens per second here; the-reference's bf16 matrix kernels are faster on this CPU than qwen36's int8-prefill, and int4 is slower still because the prefill is compute-bound. The-engine's own time is in the `x-colibri-engine-ms` header.+The time is the backbone's prefill; the reference's bf16 matrix kernels are+faster on this CPU than qwen36's int8 prefill, int4 is slower because the+prefill is compute-bound, and f16 multiplies in f32. The engine's own time is+in the `x-colibri-engine-ms` header.## Knobs| variable | default | meaning ||---|---|---|+| `COLI_DENSE_BITS` | f16 if the planner's budget holds it, else int8 (see above) | `16`, `8` or `4`; `COLI_DENSE_INT4` as for Qwen3.8-27B ([qwen36.md](qwen36.md#the-dense-27b)) || `COLI_CLEF_MAX_LEN` | 16384 | the reference's `max_length`: the state is cut to fit it, a schema longer than it is a 422 |-| `Q36_MAXT` | 8192 | the engine's context; a record longer than it is a 422 that names it, so raise it to 16384 for Clef's full budget |-| `COLI_DENSE_BITS`, `COLI_DENSE_INT4` | int8 | as for Qwen3.8-27B ([qwen36.md](qwen36.md#the-dense-27b)) |+| `Q36_MAXT` | 16384 for a Clef checkpoint (8192 for the others) | the engine's context. The KV rows are allocated as a record needs them, 2 GiB at 16384 on the 27B, and `coli plan` prices them at 16384. A lower `Q36_MAXT` refuses a longer record with a 422 that names it |## Limits