Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
qwen38: trunk offload measured, CPU int8 reference, trunk on the fake tier, planner prices the trunk
kreuzzelg1b4d19a62cea
diff --git a/c/family_registry.py b/c/family_registry.pyindex 8343af0c..db35f2e6 100644--- a/c/family_registry.py+++ b/c/family_registry.py@@ -89,6 +89,11 @@ class FamilyDescriptor:# separate from expert_inventory prevents a fixed allocation from# being multiplied by the cache capacity.fixed_resident_inventory: object = None+ # Bytes of a dense tensor that the engine's GPU trunk offload would hold+ # in VRAM (int8 per row, quantized at load time), so the planner can take+ # the trunk out of the VRAM budget before it counts hot experts. None: the+ # engine keeps its trunk on the CPU (or has none).+ trunk_inventory: object = None# Lo script sotto tools/ che `coli convert` puo' guidare per questa famiglia,# e le opzioni di `coli convert` che quello script accetta davvero.#@@ -965,6 +970,28 @@ _QWEN38_NATIVE_MATRIX_SUFFIXES = ()+def _qwen38_trunk_inventory(name, size, _config, dtype=None):+ """int8 bytes the qwen38 engine's stage-1 trunk offload holds in VRAM for+ this tensor (docs/qwen38.md, "GPU"): the dense matmul matrices of the text+ model, quantized per row when the tier starts. Matrices under 1 MiB stay+ on the CPU (a round trip costs more than a tiny GEMV saves), and so do+ the PLE projections, the vision tower and everything that is not a matmul+ weight. embed_tokens stands in for the tied lm_head."""+ if name.startswith("mtp.") or name.startswith("model.visual.") or ".ple." in name:+ return 0+ text_tensor = (name == "lm_head.weight" or+ name.startswith("model.language_model.") or+ name.startswith("model."))+ if not text_tensor or not name.endswith(_QWEN38_NATIVE_MATRIX_SUFFIXES):+ return 0+ dtype = "BF16" if dtype is None else dtype+ element_bytes = {"BF16": 2, "F16": 2, "F32": 4}.get(dtype)+ if not element_bytes:+ return 0+ elements = size // element_bytes+ return elements if elements >= (1 << 20) else 0++def _qwen38_resident_inventory(name, size, _config, dtype=None):"""Resident bytes for tensors the native text engine actually loads.@@ -1269,9 +1296,10 @@ FAMILIES = ("<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n""<|im_start|>assistant\n<think>\n"),# CUDA VRAM expert tier (qwen36_tier.c, fp8 streaming mode): hot- # routed experts get VRAM copies above the RAM LRU; the dense trunk- # stays on the CPU for now (docs/qwen38.md, "GPU").+ # routed experts get VRAM copies above the RAM LRU, and the dense+ # trunk goes first, as int8 residents (docs/qwen38.md, "GPU").supports_accelerator=True,+ trunk_inventory=_qwen38_trunk_inventory,),FamilyDescriptor(id="deepseek_v4",@@ -1490,6 +1518,20 @@ def resident_contribution(resolved, name, size, dtype=None):return contribution+def trunk_contribution(resolved, name, size, dtype=None):+ """VRAM bytes of the engine's dense-trunk offload for one tensor (0 for+ families whose trunk stays on the CPU)."""+ if isinstance(size, bool) or not isinstance(size, int) or size < 0:+ raise ValueError("tensor size must be a non-negative integer")+ inventory = resolved.descriptor.trunk_inventory+ if inventory is None:+ return 0+ contribution = inventory(name, size, resolved.family_config, dtype)+ if isinstance(contribution, bool) or not isinstance(contribution, int) or contribution < 0:+ raise RegistryError(f"invalid trunk inventory for {resolved.descriptor.id}")+ return contribution++def fixed_resident_contribution(resolved, name, size, dtype=None):"""Return resident bytes that do not belong to dense or cache storage.diff --git a/c/qwen38.c b/c/qwen38.cindex fe9e5e37..ce48b6a0 100644--- a/c/qwen38.c+++ b/c/qwen38.c@@ -1771,6 +1771,7 @@ int main(int argc, char **argv) {Model m; model_init(&m, snap, cap, bits);q38_tier_start(&m, cap); /* COLI_CUDA=1: hot experts stream to VRAM (qwen36_tier.c) */+ q38_trunk_cpu_int8(&m); /* Q38_TRUNK_CPU_INT8=1: the trunk's int8 rows on the CPU (reference) */if(is_ref)ref_logits=read_reference_logits(ref_root,m.c.vocab);g_capture_last_logit=ref_logits!=NULL||getenv("DUMP")!=NULL;q38_telemetry_init(snap, &m);diff --git a/c/qwen38_core.h b/c/qwen38_core.hindex 9fca5b8b..f2e5b38b 100644--- a/c/qwen38_core.h+++ b/c/qwen38_core.h@@ -50,6 +50,7 @@ typedef struct {Q38WeightKind kind;unsigned owns_data:1, owns_scales:1;int gpu; /* 0 = CPU; else 1 + tier handle of an int8 copy resident in VRAM (decode, S == 1) */+ int8_t *q8; float *q8sc; /* Q38_TRUNK_CPU_INT8=1: the same int8 rows kept on the CPU (reference for the GPU path, no GPU needed) */} Q38Weight;typedef struct { float *norm; Q38Weight down, up, inject; } GatedResidual;@@ -207,6 +208,7 @@ static void q38_weight_free(Q38Weight *weight) {if(!weight)return;if(weight->owns_data)free(weight->data);if(weight->owns_scales)free(weight->scales);+ free(weight->q8); free(weight->q8sc);memset(weight,0,sizeof(*weight));}@@ -269,6 +271,18 @@ static void q38_weight_matmul(float *y,const float *x,const Q38Weight *weight,* so the BF16 copy stays the reference for everything but S == 1. */if(S==1&&weight&&weight->gpu&&weight->rows==O&&weight->cols==I&&qt_dense_matmul(weight->gpu-1,y,x,I,O))return;+ if(S==1&&weight&&weight->q8&&weight->rows==O&&weight->cols==I){+ /* the int8 rows the GPU would hold, computed here: what the trunk+ * quantization alone does to the output, GPU or not */+ const int8_t *q=weight->q8; const float *sc=weight->q8sc;+ #pragma omp parallel for schedule(static)+ for(int o=0;o<O;o++){+ const int8_t *w=q+(size_t)o*I; float a=0.f;+ for(int i=0;i<I;i++)a+=x[i]*(float)w[i];+ y[o]=a*sc[o];+ }+ return;+ }if(!weight||weight->rows!=O||weight->cols!=I||!weight->data){fprintf(stderr,"invalid matmul weight: have [%d,%d] kind=%d, need [%d,%d]\n",weight?weight->rows:0,weight?weight->cols:0,@@ -1713,7 +1727,17 @@ static Q38TrunkItem *g_trunk; static int g_trunk_n, g_trunk_cap;static void q38_trunk_add(Q38Weight *w,const char *name,int layer) {if(!w||!w->data||(w->kind!=Q38_WEIGHT_BF16&&w->kind!=Q38_WEIGHT_F32))return;size_t bytes=(size_t)w->rows*w->cols+(size_t)w->rows*sizeof(float);- if(bytes<(1u<<20))return; /* a round trip costs more than a tiny GEMV saves */+ /* Q38_TRUNK_MIN_KB (default 1024): a round trip costs more than a tiny+ * GEMV saves; Q38_TRUNK_SKIP=name,name: leave those components on the+ * CPU (bisecting a numeric difference, or a component that does not pay) */+ static long min_kb=-1; static const char *skip;+ if(min_kb<0){ const char *e=getenv("Q38_TRUNK_MIN_KB"); min_kb=e?atol(e):1024; skip=getenv("Q38_TRUNK_SKIP"); }+ if(bytes<(size_t)min_kb*1024)return;+ if(skip&&*skip){+ size_t n=strlen(name); const char *s=skip;+ while(*s){ const char *c=strchr(s,','); size_t l=c?(size_t)(c-s):strlen(s);+ if(l==n&&!strncmp(s,name,n))return; if(!c)break; s=c+1; }+ }if(g_trunk_n==g_trunk_cap){g_trunk_cap=g_trunk_cap?2*g_trunk_cap:256;g_trunk=(Q38TrunkItem*)realloc(g_trunk,(size_t)g_trunk_cap*sizeof(*g_trunk));@@ -1750,6 +1774,38 @@ static void q38_trunk_offer_all(Model *m) {q38_trunk_add(&L->router,"router",l);}}+/* int8 per row, scale = max|w| / 127 (the qwen36 dnproj/lmhead format) */+static void q38_trunk_quantize(const Q38Weight *w,int8_t **qp,float **scp) {+ int O=w->rows,I=w->cols;+ int8_t *q=(int8_t*)malloc((size_t)O*I); float *sc=(float*)malloc((size_t)O*sizeof(float));+ if(!q||!sc){fprintf(stderr,"OOM trunk quantization\n");exit(1);}+ #pragma omp parallel for schedule(static)+ for(int r=0;r<O;r++){+ float row[8192]; float *src=row; float *heap=NULL;+ if(I>8192){heap=(float*)malloc((size_t)I*sizeof(float)); src=heap;}+ q38_weight_row(w,r,src);+ float mx=0.f; for(int k=0;k<I;k++){float a=fabsf(src[k]); if(a>mx)mx=a;}+ float s=mx>0.f?mx/127.f:1.f, inv=1.f/s; sc[r]=s;+ int8_t *dst=q+(size_t)r*I;+ for(int k=0;k<I;k++){int v=(int)lrintf(src[k]*inv); if(v>127)v=127; if(v<-127)v=-127; dst[k]=(int8_t)v;}+ free(heap);+ }+ *qp=q; *scp=sc;+}+/* Q38_TRUNK_CPU_INT8=1: keep the int8 rows on the CPU instead (or as well),+ * so the quantization can be judged without a GPU (PPL, token parity) */+static void q38_trunk_cpu_int8(Model *m) {+ const char *e=getenv("Q38_TRUNK_CPU_INT8");+ if(!e||e[0]!='1'||e[1])return;+ if(!g_trunk_n) q38_trunk_offer_all(m);+ double t0=now_s(); size_t bytes=0;+ for(int i=0;i<g_trunk_n;i++){+ Q38Weight *w=g_trunk[i].w; if(w->q8)continue;+ q38_trunk_quantize(w,&w->q8,&w->q8sc); bytes+=(size_t)w->rows*w->cols;+ }+ fprintf(stderr,"[qwen38] trunk: %d matrices int8 on the CPU (%.2f GiB) in %.1fs (Q38_TRUNK_CPU_INT8)\n",+ g_trunk_n,bytes/1073741824.0,now_s()-t0);+}/* after qt_init: quantize and upload what the placer accepted */static void q38_trunk_place_all(Model *m) {(void)m;@@ -1759,20 +1815,18 @@ static void q38_trunk_place_all(Model *m) {int dev=qt_place_of(it->name,it->layer);if(dev==QT_PLACE_CPU)continue;int O=w->rows,I=w->cols;- int8_t *q=(int8_t*)malloc((size_t)O*I); float *sc=(float*)malloc((size_t)O*sizeof(float));- if(!q||!sc){fprintf(stderr,"OOM trunk quantization\n");exit(1);}- #pragma omp parallel for schedule(static)- for(int r=0;r<O;r++){- float row[8192]; float *src=row; float *heap=NULL;- if(I>8192){heap=(float*)malloc((size_t)I*sizeof(float)); src=heap;}- q38_weight_row(w,r,src);- float mx=0.f; for(int k=0;k<I;k++){float a=fabsf(src[k]); if(a>mx)mx=a;}- float s=mx>0.f?mx/127.f:1.f, inv=1.f/s; sc[r]=s;- int8_t *dst=q+(size_t)r*I;- for(int k=0;k<I;k++){int v=(int)lrintf(src[k]*inv); if(v>127)v=127; if(v<-127)v=-127; dst[k]=(int8_t)v;}- free(heap);- }+ int8_t *q; float *sc; q38_trunk_quantize(w,&q,&sc);int h=qt_dense_init(q,sc,I,O,dev);+ if(h>=0&&getenv("Q38_TRUNK_SELFTEST")){+ /* DIAG: GPU int8 GEMV against the same int8 matrix on the CPU */+ float *x=(float*)malloc((size_t)I*sizeof(float)),*yg=(float*)malloc((size_t)O*sizeof(float)),*yc=(float*)malloc((size_t)O*sizeof(float));+ for(int k=0;k<I;k++)x[k]=sinf(0.37f*k)+0.1f*(k%7);+ for(int r=0;r<O;r++){double a=0; for(int k=0;k<I;k++)a+=(double)q[(size_t)r*I+k]*x[k]; yc[r]=(float)(a*sc[r]);}+ int ok=qt_dense_matmul(h,yg,x,I,O); double num=0,den=0; int worst=0;+ for(int r=0;r<O;r++){double d=yg[r]-yc[r]; num+=d*d; den+=(double)yc[r]*yc[r]; if(fabs(d)>fabs(yg[worst]-yc[worst]))worst=r;}+ fprintf(stderr,"[selftest] %-7s L%-2d [O=%d I=%d] ok=%d rel.err %.2e worst row %d gpu %.5g cpu %.5g\n",it->name,it->layer,O,I,ok,den>0?sqrt(num/den):-1.0,worst,yg[worst],yc[worst]);+ free(x);free(yg);free(yc);+ }free(q); free(sc);if(h>=0){ w->gpu=h+1; placed++; placed_bytes+=(size_t)O*I; }}diff --git a/c/resource_plan.py b/c/resource_plan.pyindex 7a2fe3b0..30d265cf 100644--- a/c/resource_plan.py+++ b/c/resource_plan.py@@ -14,6 +14,7 @@ from pathlib import Pathfrom family_registry import (expert_contributions, planner_geometry,fixed_resident_contribution, resident_contribution,+ trunk_contribution,resolve_model)@@ -26,7 +27,7 @@ EXPERT_RE = re.compile(r"(?:model\.)?layers\.(\d+)\.(?:mlp|ffn)\.experts\.(\d+)\# sidecar and self-invalidate on any change. Best-effort: any read/write failure falls# straight back to a full recompute (see analyze_model). Sits alongside .coli_usage/.coli_ssd._ANALYSIS_CACHE_NAME = ".coli_analysis.json"-_ANALYSIS_CACHE_VERSION = 7+_ANALYSIS_CACHE_VERSION = 8def _dense_in_ram(descriptor, on_disk_bytes):@@ -120,6 +121,9 @@ def analyze_model(model):# number of per-layer cache slots. Qwen3.8's native FP8 path uses this for# its normalized scale bank; fallback accounting remains conservative.expert_fixed_bytes = 0+ # What the engine's GPU trunk offload would put in VRAM (int8), for the+ # families that have one; taken out of the VRAM budget before experts.+ trunk_int8_bytes = 0expert_groups = {}tensor_names = set()for shard in shards:@@ -150,6 +154,8 @@ def analyze_model(model):else:dense_bytes += resident_contribution(resolved, name, size, dtype)+ trunk_int8_bytes += trunk_contribution(+ resolved, name, size, dtype)layer_sizes = {}for (layer, _), size in expert_groups.items():@@ -192,6 +198,7 @@ def analyze_model(model):"dense_bytes": _dense_in_ram(resolved.descriptor, dense_bytes),"dense_disk_bytes": dense_bytes,"expert_fixed_bytes": expert_fixed_bytes,+ "trunk_int8_bytes": trunk_int8_bytes,"expert_bytes": sum(expert_groups.values()),"expert_count": len(expert_groups),"expert_layers": len(per_layer),@@ -993,6 +1000,16 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,safe_vram += usablegpu_plan.append(dict(gpu, reserve_bytes=reserve, usable_bytes=usable))requested_vram = int(vram_gb * GB) if vram_gb > 0 else safe_vram+ # The engine's placer (qwen36_tier.c, COLI_PLACE=auto) takes the dense+ # trunk first -- it is read every token -- on the first planned device,+ # if it fits that device's allowance; the experts get what is left.+ trunk_bytes = int(info.get("trunk_int8_bytes", 0) or 0)+ trunk_placed = 0+ if trunk_bytes and gpu_plan and gpu_plan[0]["usable_bytes"] >= trunk_bytes \+ and requested_vram >= trunk_bytes:+ trunk_placed = trunk_bytes+ requested_vram = max(0, requested_vram - trunk_placed)+ safe_vram = max(0, safe_vram - trunk_placed)requested_vram_before_clamp = requested_vramunified_pool = max(0, available_memory - info["dense_bytes"] - runtime_bytes)if placement_unified:@@ -1112,6 +1129,7 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,"warm_expert_bytes": warm_bytes, "cache_slots_per_layer": cap},"vram": {"role": "hot-experts", "devices": gpu_plan,"budget_bytes": vram_budget, "hot_expert_bytes": hot_bytes,+ "trunk_bytes": trunk_placed,"expert_capacity": vram_experts, "requires_host_backing": False},},"expected_bottleneck": bottleneck,@@ -1121,7 +1139,9 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,"next_actions": actions,# Un motore solo-CPU non ha un tier VRAM: annunciarlo comunque fa# scrivere al piano una riga che nessuno puo' eseguire.- "decisions": ([{"target": "VRAM", "reason": "profile-ranked hot experts"}]+ "decisions": ([{"target": "VRAM", "reason": "dense trunk as int8 residents"}]+ if trunk_placed else []) ++ ([{"target": "VRAM", "reason": "profile-ranked hot experts"}]if resolved.descriptor.supports_accelerator else []) + [{"target": "RAM", "reason": "warm experts execute on CPU without quality loss"},{"target": "Disk", "reason": "immutable recovery source for cold experts"},@@ -1223,7 +1243,9 @@ def format_plan(plan):f"{gpu['index']}:{gpu['name']}"+ ("" if plans_placement(gpu) else " (identity only)")for gpu in vram["devices"])- lines.append(f"VRAM {format_bytes(vram['budget_bytes'])} hot tier · "+ trunk = vram.get("trunk_bytes", 0)+ lines.append("VRAM " + (f"{format_bytes(trunk)} int8 trunk + " if trunk else "") ++ f"{format_bytes(vram['budget_bytes'])} hot tier · "f"~{vram['expert_capacity']} experts · {names}")else:# Backend-neutral, matching the accelerator wording #903 settled on:diff --git a/c/tests/qwen36_fake_cuda.h b/c/tests/qwen36_fake_cuda.hindex 6a9d3023..46d8f7a3 100644--- a/c/tests/qwen36_fake_cuda.h+++ b/c/tests/qwen36_fake_cuda.h@@ -28,7 +28,7 @@#include "../backend_cuda.h"-struct ColiCudaTensor { int fmt, I, O, device, gs; const void *w; };+struct ColiCudaTensor { int fmt, I, O, device, gs; const void *w; const float *sc; };static int fake_uploads;static int last_fmt = -1;@@ -41,11 +41,21 @@ static size_t fake_free_bytes = 2ull << 30; /* what coli_cuda_mem_info reportstatic int (*fake_issue_hook)(int device, int count, const float *x) = NULL;static void (*fake_upload_hook)(int fmt) = NULL;-static int upload_common(ColiCudaTensor **t, const void *w, int fmt,+/* fake_dense_compute=1: coli_cuda_matmul really computes fmt 1 (int8 per+ * row) from the uploaded bytes, so an engine test can put a trunk on the fake+ * tier and demand the same tokens as the CPU int8 reference. The engine+ * frees its int8 rows right after qt_dense_init, so the upload keeps a copy. */+static int fake_dense_compute;+static int upload_common(ColiCudaTensor **t, const void *w, const float *sc, int fmt,int I, int O, int device, int gs) {if (fake_upload_hook) fake_upload_hook(fmt);ColiCudaTensor *n = (ColiCudaTensor *)calloc(1, sizeof *n);- n->fmt = fmt; n->I = I; n->O = O; n->device = device; n->gs = gs; n->w = w;+ n->fmt = fmt; n->I = I; n->O = O; n->device = device; n->gs = gs; n->w = w; n->sc = sc;+ if (fake_dense_compute && fmt == 1 && w && sc) {+ int8_t *q = (int8_t *)malloc((size_t)I * O); float *s = (float *)malloc((size_t)O * sizeof(float));+ if (q && s) { memcpy(q, w, (size_t)I * O); memcpy(s, sc, (size_t)O * sizeof(float)); n->w = q; n->sc = s; }+ else { free(q); free(s); n->w = NULL; n->sc = NULL; }+ }*t = n;fake_uploads++;last_fmt = fmt;@@ -58,13 +68,16 @@ static int upload_common(ColiCudaTensor **t, const void *w, int fmt,}int coli_cuda_tensor_upload(ColiCudaTensor **t, const void *w, const float *s,int fmt, int I, int O, int device) {- (void)s; return upload_common(t, w, fmt, I, O, device, 0);+ return upload_common(t, w, s, fmt, I, O, device, 0);}int coli_cuda_tensor_upload_g(ColiCudaTensor **t, const void *w, const float *s,int fmt, int I, int O, int device, int gs) {- (void)s; return upload_common(t, w, fmt, I, O, device, gs);+ return upload_common(t, w, s, fmt, I, O, device, gs);+}+void coli_cuda_tensor_free(ColiCudaTensor *t) {+ if (t && fake_dense_compute && t->fmt == 1) { free((void *)t->w); free((void *)t->sc); }+ free(t);}-void coli_cuda_tensor_free(ColiCudaTensor *t) { free(t); }int coli_cuda_available_device_count(void) { return fake_ndev; }int coli_cuda_device_count(void) { return fake_ndev; }int coli_cuda_init(const int *d, int n) { (void)d; (void)n; return 1; }@@ -99,7 +112,17 @@ void coli_cuda_stats(int device, size_t *count, size_t *bytes) {* unused on purpose (CFLAGS carry -Wno-unused-parameter). */static int fake_matmuls;int coli_cuda_matmul(ColiCudaTensor **tensor, float *y, const float *x, const void *weights, const float *scales, int fmt, int S, int I, int O, int device, int gs) {- fake_matmuls++; return 1;+ fake_matmuls++;+ ColiCudaTensor *t = tensor ? *tensor : NULL;+ if (fake_dense_compute && t && t->fmt == 1 && t->w && t->sc && t->I == I && t->O == O) {+ const int8_t *q = (const int8_t *)t->w;+ for (int s = 0; s < S; s++) for (int o = 0; o < O; o++) {+ const int8_t *w = q + (size_t)o * I; const float *xs = x + (size_t)s * I; float a = 0.f;+ for (int i = 0; i < I; i++) a += xs[i] * (float)w[i];+ y[(size_t)s * O + o] = a * t->sc[o];+ }+ }+ return 1;}#endif /* QWEN36_FAKE_CUDA_H */diff --git a/c/tests/test_qwen38_tier_engine.c b/c/tests/test_qwen38_tier_engine.cindex 5455c198..c439df1e 100644--- a/c/tests/test_qwen38_tier_engine.c+++ b/c/tests/test_qwen38_tier_engine.c@@ -94,6 +94,25 @@ int main(void) {qt_shutdown();tk(!G_fp8_stream && !G.on, "shutdown leaves the mode");+ /* Second pass: the dense trunk on the fake tier. Every dense matrix of the+ * fixture is offered (Q38_TRUNK_MIN_KB=0), quantized to int8 per row and+ * "uploaded"; the fake backend now computes fmt 1 from the uploaded bytes,+ * so the run must reproduce the oracle within its limits like the CPU int8+ * reference (Q38_TRUNK_CPU_INT8=1) does, and every offered matrix must have+ * been placed and released again at shutdown. */+ printf(" trunk on the fake tier\n");+ setenv("Q38_TRUNK_GPU", "1", 1);+ setenv("Q38_TRUNK_MIN_KB", "0", 1);+ setenv("COLI_PLACE", "auto", 1); /* the placer decides per offer */+ setenv("CUDA_EXPERT_GB", "0.5", 1); /* room for the trunk and every expert */+ fake_dense_compute = 1; fake_uploads = 0;+ rc = qwen38_main_unused(4, argv);+ tk(rc == 0, "engine with the int8 trunk on the fake tier stays within the oracle's limits");+ tk(g_trunk_n > 0 && qt_dense_count() == g_trunk_n, "every offered dense matrix was placed and uploaded");+ tk(fake_uploads >= g_trunk_n, "one upload per placed matrix");+ qt_shutdown();+ tk(qt_dense_count() == 0, "dense handles released at shutdown");+if (t_fails) { printf("test_qwen38_tier_engine: %d failure(s)\n", t_fails); return 1; }printf("test_qwen38_tier_engine: ok\n");return 0;diff --git a/c/tests/test_resource_plan.py b/c/tests/test_resource_plan.pyindex 255fcb35..40e587ea 100644--- a/c/tests/test_resource_plan.py+++ b/c/tests/test_resource_plan.py@@ -712,7 +712,15 @@ memInfo.free: 23.50 GB (97%)},}(self.model / "config.json").write_text(json.dumps(config))- tensors = [("model.embed_tokens.weight", 256, "BF16")]+ MiB = 1 << 20+ tensors = [("model.embed_tokens.weight", 256, "BF16"),+ # dense matmul matrices the engine offers to the tier: one+ # big enough to go (4 MiB BF16 -> 2 MiB int8), one under the+ # 1 MiB line that stays on the CPU, one PLE projection that+ # is never offered+ ("model.layers.0.linear_attn.in_proj_qkv.weight", 4 * MiB, "BF16"),+ ("model.layers.0.mlp.gate.weight", 1024, "BF16"),+ ("model.layers.1.ple.key_proj.weight", 4 * MiB, "BF16")]for projection in ("gate_proj", "up_proj", "down_proj"):prefix = f"model.layers.0.mlp.experts.0.{projection}"tensors.append((prefix + ".weight", 32, "F8_E4M3"))@@ -722,7 +730,9 @@ memInfo.free: 23.50 GB (97%)))write_shard(self.model / "model.safetensors", tensors)analysis = analyze_model(self.model)- self.assertEqual(analysis["dense_bytes"], 256)+ self.assertEqual(analysis["dense_bytes"], 256 + 4 * MiB + 1024 + 4 * MiB)+ # The stage-1 trunk offload: int8 bytes of the offered matrices only.+ self.assertEqual(analysis["trunk_int8_bytes"], 2 * MiB)# The three native FP8 sidecars are retained once in the normalized# scale bank, not once per cache slot.self.assertEqual(analysis["expert_fixed_bytes"], 12)@@ -742,6 +752,11 @@ memInfo.free: 23.50 GB (97%)self.assertEqual([device["index"] for device in plan["tiers"]["vram"]["devices"]], [0])self.assertGreater(plan["tiers"]["vram"]["budget_bytes"], 0)self.assertTrue(any(item["target"] == "VRAM" for item in plan["decisions"]))+ # The trunk goes first, out of the same VRAM, and the plan says so.+ self.assertEqual(plan["tiers"]["vram"]["trunk_bytes"], 2 * MiB)+ self.assertTrue(any(item["reason"] == "dense trunk as int8 residents"+ for item in plan["decisions"]))+ self.assertIn("int8 trunk", format_plan(plan))cap = plan["tiers"]["ram"]["cache_slots_per_layer"]self.assertGreaterEqual(cap, 1)environment = environment_for_plan(plan)@@ -760,7 +775,12 @@ memInfo.free: 23.50 GB (97%)self.assertEqual([device["index"] for device in selected["tiers"]["vram"]["devices"]], [0])capped = build_plan(self.model, context=64, vram_gb=4, available_memory=16 * GB,available_disk=16 * GB, gpus=[gpu])- self.assertLessEqual(capped["tiers"]["vram"]["budget_bytes"], 4 * GB)+ self.assertLessEqual(capped["tiers"]["vram"]["budget_bytes"], 4 * GB - 2 * MiB)+ self.assertEqual(capped["tiers"]["vram"]["trunk_bytes"], 2 * MiB)+ # A budget too small for the trunk leaves it on the CPU: experts only.+ tiny = build_plan(self.model, context=64, vram_gb=0.001, available_memory=16 * GB,+ available_disk=16 * GB, gpus=[gpu])+ self.assertEqual(tiny["tiers"]["vram"]["trunk_bytes"], 0)def test_cli_emits_versioned_json(self):cli = Path(__file__).parents[1] / "coli"diff --git a/docs/qwen36-cuda-tier.md b/docs/qwen36-cuda-tier.mdindex 281da378..57e6a195 100644--- a/docs/qwen36-cuda-tier.md+++ b/docs/qwen36-cuda-tier.md@@ -124,6 +124,23 @@ have it written for it.Peak RSS is ~2 GB higher under `auto`: the host-side int8 copies stay as theCPU fallback. Known, not yet addressed.+**Any dense matrix, by name.** The offer table is not limited to `lmhead` and+`dnproj`: an engine offers whatever it wants placed with `qt_trunk_offer(name,+layer, bytes)` before `qt_init`, asks `qt_place_of(name, layer)` afterwards,+and hands the placed matrices over as int8 rows with+`qt_dense_init(q, scales, I, O, device)`, which returns a handle;+`qt_dense_matmul(handle, y, x, I, O)` answers one GEMV from VRAM and returns 0+(CPU from here on) if the backend fails. The qwen36 calls remain thin+wrappers over the same mechanism. Qwen3.8 uses it for its whole trunk -- 553+matrices, 4.0 GiB int8 on one card ([qwen38.md](qwen38.md), "GPU") -- and+that is also where the backend's resident dense matvec got its own staging+buffers: `coli_cuda_matmul` used to share the `x`/`y` device buffers with the+expert group, which runs asynchronously on its own stream between `qt_issue`+and `qt_take`. A dense GEMV issued in that window (Qwen3.8's shared expert)+overwrote the group's input and output mid-flight -- no CUDA error, only+wrong numbers. qwen36 never called the dense path inside that window, so its+outputs were unaffected.+## Measured (Threadripper 3945WX 12C, RTX 3070 8 GB + Quadro RTX 4000 8 GB, Qwen3.6-35B-A3B int4, 200-token decode)| | 1 GPU (8 GB) | 2 GPUs (16 GB) |diff --git a/docs/qwen38.md b/docs/qwen38.mdindex 3305de68..03451b00 100644--- a/docs/qwen38.md+++ b/docs/qwen38.md@@ -167,8 +167,9 @@ conversion); the rest run on the CPU as before. Every expert the CPUcomputes is reported to the tier, which copies the 4.7 MiB slab and thethree scale tables during that call -- the RAM slot may be recycled by thenext token -- and promotes it when it has room or when it is hotter than-the coldest resident expert on its device (budget-neutral swap). The dense-trunk, prefill, QSA and the PLE table stay on the CPU.+the coldest resident expert on its device (budget-neutral swap). Prefill,+the DeltaNet recurrence, QSA and the PLE table stay on the CPU; the dense+trunk goes to the GPU as well, see below.```bashmake -C c qwen38 CUDA=1 CUDA_ARCH=native # NVCC=/usr/bin/nvcc on distro CUDA@@ -230,6 +231,82 @@ real checkpoint, and the honest summary is: on a machine of this class theexpert tier is not where Qwen3.8's decode time is. The dense trunk (a third ofthe token) and the expert reads (another third, a RAM-cap question) are.+### The dense trunk in VRAM (stage 1)++The trunk is the largest fixed cost of a decode token and it is+bandwidth-bound: 8 GiB of BF16 matmul weights read on every token at the+memory bus's pace. With the tier on, the engine offers every dense matmul+matrix of at least 1 MiB to the tier's placer by name and layer (the+DeltaNet projections `dnqkv`/`dnz`/`dnout`, attention `attnq`/`attnk`/+`attnv`/`attno`/`qsaidx`, the hyper-connection mixers `hcad`/`hcau`/`hcmd`/+`hcmu`, the shared expert `shg`/`shu`/`shd`, the `router`, and `lmhead`);+whatever the placer accepts is quantized to **int8 per row** (scale = max|w|+/ 127, the qwen36 dnproj/lmhead format) when the tier starts -- about 2 s+for the 553 matrices, 3.96 GiB on one card -- and answers decode GEMVs from+there, one round trip per matmul (`x` up, `y` down; activations stay on the+CPU). Prefill rows (S > 1) and any backend failure take the BF16 CPU path,+which stays in RAM. The placer takes the trunk before the experts (it is+read on every token), so on an 8 GB card about 2 GB remain for hot experts;+`coli plan` prices it the same way (`4.0 GB int8 trunk + ... hot tier`).++| variable | effect |+|---|---|+| `Q38_TRUNK_GPU=0` | keep the trunk on the CPU (experts-only tier, the behaviour before this) |+| `Q38_TRUNK_MIN_KB=<n>` | offer matrices of at least n KiB (default 1024; a round trip costs more than a tiny GEMV saves) |+| `Q38_TRUNK_SKIP=name,name` | leave the named components on the CPU (bisecting, or a component that does not pay) |+| `QT_UPLOAD_SYNC=1` | the tier's `qt_issue` waits for every in-flight upload first (tests and diagnostics: deterministic residency, no upload/compute overlap) |+| `Q38_TRUNK_CPU_INT8=1` | the same int8 rows on the CPU instead -- what the quantization alone does to the output, no GPU needed (perplexity, token parity); a matrix the GPU holds is still answered from VRAM |+| `Q38_TRUNK_SELFTEST=1` | at start, every placed matrix is checked once: GPU GEMV against the same int8 rows on the CPU (relative error printed per matrix) |++**Numerics.** GPU int8 against CPU int8 on the same rows: relative error+~1e-7 on all 553 matrices (float summation order), greedy tokens identical+over 30 tokens on the 315-token prompt and 20 on a short one. int8 against+BF16: the per-row quantization error is 1 - 3 % per matrix (largest on the+router and the hyper-connection down-mixers), and on the same prompts the+greedy text is identical to the BF16 run for the 30 tokens compared.+Perplexity on wikitext-2 (8 chunks of 512, 2048 scored tokens, llama-perplexity+protocol): 1.880 with the trunk and the expert tier on the GPU against 1.845 for+the BF16 CPU run, +1.9 %. The expert tier on its own is neutral (+0.0008 nats on+a 256-token probe), the lm_head contributes nothing, and keeping the 48 routers+in BF16 on the CPU (`Q38_TRUNK_SKIP=router`) only recovers 0.3 points (1.875):+the per-row int8 error is spread over the trunk, not concentrated in one class.+Group scales (gs 64/128) for the trunk are the lever left; that needs a kernel+format, not a placement change.++**Measured** (same machine and prompt as above, cap 224 so the RAM LRU+serves 84 % of expert reads, `COLI_TIMERS=1` decode bank, 100 tokens):++| | CPU only (BF16 trunk) | experts only, one card | trunk on one card, no experts | trunk + experts, one card | trunk + experts, two cards |+|---|---:|---:|---:|---:|---:|+| VRAM: trunk / experts | -- | 0 / 6.1 GB | 4.0 / 0.1 GB | 4.0 / 2.1 GB | 1.8 + 2.2 / 4.3 + 4.3 GB |+| VRAM share of routed experts | -- | 43 % | 2 % | 22 % | 52 % |+| resident-mm (dense trunk incl. DeltaNet proj.), ms/token | 284 | 285 | 52 | 63 | 89 |+| shared expert / lm-head, ms/token | 21 / 46 | 21 / 46 | 6 / 5 | 7 / 5 | 12 / 14 |+| routed-expert GEMV on the CPU, ms/token | 179 | 118 | 182 | 151 | 93 |+| expert-read (page-cache copies), ms/token | 168 | 164 | 162 | 160 | 145 |+| **decode, ms/token** | **744** | **754** | **557** | **523** | **466** |+| **decode tok/s** | **1.34** | **1.33** | **1.80** | **1.91** | **2.14** |+| greedy tokens (100) | reference | identical | identical | identical | identical |++Peak RSS 60.1 - 60.5 GB in every run (cap 224); TTFT 183 - 185 s in every run (the prompt's+forward stays on the CPU). On two cards the placer spreads the trunk by free room (1.8 GB on+the 3070, 2.2 GB with the lm_head on the Quadro) and the experts on both; the Quadro is the+slower card (lm-head 14 ms there against 5 ms on the 3070), which is the +26 ms of+resident-mm against one card -- and the 52 % expert share still wins by 57 ms. The trunk is+worth +34 % on its own (1.34 -> 1.80), the expert tier nothing on its own (1.33) and +6 %+on top of the trunk (1.91), because the GEMVs it saves were the small part all along; the+two-card run gets its +60 % from both. The first calibration (06.09.) gave 1.45 -> 1.76 on+the same prompt with the old binary; today's CPU baseline is 8 % lower, run-to-run scatter+of the page-cache expert reads (168 vs 149 ms), so the ratios are the comparable figures.++One thing found on the way: the backend's resident dense matvec shared its+`x`/`y` staging buffers with the asynchronous expert group. The shared+expert's three GEMVs run between `qt_issue` and `qt_take`, so with the trunk+in VRAM they overwrote the in-flight group's input and output -- no CUDA+error, only wrong tokens, worse the more experts were resident. The dense+path has its own buffers now ([qwen36-cuda-tier.md](qwen36-cuda-tier.md));+qwen36 never called the dense path inside that window.+## Performance telemetryEvery served request reports its own routed-expert cache hit rate; persistent