Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
tests(qwen36 tier), docs: test_qwen36_tier_replan; the residents-follow-the-prompt section
kreuzzelgb842448ae8c5
diff --git a/c/Makefile b/c/Makefileindex d1ac0f7f..2fddd84b 100644--- a/c/Makefile+++ b/c/Makefile@@ -2433,6 +2433,10 @@ tests/test_qwen36_tier_withdraw$(EXE): tests/test_qwen36_tier_withdraw.c qwen36_tests/test_qwen36_tier_layer_home$(EXE): tests/test_qwen36_tier_layer_home.c qwen36_tier.c$(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)+# qt_replan: the resident set follows the prompt's own routing counts (fake backend).+tests/test_qwen36_tier_replan$(EXE): tests/test_qwen36_tier_replan.c qwen36_tier.c+ $(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)+tests/test_qwen36_tier_int8_engine$(EXE): tests/test_qwen36_tier_int8_engine.c qwen36.c qwen36_tier.c $(VK_OBJ)$(CC) $(CFLAGS) -DCOLI_CUDA $< $(VK_OBJ) -o $@ $(LDFLAGS)diff --git a/c/qwen36_tier.c b/c/qwen36_tier.cindex e98c9616..bb7aca65 100644--- a/c/qwen36_tier.c+++ b/c/qwen36_tier.c@@ -1291,7 +1291,7 @@ int qt_replan(int layer,const uint32_t *counts,int max_swaps){int nc=0, nv=0;for(size_t i=lo;i<hi;i++){QSlot *s=&G.slot[i]; int e=(int)(i%G.ne);- if(home(e)!=di || s->queued) continue;+ if(home2((int)(i/G.ne),e)!=di || s->queued) continue;if(s->resident) vict[nv++]=(int)i;else if(s->g4 && counts[i-lo]>0) cand[nc++]=(int)i;}diff --git a/c/tests/test_qwen36_tier_replan.c b/c/tests/test_qwen36_tier_replan.cnew file mode 100644index 00000000..b56f1c4a--- /dev/null+++ b/c/tests/test_qwen36_tier_replan.c@@ -0,0 +1,145 @@+/* qt_replan: the resident set follows the prompt.+ *+ * The warmstart fills VRAM from a heat file, i.e. from what earlier prompts+ * routed to. A new prompt routes elsewhere, and the LFRU tick corrects that+ * one expert per sixteen tokens. qt_replan takes this prompt's own routing+ * counts (the engine's prefill counts) and swaps residents the prompt never+ * touched for its most-routed non-residents, budget-neutral, through the same+ * victim-first swap the tick uses, in strict count order and only while the+ * newcomer's count beats the victim's. Evicted experts are reported through+ * qt_evicted_take so the engine can rebuild their CPU copies before the miss+ * path needs them. Fake CUDA backend, no GPU, no toolkit. */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "../compat.h" /* setenv: MinGW has none */+#include "qwen36_fake_cuda.h"++#include "../qwen36_tier.c"++static int fails;+static void check(int ok, const char *what) { if (!ok) { printf(" FAIL: %s\n", what); fails++; } }++enum { NL = 2, NE = 8, D = 64, IH = 32, TOPK = 2 };++static int resident_set(int layer, int *out) { /* returns count, fills sorted eids */+ int n = 0;+ pthread_mutex_lock(&G.mx);+ for (int e = 0; e < NE; e++) if (qs(layer, e)->resident) out[n++] = e;+ pthread_mutex_unlock(&G.mx);+ return n;+}+static int same(const int *a, int na, const int *b, int nb) {+ if (na != nb) return 0;+ for (int i = 0; i < na; i++) if (a[i] != b[i]) return 0;+ return 1;+}++int main(void) {+ setenv("COLI_CUDA", "1", 1); setenv("COLI_GPUS", "0", 1);+ setenv("QT_NO_WARMSTART", "1", 1); setenv("HEAT_FILE", "", 1); setenv("COLI_PLACE", "off", 1);+ setenv("QT_UPLOAD_SYNC", "", 1);+ fake_ndev = 1; fake_uploads = 0; fake_overwrites = 0;++ /* budget: exactly eight experts, four per layer once noted in interleaved order */+ size_t exp_bytes = 3 * dev_alloc_footprint((size_t)D * IH / 2) + 3 * dev_alloc_footprint((2 * IH + D) / 3 * sizeof(float));+ char gb[64]; snprintf(gb, sizeof gb, "%.15f", (double)(8 * exp_bytes + exp_bytes / 2) / 1073741824.0);+ setenv("CUDA_EXPERT_GB", gb, 1);+ check(qt_init(NL, NE, D, IH, NE, TOPK, 0, 1), "tier starts (int4 mode, per-row scales)");++ static unsigned char g4[NL][NE][D * IH / 2], u4[NL][NE][D * IH / 2], d4[NL][NE][D * IH / 2];+ static float sc[NL][NE][2 * IH + D];+ for (int e = 0; e < NE; e++) for (int l = 0; l < NL; l++) {+ memset(g4[l][e], (unsigned char)(e + 1), sizeof g4[l][e]); memset(u4[l][e], (unsigned char)(e + 2), sizeof u4[l][e]);+ memset(d4[l][e], (unsigned char)(e + 3), sizeof d4[l][e]);+ for (int i = 0; i < 2 * IH + D; i++) sc[l][e][i] = 1.0f;+ /* experts 0..3 of both layers fit the budget and go up; 4..7 only leave+ * their RAM pointers with the tier, which is what a real warmstart does+ * for the experts it cannot place */+ qt_note_block(l, e, g4[l][e], u4[l][e], d4[l][e], sc[l][e], sc[l][e] + IH, sc[l][e] + 2 * IH);+ }+ qt_fill_wait();+ int res[NE]; int n = resident_set(0, res);+ { int want[] = {0, 1, 2, 3}; check(same(res, n, want, 4), "warmstart: layer 0 experts 0..3 resident, 4..7 not"); }+ n = resident_set(1, res);+ { int want[] = {0, 1, 2, 3}; check(same(res, n, want, 4), "warmstart: layer 1 experts 0..3 resident, 4..7 not"); }+ check(fake_uploads == 3 * 8, "eight experts uploaded (three tensors each)");+ size_t used0 = G.used[0];++ /* the prompt's counts: it never routed to 0 and 1, a little to 2 and 3,+ * mostly to 4 and 5, once to 6, never to 7 */+ uint32_t freq[NE] = {0, 0, 5, 7, 10, 9, 1, 0};++ /* layer 0, cap 1: only the best pair, 4 (10) for 0 (count 0, the coldest resident) */+ ColiCudaTensor *victim_tg; pthread_mutex_lock(&G.mx); victim_tg = qs(0, 0)->tg; pthread_mutex_unlock(&G.mx);+ int planned = qt_replan(0, freq, 1);+ check(planned == 1, "cap 1 plans exactly one swap");+ qt_fill_wait();+ pthread_mutex_lock(&G.mx);+ check(qs(0, 4)->tg == victim_tg && qs(0, 0)->tg == NULL, "the swap is in place: the newcomer took the victim's device buffers");+ pthread_mutex_unlock(&G.mx);+ check(fake_overwrites == 3 && fake_uploads == 3 * 8, "three overwrites, no new upload");+ n = resident_set(0, res);+ { int want[] = {1, 2, 3, 4}; check(same(res, n, want, 4), "after the first swap: 4 in, 0 out"); }+ n = resident_set(1, res);+ { int want[] = {0, 1, 2, 3}; check(same(res, n, want, 4), "a layer-0 re-plan leaves layer 1 alone"); }+ check(G.used[0] == used0, "a swap is budget-neutral");+ int ls[8], es[8];+ int nev = qt_evicted_take(ls, es, 8);+ check(nev == 1 && ls[0] == 0 && es[0] == 0, "the evicted expert is reported once, as (layer 0, expert 0)");+ check(qt_evicted_take(ls, es, 8) == 0, "and not a second time");++ /* no cap: 5 (9) for 1 (count 0); 6 (1) against the next victim 2 (5) is+ * not worth a swap, so the plan stops there */+ planned = qt_replan(0, freq, 100);+ check(planned == 1, "the second plan holds one pair: a newcomer must beat its victim's count");+ qt_fill_wait();+ n = resident_set(0, res);+ { int want[] = {2, 3, 4, 5}; check(same(res, n, want, 4), "after the second swap: 5 in, 1 out; 2 and 3 stay"); }+ check(fake_overwrites == 6 && fake_uploads == 3 * 8, "again in place: six overwrites so far, still no new upload");+ check(G.inplace == 2, "the tier counts both swaps as in-place");+ nev = qt_evicted_take(ls, es, 8);+ check(nev == 1 && es[0] == 1, "expert 1 reported as evicted");+ check(G.rp_n == G.rp_i, "nothing left pending: the queue was idle, the plan drained at once");++ /* same counts again: the set already matches the prompt */+ check(qt_replan(0, freq, 100) == 0, "a re-plan on the same counts plans nothing");+ check(qt_replan(0, NULL, 100) == 0 && qt_replan(0, freq, 0) == 0 && qt_replan(NL, freq, 100) == 0,+ "NULL counts, a zero cap or a layer out of range plan nothing");++ /* layer 1 from its own counts: 7 (10) takes the place of a never-routed+ * resident; 0 is resident and routed, so it stays */+ uint32_t freq1[NE] = {9, 0, 0, 0, 0, 0, 0, 10};+ fake_overwrite_fail = 1; /* a backend without the entry point: the swap must still land, by free + upload */+ check(qt_replan(1, freq1, 100) == 1, "layer 1: one swap, 7 for one of the count-0 residents");+ qt_fill_wait();+ fake_overwrite_fail = 0;+ check(fake_overwrites == 6 && fake_uploads == 3 * 9, "without overwrite support the swap falls back to a fresh upload");+ n = resident_set(1, res);+ check(n == 4 && res[0] == 0 && res[3] == 7, "layer 1 keeps 0 and now holds 7");+ n = resident_set(0, res);+ { int want[] = {2, 3, 4, 5}; check(same(res, n, want, 4), "layer 0 untouched by the layer-1 plan"); }+ nev = qt_evicted_take(ls, es, 8);+ check(nev == 1 && ls[0] == 1, "the layer-1 victim is reported with its layer");++ /* the whole-table form (layer < 0) plans across layers, per device: layer 0's+ * expert 6 (routed once) is worth more than layer 1's never-routed residents,+ * which the per-layer form could not trade against each other */+ uint32_t all[NL * NE]; memcpy(all, freq, sizeof freq); memcpy(all + NE, freq1, sizeof freq1);+ check(qt_replan(-1, all, 100) == 1, "the whole-table form plans one cross-layer swap");+ qt_fill_wait();+ check(resident_set(0, res) == 5 && resident_set(1, res) == 3, "layer 0 gained a resident, layer 1 lost one");+ check(G.used[0] == used0, "still budget-neutral");+ check(qt_replan(-1, all, 100) == 0, "and then nothing is left worth a swap");++ /* the decode marker: stats after the mark count from here */+ qt_stats_mark();+ check(G.mk_on && G.mk_hits == 0 && G.mk_miss == 0, "the marker snapshots the counters (none yet)");+ qt_stats();++ qt_shutdown();+ if (fails) { printf("test_qwen36_tier_replan: %d failure(s)\n", fails); return 1; }+ printf("OK test_qwen36_tier_replan: the resident set follows the prompt's counts, budget-neutral, evictions reported\n");+ return 0;+}diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex fbd9e5b3..98bc2b96 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -469,6 +469,8 @@ and the CPU/GPU execution split.| `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). || `Q36_OFFER_SHEXP` | `0` (off) | Offer the shared expert to the VRAM placer. Off by default: on the card it costs 6.3 ms/token (3070) to 11-12.7 ms (with a slower second card) against 3.7-4.0 on the CPU, where it hides behind the expert group. |+| `QT_PREFILL_REPLAN` | `0` (off) | CUDA expert tier: after each prefill layer's routing, swap VRAM residents this prompt never routed to for its most-routed non-residents of that layer, budget-neutral, uploads overlapping the rest of the prefill. Measured on the 35B: decode VRAM hit rate 60 -> 73 % against a heat file from other prompts, 38 -> 75 % from a cold start. See [qwen36-cuda-tier.md](qwen36-cuda-tier.md#the-residents-follow-the-prompt-qt_prefill_replan1). |+| `QT_PREFILL_REPLAN_MAX` | `24` | Cap on the swaps planned per prefill layer by `QT_PREFILL_REPLAN` (offline at B=96 the uncapped plan's hit rate with two thirds of the swaps). |## Qwen3.8 engine (`qwen38`)diff --git a/docs/qwen36-cuda-tier.md b/docs/qwen36-cuda-tier.mdindex 9b61abc2..6e47bf78 100644--- a/docs/qwen36-cuda-tier.md+++ b/docs/qwen36-cuda-tier.md@@ -303,6 +303,83 @@ cards would keep the MoE gain without that price. Cold, two cards win eitherway (45.3 against 52.3 ms), since more experts are resident at once. For therecord, Ollama 0.34.4 on the same pair shows the same shape: 38.1 tok/s on the3070 alone, 36.6-37.5 on both cards, 33.0 on the Quadro alone.+## The residents follow the prompt (`QT_PREFILL_REPLAN=1`)++The warmstart fills VRAM from the heat file, i.e. from what earlier prompts+routed to, and the LFRU tick then corrects one expert per sixteen tokens and+device. For a prompt on a new topic that is thousands of tokens of catching up:+measured on the 35B with a heat file accumulated over six other prompts, a+fresh prompt's decode hits VRAM 56-63 % of the time at 37 % residency, a cold+start 38 %, and a heat file from the *same* prompt 89-91 % -- the heat+warmstart is an oracle for a repeated prompt and a stranger's guess for a new+one.++The prefill knows better. Its routing is this prompt's routing: offline, a+static per-layer set of B experts chosen from the prompt's own prefill counts+covers its decode routing far better than the heat file at the same budget+(held-out prompts, four topics):++| B per layer (of 256) | heat from other prompts | own prefill counts | oracle (own decode) |+|---|---|---|---|+| 32 | 0.217 | **0.421** | 0.566 |+| 64 | 0.423 | **0.613** | 0.777 |+| 96 (~the 8 GB card's share) | 0.593 | **0.741** | 0.890 |+| 128 | 0.725 | **0.825** | 0.952 |++`QT_PREFILL_REPLAN=1` spends that: after each prefill layer's routing the+engine hands the tier the layer's counts over the prompt rows, and the tier+swaps residents the prompt never routed to for the prompt's most-routed+non-residents of that layer -- budget-neutral, through the same victim-first+swap the LFRU tick uses, in strict count order and only while the newcomer's+count beats the victim's. The swaps of layer L upload while layers L+1.. still+compute; whatever the upload queue does not take at once is drained on the+next layers and, a few per token, on the decode ticks (each swap is a+`cudaFree` + `cudaMalloc`, which synchronise the device under the async+groups, so the decode drains slowly on purpose). `QT_PREFILL_REPLAN_MAX`+caps the swaps per layer (default 256). Placement never changes routing:+the tokens are the ones the CPU path produces.++Two costs come with an eviction and are handled here rather than paid in the+miss path: the tier reports evicted experts (`qt_evicted_take`) and the engine+rebuilds their RAM int8 copies at the next step, in parallel, before the+layers run -- on the int4 container the warmstart had freed them, and left to+the miss path 2,000 victims cost ~7 ms/token over the following 300 tokens.+The `[qtier]` footer also reports the hit rate counted from the first decode+token (`decode VRAM hit rate`), which is the number that moves.++Measured on the 3070 alone (per-row int4 35B, 200-250-token prompts, 300+decoded tokens, four held-out prompts, heat file from six other prompts,+`QT_PREFILL_REPLAN_MAX=24` = 960 swaps per prompt, 12 cores `OMP_PLACES=cores`).+`off -> on`, decode-only figures from `COLI_TIMERS=1`:++| prompt | trunk | decode VRAM hit rate | MoE ms/token | total ms/token | TTFT |+|---|---|---|---|---|---|+| chat | CPU (`COLI_PLACE=off`) | 54.8 -> **72.8 %** | 18.8 -> 15.2 | 67.7 -> 68.5 | 3.9 -> 5.0 s |+| code | CPU | 59.9 -> **75.1 %** | 18.0 -> 14.5 | 69.5 -> 66.8 | 5.1 -> 5.4 s |+| Chinese | CPU | 62.7 -> **74.8 %** | 16.8 -> 14.6 | 68.8 -> 65.8 | 4.0 -> 5.0 s |+| reasoning | CPU | 63.1 -> **75.3 %** | 17.4 -> 15.9 | 70.4 -> 71.6 | 4.4 -> 5.5 s |+| chat | VRAM (all five components) | 41.8 -> **61.7 %** | 22.9 -> 18.7 | 49.2 -> **45.2** | 6.4 -> 6.6 s |+| code | VRAM | 45.1 -> **64.8 %** | 22.3 -> 17.5 | 49.0 -> **44.1** | 8.1 -> 8.2 s |+| Chinese | VRAM | 49.6 -> **60.3 %** | 20.4 -> 20.4 | 46.3 -> 47.8 | 6.2 -> 7.0 s |+| reasoning | VRAM | 44.5 -> **66.7 %** | 22.4 -> 17.6 | 48.7 -> **44.4** | 7.0 -> 7.5 s |++The hit rate moves as the offline table predicted (+12 to +22 points), the+MoE phase loses 2 to 5 ms/token, and with the trunk in VRAM that is 8-10 % of+the token on three prompts of four (the fourth is inside the run-to-run noise+of about ±2 ms). With the trunk on the CPU the same MoE saving disappears in+the 50 ms the dense trunk costs there. The price is at the front: the swaps+upload during the prefill, and each one is six synchronous host-to-device+copies (three matrices, three scale vectors), about 1 ms on this box, so 960+swaps add 0.1-1.1 s to the TTFT of a 200-token prompt; the decode saving pays+that back after 100-250 tokens. Fewer swaps buy most of the gain -- offline at+B = 96, a cap of 12 per layer (480 swaps) reaches 0.709 of the 0.741 the+uncapped plan reaches, 24 per layer reaches 0.741 -- which is why the default+cap is 24. The follow-up that would take the TTFT price away is a pinned,+asynchronous staging path (or one contiguous device block per expert) so the+copies stop serialising with the prefill's expert groups; the swap itself+already writes into the victim's buffers (`coli_cuda_tensor_overwrite`, no+`cudaFree`/`cudaMalloc`; a backend without the entry point falls back to+free-then-upload).## Measured (Threadripper 3945WX 12C, RTX 3070 8 GB + Quadro RTX 4000 8 GB, Qwen3.6-35B-A3B int4, 200-token decode)