Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
plan: price each expert row at its own width, not the container's widest (#856)
JustVugg7c9762523056
diff --git a/c/Makefile b/c/Makefileindex e630eb54..b573d792 100644--- a/c/Makefile+++ b/c/Makefile@@ -913,6 +913,9 @@ tests/test_corpus_draft$(EXE): tests/test_corpus_draft.c colibri.c st.h uring.htests/test_cap_precedence$(EXE): tests/test_cap_precedence.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+tests/test_cap_mixed_width$(EXE): tests/test_cap_mixed_width.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h route_trace.h+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+tests/test_ssd_probe$(EXE): tests/test_ssd_probe.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)diff --git a/c/colibri.c b/c/colibri.cindex ded7b3d7..3368782d 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -2263,8 +2263,34 @@ static int expert_load_impl(Model *m, int layer, int eid, ESlot *s, int fatal, iint64_t wtot=tw[0]->nbytes+tw[1]->nbytes+tw[2]->nbytes;int64_t ftot=(tq[0]->nbytes+tq[1]->nbytes+tq[2]->nbytes)/4;/* rialloca se lo slot (riusato tra layer) e' troppo piccolo per QUESTO expert:- * pread oltre la mappatura = short-read o CORRUZIONE silenziosa dei vicini */- if(!s->slab || wtot+8192 > s->slab_cap){+ * pread oltre la mappatura = short-read o CORRUZIONE silenziosa dei vicini+ *+ * ...and reallocate when it is too LARGE, which is #856. Slabs do not stay in+ * the row that grew them: the LRU promotion swaps ws[q] with a cache slot+ * (search "promozione LRU"), so a ws[] slot widened to hold an int8 MTP expert+ * comes back on the next token, loads a narrow int4 routed expert without+ * resizing, and is then swapped into a MAIN layer's cache -- still carrying the+ * MTP width. Up to 64 slabs per token bleed that way, so given enough tokens+ * every cache slot in the model costs the widest width in the container.+ *+ * That is why cap_for_ram() charged every row the widest width: the pessimism+ * was the true asymptote, not paranoia. It also halved the cache on GLM-5.2+ * (154 -> 77 slots per row, measured in #856). Shrinking here removes the bleed,+ * which is what lets the cap be computed from each row's REAL width.+ *+ * Hysteresis, not exact fit: alignment rounding alone makes slab_cap exceed the+ * request under COLI_METAL, and a shrink for a few KB would churn the allocator+ * on every miss. 25% is relative so it scales with the model; the floor only has+ * to clear that 16 KB rounding. Experts within a row share a shape, so the only+ * thing that crosses this threshold is a slab that came from a DIFFERENT row --+ * which is exactly the migration being stopped.+ *+ * Never arena slices (aslab): those are interior pointers into one per-layer+ * allocation and must not be freed. They are already per-layer-width, so they+ * have nothing to shrink. */+ int64_t want=wtot+8192;+ int64_t hyst=want/4; if(hyst<(1<<16)) hyst=1<<16; /* 64 KB clears the 16 KB METAL rounding */+ if(!s->slab || want > s->slab_cap || (!s->aslab && s->slab_cap > want+hyst)){#ifdef COLI_METAL/* page-align + zero-copy wrap: the GPU reads this slab in place (unified memory) */if(s->slab && g_metal_enabled) coli_metal_unregister(s->slab);@@ -2280,7 +2306,10 @@ static int expert_load_impl(Model *m, int layer, int eid, ESlot *s, int fatal, inuma_slab_bind(s->slab,(size_t)s->slab_cap);#endif}- if(!s->fslab || ftot > s->fslab_cap){+ /* The scales migrate with their weights, so they shrink on the same rule (#856).+ * fslab_cap counts FLOATS, so the hysteresis is in floats too. */+ int64_t fhyst=ftot/4; if(fhyst<(1<<14)) fhyst=1<<14; /* floats, so 64 KB again */+ if(!s->fslab || ftot > s->fslab_cap || (!s->afslab && s->fslab_cap > ftot+fhyst)){#ifdef COLI_METAL/* page-align + register: the GPU reads the scales in place (unified memory).* Honours `fatal` exactly like the CPU arm below — a speculative pilot load@@ -2486,7 +2515,12 @@ static int uring_load_add(UringBatch *b,Model *m,int layer,int eid,ESlot *s,intint64_t wtot=l->tw[0]->nbytes+l->tw[1]->nbytes+l->tw[2]->nbytes;int64_t ftot=(l->tq[0]->nbytes+l->tq[1]->nbytes+l->tq[2]->nbytes)/4;if(wtot<=0 || ftot<=0) return uring_load_error(l,EINVAL,"io_uring expert size"),li;- if(!s->slab || wtot+8192>s->slab_cap){+ /* Same shrink rule as the pread path (#856): a slot that once held a wider+ * expert must not carry that width into a narrower row, or the per-row cap+ * cap_for_ram() computes stops being true. Same hysteresis, same arena guard. */+ int64_t want=wtot+8192, hyst=want/4; if(hyst<(1<<16)) hyst=1<<16;+ int64_t fhyst=ftot/4; if(fhyst<(1<<14)) fhyst=1<<14; /* floats, so 64 KB again */+ if(!s->slab || want>s->slab_cap || (!s->aslab && s->slab_cap > want+hyst)){#ifdef COLI_METALif(s->slab&&g_metal_enabled) coli_metal_unregister(s->slab);compat_aligned_free(s->slab);@@ -2501,7 +2535,7 @@ static int uring_load_add(UringBatch *b,Model *m,int layer,int eid,ESlot *s,ints->slab_cap=wtot+8192;#endif}- if(!s->fslab || ftot>s->fslab_cap){+ if(!s->fslab || ftot>s->fslab_cap || (!s->afslab && s->fslab_cap > ftot+fhyst)){#ifdef COLI_METALif(s->fslab&&g_metal_enabled) coli_metal_unregister(s->fslab);free(s->fslab); size_t fb=(((size_t)ftot*sizeof(float))+16383)&~(size_t)16383;@@ -6524,9 +6558,14 @@ static void prof_report(Model *m, const ProfBase *b, double elapsed, int tokens,int64_t io=atomic_load_explicit(&g_prof_io,memory_order_relaxed)-b->io;uint64_t dh=m->hits-b->hits, dm=m->miss-b->miss, dq=m->ereq-b->ereq;double hitp=(dh+dm)?100.0*dh/(dh+dm):100.0;- double eb=(double)expert_bytes_probe(m,m->ebits);- int pinned=0,lru=0;- for(int i=0;i<=c->n_layers;i++){ if(m->npin)pinned+=m->npin[i]; if(m->ecn)lru+=m->ecn[i]; }+ /* Per-row widths (#856): "resident experts: N (X GB)" is the line people quote+ * when they compare the engine's own accounting against free RAM. */+ int pinned=0,lru=0; double pin_b=0,lru_b=0;+ for(int i=0;i<=c->n_layers;i++){+ double w=(double)expert_bytes_row(m,i,m->ebits);+ if(m->npin){ pinned+=m->npin[i]; pin_b+=(double)m->npin[i]*w; }+ if(m->ecn){ lru+=m->ecn[i]; lru_b+=(double)m->ecn[i]*w; }+ }double io_w=m->t_ewait-b->ewait; /* stall the compute thread felt */double io_svc=edisk_s()-b->edisk; /* read service on the loading threads (overlaps compute) */uint64_t dhp=m->hit_pin-b->hit_pin, dhe=m->hit_ecache-b->hit_ecache; /* split #336 */@@ -6573,7 +6612,7 @@ static void prof_report(Model *m, const ProfBase *b, double elapsed, int tokens,}}fprintf(f,"[PROF] resident experts: %d pinned (%.1f GB) + %d in LRU (%.1f GB, cap %d/layer)\n",- pinned,pinned*eb/1e9,lru,lru*eb/1e9,m->ecap);+ pinned,pin_b/1e9,lru,lru_b/1e9,m->ecap);double emm=m->t_emm-b->emm, ecpu=m->t_ecpu-b->ecpu, egpu=m->t_egpu-b->egpu;double route=m->t_route-b->route,p2p=m->t_p2p-b->p2p;uint64_t np2p=m->n_p2p-b->n_p2p;@@ -8357,11 +8396,12 @@ static double autopin_lru_reserve(double expert_available, double bytes_per_slotreturn (double)cap*bytes_per_slot;}+/* #856: nsp*widest -> the sum of each row's REAL width. The "nsp+=2" was an+ * approximation of one wide MTP row while every OTHER row was charged the narrow+ * width; once the probe started returning the widest for all of them the two+ * compounded, and the autopin reserve inherited the same halving as the cap. */static double expert_cache_bytes_per_slot(Model *m, int ebits){- int nsp=0;- for(int i=0;i<m->c.n_layers;i++) if(m->L[i].sparse) nsp++;- if(m->has_mtp) nsp+=2;- return (double)nsp*(double)expert_bytes_probe(m,ebits);+ return expert_cache_row_bytes(m,ebits);}/* clampa la cache expert a un budget RAM (GB): cap t.c. residente + cache + slack <= budget.@@ -8369,8 +8409,13 @@ static double expert_cache_bytes_per_slot(Model *m, int ebits){* sforare = OOM-kill del kernel a meta' generazione, molto peggio di una cache piu' piccola). */static void cap_for_ram(Model *m, double ram_gb, int ebits, int max_ctx){Cfg *c=&m->c; int nsp=0; for(int i=0;i<c->n_layers;i++) if(m->L[i].sparse) nsp++;- if(m->has_mtp) nsp+=2; /* riga cache MTP: conta ~doppia (expert int8 = 2x int4) */+ if(m->has_mtp) nsp++; /* la riga MTP e' una riga; la sua LARGHEZZA+ * la porta row_b, non piu' un "conta doppio" */+ /* eb = the WIDEST width in the container: correct for ws[], which is shared across+ * rows, and only for that. row_b = the sum of the widths the rows really hold,+ * which is what one LRU slot per row costs (#856). */int64_t eb=expert_bytes_probe(m,ebits);+ double row_b=expert_cache_row_bytes(m,ebits);int auto_b = ram_gb<=0;if(auto_b){ ram_gb = g_mem_avail_boot*0.88; /* misurata PRIMA del load: il residente gia'* allocato viene sottratto sotto, non due volte */@@ -8400,7 +8445,7 @@ static void cap_for_ram(Model *m, double ram_gb, int ebits, int max_ctx){double pc_b = 2.5e9;double slack = 1.2e9 + pc_b + ws_b + kv_b + kvb_b;double avail = ram_gb*1e9 - (double)m->resident_bytes - slack;- int capmax = (avail>0 && nsp>0) ? (int)(avail/((double)nsp*eb)) : 0;+ int capmax = (avail>0 && row_b>0) ? (int)(avail/row_b) : 0;int floored = capmax<1; /* il budget non regge nemmeno UNO slot per layer */if(capmax<1) capmax=1;/* Il floor a 1 e' una bugia comoda: con avail negativo capmax sarebbe 0, cioe'@@ -8410,14 +8455,16 @@ static void cap_for_ram(Model *m, double ram_gb, int ebits, int max_ctx){* nessun log, il motore muore muto (issue #305). Dirlo, e fermarsi se il picco* non entra nemmeno nella RAM realmente disponibile misurata all'avvio. */if(floored){- double peak = (double)m->resident_bytes + (double)capmax*nsp*eb + slack;- /* eb is printed because it is the one term nobody can check from outside:- * every projection here divides by it, so a wrong width is indistinguishable- * from a wrong budget in this message (#766). */+ double peak = (double)m->resident_bytes + (double)capmax*row_b + slack;+ /* The width is printed because it is the one term nobody can check from+ * outside: every projection here divides by it, so a wrong width is+ * indistinguishable from a wrong budget in this message (#766). Report the+ * per-row AVERAGE, since that is now the divisor -- printing the widest while+ * dividing by something else is how #856 stayed invisible for a release. */fprintf(stderr,"[RAM_GB=%.1f%s] WARNING: cap=1 is the floor, projected peak %.1f GB is "- "%.1f GB OVER the budget (resident %.1f GB + reserve %.1f GB, expert %.1f MB).%s\n",+ "%.1f GB OVER the budget (resident %.1f GB + reserve %.1f GB, expert %.1f MB avg/row).%s\n",ram_gb,auto_b?" auto":"",peak/1e9,(peak-ram_gb*1e9)/1e9,- m->resident_bytes/1e9,slack/1e9,(double)eb/1e6,+ m->resident_bytes/1e9,slack/1e9,row_b/(nsp>0?nsp:1)/1e6,getenv("PIN_GB")?" PIN_GB is inflating the resident set: lower it or drop it.":"");#ifdef COLI_CUDA/* #686: on a single GPU that also holds host copies of the VRAM tier, the@@ -8440,11 +8487,11 @@ static void cap_for_ram(Model *m, double ram_gb, int ebits, int max_ctx){}if(capmax < m->ecap){fprintf(stderr,"[RAM_GB=%.1f%s] resident %.1f GB + reserve %.1f GB (ws %.1f, KV %dx%d %.1f, kvb %.1f), "- "experts %.1f MB x %d layers -> cap lowered %d->%d (projected peak %.1f GB)\n",+ "experts %.1f MB avg x %d layers -> cap lowered %d->%d (projected peak %.1f GB)\n",ram_gb,auto_b?" auto":"",m->resident_bytes/1e9,slack/1e9,ws_b/1e9,kv_slot_count(),max_ctx,kv_b/1e9,kvb_b/1e9,- eb/1e6, nsp, m->ecap, capmax,- (m->resident_bytes + (double)capmax*nsp*eb + slack)/1e9);+ row_b/(nsp>0?nsp:1)/1e6, nsp, m->ecap, capmax,+ (m->resident_bytes + (double)capmax*row_b + slack)/1e9);m->ecap=capmax;} else {/* AUTO-RAISE (issue #12): il budget consente PIU' cache di quella chiesta.@@ -8468,11 +8515,11 @@ static void cap_for_ram(Model *m, double ram_gb, int ebits, int max_ctx){fprintf(stderr,"[RAM_GB=%.1f%s] cap raised %d->%d: budget allows it ""(projected peak %.1f GB; set CAP_RAISE=0 to disable)\n",ram_gb, auto_b?" auto":"", m->ecap, newcap,- (m->resident_bytes + (double)newcap*nsp*eb + slack)/1e9);+ (m->resident_bytes + (double)newcap*row_b + slack)/1e9);m->ecap=newcap;} elsefprintf(stderr,"[RAM_GB=%.1f%s] cap=%d ok (projected peak %.1f GB)\n", ram_gb, auto_b?" auto":"", m->ecap,- (m->resident_bytes + (double)m->ecap*nsp*eb + slack)/1e9);+ (m->resident_bytes + (double)m->ecap*row_b + slack)/1e9);}}@@ -8509,15 +8556,21 @@ static void prof_config(Model *m, double ram_env, int est_ctx){if(g_metal_enabled) backend="Metal";#endifint nsp=0; for(int i=0;i<c->n_layers;i++) if(m->L[i].sparse) nsp++;- int rows=nsp+(m->has_mtp?2:0); /* stessa convenzione di cap_for_ram (MTP int8 = 2x) */- int pinned=0; for(int i=0;i<=c->n_layers;i++) if(m->npin) pinned+=m->npin[i];- double eb=(double)expert_bytes_probe(m,m->ebits);+ /* #856: the cache figure comes from the same per-row sum the cap is computed+ * from. Printing a projection derived differently from the cap is how the+ * halving stayed invisible through a whole release. */+ int pinned=0; double pin_b=0;+ for(int i=0;i<=c->n_layers;i++) if(m->npin){+ pinned+=m->npin[i];+ pin_b+=(double)m->npin[i]*(double)expert_bytes_row(m,i,m->ebits);+ }+ (void)nsp;fprintf(stderr,"[PROF] machine: %s | %d cores (%d omp threads) | RAM %.1f GB total, %.1f GB available | backend %s\n",cpu[0]?cpu:"unknown CPU",cores,omp_get_max_threads(),rt,ra,backend);fprintf(stderr,"[PROF] config: RAM_GB=%s%.1f CTX=%d | expert cache cap %d/layer (up to %.1f GB) | pinned %d (%.1f GB) | ""DRAFT=%d PIPE=%d DIRECT=%d MMAP=%d IDOT=%d DSA=%s PILOT=%d CACHE_ROUTE=%d\n",ram_env<=0?"auto ":"",ram_env<=0?g_mem_avail_boot*0.88:ram_env,est_ctx,- m->ecap,(double)m->ecap*rows*eb/1e9,pinned,pinned*eb/1e9,+ m->ecap,(double)m->ecap*expert_cache_row_bytes(m,m->ebits)/1e9,pinned,pin_b/1e9,g_draft,g_pipe,g_direct,g_mmap,g_idot,(m->has_dsa&&c->index_topk)?"on":"off",g_pilot,g_cache_route);}diff --git a/c/telemetry.h b/c/telemetry.hindex c0732a0f..192f4331 100644--- a/c/telemetry.h+++ b/c/telemetry.h@@ -43,7 +43,11 @@ static int64_t expert_bytes_layer(Model *m, int layer){* 118 GB. The projection's shape was right; only this constant was wrong.** nsp += 2 in cap_for_ram() already nods at the MTP row costing double, but that- * corrects one row out of nsp; the slabs grow on all of them. */+ * corrects one row out of nsp; the slabs grow on all of them.+ *+ * #856 SCOPE: this is the right width for the ws[64] working set, whose slots ARE+ * shared across rows, and for nothing else. Sizing the per-row LRU caches with it+ * is what expert_cache_row_bytes() below replaces. */static int64_t expert_bytes_probe(Model *m, int ebits){Cfg *c=&m->c;int64_t eb=expert_bytes_layer(m,c->first_dense);@@ -52,6 +56,36 @@ static int64_t expert_bytes_probe(Model *m, int ebits){return eb;}+/* Width of the experts ONE row actually holds; same fallback as the probe above.+ *+ * Every row has its own ecache[layer] and its own pin arena, so a row costs the+ * width IT holds. Charging all of them the container's widest halved the cache on+ * GLM-5.2 shipped as int4 routed + int8 MTP: 154 -> 77 slots per row, with the+ * 5,852 experts that left RAM reappearing one-for-one on disk (#856). Diagnosis by+ * @terrizoaguimor from @brad-evony's dashboard screenshots. */+static int64_t expert_bytes_row(Model *m, int layer, int ebits){+ Cfg *c=&m->c;+ int64_t eb=expert_bytes_layer(m,layer);+ if(eb>0) return eb;+ eb = tbytes(c->moe_inter,c->hidden,ebits)*2 + tbytes(c->hidden,c->moe_inter,ebits);+ /* Header unreadable. For the MTP row keep the old "counts double" approximation+ * (nsp+=2 in cap_for_ram) rather than assume it is as narrow as a routed row:+ * under-reserving is the direction that ends in an OOM-kill. */+ return layer==c->n_layers ? eb*2 : eb;+}++/* What ONE slot per row costs across EVERY row -- the divisor of the expert budget.+ * Stateless on purpose: st_find is a hash lookup, so this is ~6 probes per layer+ * and a few hundred for a 78-layer model, called a handful of times at startup.+ * A memo keyed on anything less than (model, ebits) is a staleness bug waiting for+ * whoever next changes has_mtp or the layer map. */+static double expert_cache_row_bytes(Model *m, int ebits){+ Cfg *c=&m->c; double sum=0;+ for(int i=0;i<c->n_layers;i++) if(m->L[i].sparse) sum+=(double)expert_bytes_row(m,i,ebits);+ if(m->has_mtp) sum+=(double)expert_bytes_row(m,c->n_layers,ebits);+ return sum;+}+/* BRAIN MAP: per-turn expert hit bitmap for the dashboard. */static uint8_t **g_ehit;static void ehit_mark(Model *m, int layer, int eid){@@ -148,8 +182,20 @@ static void tiers_emit(Model *m){#endifint ram=pinned-vram+lru; if(ram<0) ram=0;int disk=total-vram-ram; if(disk<0) disk=0;- double eb=(double)expert_bytes_probe(m,m->ebits);- printf("TIERS %d %d %d %.2f %.2f\n",vram,ram,disk,vram_gb,ram*eb/1e9);+ /* Per-row widths, not count x widest. The dashboard read "RAM tier ~221 GB" on a+ * box where Windows still showed 140 GB free, because every resident expert was+ * being priced as an int8 MTP one (#856). A tier figure that disagrees with the+ * operating system teaches people to distrust the panel. */+ double ram_b=0;+ for(int i=0;i<=c->n_layers;i++){+ int64_t w=expert_bytes_row(m,i,m->ebits);+ ram_b += (double)((m->npin?m->npin[i]:0)+(m->ecn?m->ecn[i]:0))*(double)w;+ }+ if(vram>0){ /* the VRAM tier's host copies are not RAM-tier bytes */+ double avg = ram+vram>0 ? ram_b/(double)(ram+vram) : 0.0;+ ram_b -= avg*(double)vram; if(ram_b<0) ram_b=0;+ }+ printf("TIERS %d %d %d %.2f %.2f\n",vram,ram,disk,vram_gb,ram_b/1e9);fflush(stdout);}diff --git a/c/tests/test_cap_mixed_width.c b/c/tests/test_cap_mixed_width.cnew file mode 100644index 00000000..236d79bf--- /dev/null+++ b/c/tests/test_cap_mixed_width.c@@ -0,0 +1,309 @@+/* test_cap_mixed_width.c -- #856: a mixed-width container must not price every+ * expert row at the container's widest width.+ *+ * GLM-5.2 ships as int4 routed experts with an int8 MTP head. #793 made+ * expert_bytes_probe() return the WIDEST width in the container, which is right+ * for the shared ws[64] working set and wrong for the per-layer LRU caches --+ * each of which holds only its own row's experts. cap_for_ram() divided by it,+ * so the cache halved: 154 -> 77 slots per row on the reporter's box, with the+ * 5,852 experts that left RAM reappearing one-for-one on disk.+ *+ * Two things have to hold, and this exercises both against a REAL container+ * written to disk and indexed by st_init -- fabricated widths, not fabricated+ * arithmetic:+ *+ * 1. the budget divisor is the SUM of each row's real width+ * 2. a slot that once held a wide expert SHRINKS when it is reused for a+ * narrow row -- otherwise the wide slab migrates through the ws[]<->LRU+ * swap into narrow rows and (1) becomes a lie the allocator disproves+ */+#define main coli_glm_main_unused+#include "../colibri.c"+#undef main++#include <stdio.h>+#include <string.h>+#include <sys/stat.h>++static int fails = 0;+#define CHECK(c) do{ if(!(c)){ printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } }while(0)++/* Small enough to write, structured exactly like the real thing: sparse layers+ * 1..4 are int4 (half a byte per weight + one f32 scale per row), layer 5 is the+ * MTP head at int8 (one byte per weight). Ratio 2:1 on the weights, which is the+ * ratio that produced the exact halving in the field. */+/* Big enough that the shrink's 25% relative threshold dominates its 64 KB floor:+ * a toy-sized expert is smaller than the anti-churn floor, so nothing would ever+ * shrink and the test would pass by never exercising the path. */+enum { N_LAYERS = 5, FIRST_DENSE = 1, N_EXPERTS = 2, O = 384, I = 768 };++static const char *SUF[3] = { "gate_proj", "up_proj", "down_proj" };++typedef struct { char name[128]; int64_t nbytes; const char *dtype; } Ent;+static Ent ents[512]; static int nent;++static void add(const char *fmt, int64_t nbytes, const char *dtype, int l, int e, const char *suf){+ Ent *t=&ents[nent++];+ snprintf(t->name,sizeof t->name,fmt,l,e,suf);+ t->nbytes=nbytes; t->dtype=dtype;+}++/* gate/up are [moe_inter, hidden]; down is [hidden, moe_inter] -- transposed, so+ * its row count (and therefore its per-row scale array) differs. Getting this+ * wrong makes the loader reject the container, which is itself a useful signal+ * that the fixture is shaped like a real one.+ * int4: rows*(cols+1)/2 weight bytes + rows f32 scales. int8: rows*cols + rows f32.+ * Exactly the arithmetic expert_bytes_layer() sums out of the headers. */+static void add_expert_dims(int l, int e, int int8, int inter, int hid){+ for(int k=0;k<3;k++){+ int rows = (k==2) ? hid : inter, cols = (k==2) ? inter : hid; /* k==2 is down_proj */+ add("model.layers.%d.mlp.experts.%d.%s.weight",+ int8 ? (int64_t)rows*cols : (int64_t)rows*((cols+1)/2), "U8", l, e, SUF[k]);+ add("model.layers.%d.mlp.experts.%d.%s.weight.qs",+ (int64_t)rows*4, "F32", l, e, SUF[k]);+ }+}+static void add_expert(int l, int e, int int8){ add_expert_dims(l,e,int8,O,I); }++/* Flush whatever add_expert queued into a real single-shard container. st_init+ * refuses data_offsets past EOF, so the payload has to exist -- no sparse+ * shortcut: ftruncate is free on ext4 and is NOT free on the NTFS runner. */+static int write_ents(const char *dir){+ char path[256]; snprintf(path,sizeof path,"%s/model.safetensors",dir);+ char *hdr=malloc(1<<20); int hn=0; int64_t off=0;+ hn+=sprintf(hdr+hn,"{");+ for(int i=0;i<nent;i++){+ hn+=sprintf(hdr+hn,"%s\"%s\":{\"dtype\":\"%s\",\"shape\":[%lld],\"data_offsets\":[%lld,%lld]}",+ i?",":"", ents[i].name, ents[i].dtype,+ (long long)ents[i].nbytes/(ents[i].dtype[0]=='F'?4:1),+ (long long)off,(long long)(off+ents[i].nbytes));+ off+=ents[i].nbytes;+ }+ hn+=sprintf(hdr+hn,"}");+ while(hn%8) hdr[hn++]=' ';++ FILE *f=fopen(path,"wb"); if(!f){ free(hdr); return 0; }+ uint64_t hl=(uint64_t)hn; fwrite(&hl,8,1,f); fwrite(hdr,1,(size_t)hn,f);+ void *zero=calloc(1,65536);+ for(int64_t left=off;left>0;){ size_t n=left>65536?65536:(size_t)left; fwrite(zero,1,n,f); left-=(int64_t)n; }+ free(zero); free(hdr); fclose(f);+ return 1;+}++static int write_container(const char *dir){+ nent=0;+ for(int l=FIRST_DENSE;l<N_LAYERS;l++)+ for(int e=0;e<N_EXPERTS;e++) add_expert(l,e,0); /* routed rows: int4 */+ for(int e=0;e<N_EXPERTS;e++) add_expert(N_LAYERS,e,1); /* MTP row: int8 */+ return write_ents(dir);+}++/* GLM-5.2's real per-expert widths, from its config.json: hidden 6144,+ * moe_intermediate 2048, first_k_dense_replace 3, 78 layers, MTP head at int8.+ * Only expert 0 of one routed layer and of the MTP layer are written, because+ * expert_bytes_layer() probes exactly those; the other 74 routed rows fall back+ * to tbytes(), which yields the identical width. 54 MB, and it is the only way+ * to make the probe return the int8 head -- which is the whole defect. */+static int write_glm_probe_container(const char *dir){+ nent=0;+ add_expert_dims(3,0,0,2048,6144); /* routed row, int4 -> 18,915,328 B */+ add_expert_dims(78,0,1,2048,6144); /* MTP head, int8 -> 37,789,696 B */+ return write_ents(dir);+}++int main(void){+ const char *dir="tests/tmp_cap_mixed";+#ifdef _WIN32+ mkdir(dir);+#else+ mkdir(dir,0755);+#endif+ if(!write_container(dir)){ printf("FAIL: could not write the fixture container\n"); return 1; }++ Model m; memset(&m,0,sizeof m);+ Cfg *c=&m.c;+ c->n_layers=N_LAYERS; c->first_dense=FIRST_DENSE; c->n_experts=N_EXPERTS;+ c->hidden=I; c->moe_inter=O;+ m.ebits=4; m.has_mtp=1;+ m.L=calloc(N_LAYERS+1,sizeof(Layer));+ for(int i=FIRST_DENSE;i<N_LAYERS;i++) m.L[i].sparse=1;+ st_init(&m.S,dir); /* void: it exits on a malformed container */+ if(!st_find(&m.S,"model.layers.1.mlp.experts.0.gate_proj.weight")){+ printf("FAIL: st_init did not index the fixture\n"); return 1; }++ /* ---- A. GLM-5.2's REAL geometry, no container ------------------------- */+ /* expert_bytes_row falls back to the tbytes() formula when a header is absent,+ * so the published config alone reproduces the shipped widths -- and this is+ * the only coverage that fallback branch has. Numbers from GLM-5.2's+ * config.json: 78 layers, first_k_dense_replace 3, hidden 6144,+ * moe_intermediate 2048, num_nextn_predict_layers 1. */+ {+ const char *gdir="tests/tmp_cap_glm";+#ifdef _WIN32+ mkdir(gdir);+#else+ mkdir(gdir,0755);+#endif+ if(!write_glm_probe_container(gdir)){ printf("FAIL: GLM fixture\n"); return 1; }+ Model g; memset(&g,0,sizeof g);+ g.c.n_layers=78; g.c.first_dense=3; g.c.n_experts=256;+ g.c.hidden=6144; g.c.moe_inter=2048; g.ebits=4; g.has_mtp=1;+ g.L=calloc(79,sizeof(Layer));+ for(int i=3;i<78;i++) g.L[i].sparse=1; /* 75 MoE rows */+ st_init(&g.S,gdir);+ int grows=0; for(int i=0;i<78;i++) if(g.L[i].sparse) grows++;+ int64_t gnarrow=expert_bytes_row(&g,3,4); /* from the header */+ int64_t gwide =expert_bytes_row(&g,78,4); /* from the header */+ int64_t gfall =expert_bytes_row(&g,40,4); /* no header: tbytes fallback */+ int64_t gprobe =expert_bytes_probe(&g,4);+ printf("A. GLM-5.2: %d MoE rows + MTP = %d | int4 %lld B | int8 MTP %lld B | probe %lld B\n",+ grows,grows+1,(long long)gnarrow,(long long)gwide,(long long)gprobe);+ CHECK(grows==75); /* 76 rows, exactly what the report showed */+ CHECK(gnarrow==18915328); /* the 18.9 MB int4 expert the docs quote */+ CHECK(gwide ==37789696); /* the 37.79 MB int8 MTP measured on the A6000 */+ CHECK(gfall ==gnarrow); /* headerless rows agree with the headers */+ CHECK(gprobe ==gwide); /* the probe is the container maximum */++ /* Cost of ADDING the MTP row -- the whole of #856. Measured twice the same+ * way, so nothing here duplicates cap_for_ram's slack formula. */+ g_mem_avail_boot=512.0;+ g.has_mtp=0; g.resident_bytes=0; g.ecap=1<<20; cap_for_ram(&g,242.0,4,4096);+ int cap_no=g.ecap;+ g.has_mtp=1; g.resident_bytes=0; g.ecap=1<<20; cap_for_ram(&g,242.0,4,4096);+ int cap_yes=g.ecap;+ printf("A. cap %d -> %d on adding one MTP row to 75 (%.1f%% lost)\n",+ cap_no,cap_yes,100.0*(1.0-(double)cap_yes/(double)cap_no));+ CHECK(cap_no>0 && cap_yes>0);+ /* One row in 76 costs ~2.6%. v1.5.0 charged ~51% -- the halving. */+ CHECK((double)cap_yes/(double)cap_no > 0.95);+ /* And the reporter's shape: from the SAME budget, the old divisor yields+ * half the slots. 11,704 experts in RAM became 5,852; 154/row became 77. */+ double d_new=(double)grows*(double)gnarrow+(double)gwide;+ double d_150=(double)(grows+2)*(double)gprobe;+ CHECK(fabs(d_150/d_new-2.0)<0.01);+ CHECK((int)(154.0*d_new/d_150)==77);+ free(g.L);+ { char pth[256]; snprintf(pth,sizeof pth,"%s/model.safetensors",gdir);+ remove(pth); rmdir(gdir); }+ }++ /* ---- the widths the container really holds ---------------------------- */+ int64_t narrow = expert_bytes_row(&m,FIRST_DENSE,m.ebits);+ int64_t wide = expert_bytes_row(&m,N_LAYERS,m.ebits);+ int64_t probe = expert_bytes_probe(&m,m.ebits);+ printf(" routed row %lld B\n MTP row %lld B\n probe(max) %lld B\n",+ (long long)narrow,(long long)wide,(long long)probe);+ CHECK(narrow > 0);+ CHECK(wide > narrow); /* int8 head is wider than int4 rows */+ CHECK(probe == wide); /* the probe is the container maximum */++ /* ---- (1) the divisor is the sum of the REAL widths --------------------- */+ int nsp=0; for(int i=0;i<c->n_layers;i++) if(m.L[i].sparse) nsp++;+ double row_b = expert_cache_row_bytes(&m,m.ebits);+ double want = (double)nsp*(double)narrow + (double)wide;+ double v150 = (double)(nsp+2)*(double)probe; /* what v1.5.0 divided by */+ printf(" divisor now %.0f B (v1.5.0 used %.0f B, %.2fx)\n", row_b, v150, v150/row_b);+ CHECK(fabs(row_b-want) < 1.0);+ CHECK(v150 > row_b); /* v1.5.0 over-charged, hence the halving */++ /* The cap is avail/divisor, so the ratio of divisors IS the ratio of caps.+ * Four int4 rows charged as int8 against one genuinely int8 row lands just+ * under 2x -- the scales are the same size at both widths, so the weights+ * double and the container does not quite. That is the halving the reporter+ * measured (154 -> 77) at this fixture's scale. */+ CHECK(v150 > 1.8*row_b);++ /* expert_cache_bytes_per_slot feeds the autopin LRU reserve; it must agree+ * with the cap's divisor or pinning re-introduces the same shortfall. */+ CHECK(fabs(expert_cache_bytes_per_slot(&m,m.ebits)-row_b) < 1.0);++ /* ---- end to end: the cap cap_for_ram() really sets ---------------------- */+ /* Discriminating, and it duplicates none of cap_for_ram's slack formula: run the+ * SAME budget with and without the MTP row. Adding one int8 row to four int4 rows+ * must cost (4u+2u)/4u = 1.5x of the cap. v1.5.0 charged (4+2)*2u against 4u --+ * 3x -- because the MTP row both widened every other row AND counted twice. */+ g_mem_avail_boot=64.0;+ m.has_mtp=0; m.resident_bytes=0; m.ecap=1<<20; cap_for_ram(&m,8.0,m.ebits,128);+ int cap_routed_only=m.ecap;+ m.has_mtp=1; m.resident_bytes=0; m.ecap=1<<20; cap_for_ram(&m,8.0,m.ebits,128);+ int cap_with_mtp=m.ecap;+ double cost=(double)cap_routed_only/(double)cap_with_mtp;+ printf(" cap %d (routed only) -> %d (+MTP row) = %.2fx\n",+ cap_routed_only,cap_with_mtp,cost);+ CHECK(cap_routed_only>0 && cap_with_mtp>0);+ CHECK(cost > 1.3 && cost < 1.7); /* ~1.5x, the honest cost of one wide row */+ CHECK(cost < 2.5); /* v1.5.0 landed near 3x here */++ /* ---- (2) a reused slot must shrink back down --------------------------- */+ /* This is what makes (1) true rather than optimistic: the LRU promotion in+ * moe() swaps ws[] slots into per-layer caches, so without a shrink the wide+ * slab migrates into a narrow row and stays there. */+ ESlot s; memset(&s,0,sizeof s);+ CHECK(expert_load(&m,N_LAYERS,0,&s,0,0)==0); /* wide row first */+ int64_t cap_after_wide = s.slab_cap;+ CHECK(cap_after_wide >= wide);+ CHECK(expert_load(&m,FIRST_DENSE,0,&s,0,0)==0); /* now the same slot, narrow row */+ int64_t cap_after_narrow = s.slab_cap;+ printf(" slab_cap after MTP %lld B -> after routed %lld B\n",+ (long long)cap_after_wide,(long long)cap_after_narrow);+ CHECK(cap_after_narrow < cap_after_wide); /* it came down */+ CHECK(cap_after_narrow >= narrow); /* and still fits what it holds */++ /* Negative control: the shrink must never make a slot too small for its own+ * expert. Reload the wide row into the shrunken slot and require it to grow. */+ CHECK(expert_load(&m,N_LAYERS,1,&s,0,0)==0);+ CHECK(s.slab_cap >= wide);++ /* ---- D. the migration itself, as moe() actually performs it ------------ */+ /* colibri.c:4803 is ESlot tmp=*dst; *dst=m->ws[q]; m->ws[q]=tmp; -- the cache+ * slot's OLD contents travel back into ws[]. So a wide slab reaches a narrow row+ * on the THIRD step, not the first, which is why a two-load test would miss it. */+ {+ ESlot ws, mtp_cache, main_cache;+ memset(&ws,0,sizeof ws); memset(&mtp_cache,0,sizeof mtp_cache);+ memset(&main_cache,0,sizeof main_cache);+ ESlot tmp;+ /* 1: MTP miss loads wide into ws, promoted into an empty MTP cache slot */+ CHECK(expert_load(&m,N_LAYERS,0,&ws,0,0)==0);+ tmp=mtp_cache; mtp_cache=ws; ws=tmp;+ /* 2: another MTP miss; the promotion now EVICTS, handing the wide slab back */+ CHECK(expert_load(&m,N_LAYERS,1,&ws,0,0)==0);+ tmp=mtp_cache; mtp_cache=ws; ws=tmp;+ CHECK(ws.slab_cap >= wide); /* ws is carrying a wide slab now */+ /* 3: a MAIN row's miss reuses that slot -- the bleed, if nothing shrinks */+ CHECK(expert_load(&m,FIRST_DENSE,1,&ws,0,0)==0);+ tmp=main_cache; main_cache=ws; ws=tmp;+ printf("D. slab that reached the int4 row: %lld B (a wide one is %lld B)\n",+ (long long)main_cache.slab_cap,(long long)wide);+ CHECK(main_cache.slab_cap < wide); /* the narrow row is not paying int8 */+ CHECK(main_cache.slab_cap >= narrow); /* and still holds what it holds */+ }++ /* ---- C. arena slices must never be shrunk ------------------------------ */+ /* pin_arena_bind hands slots interior pointers into ONE per-layer allocation+ * (#419). Freeing one would corrupt the heap, and they are already per-layer+ * width so they have nothing to shrink. Prove the guard, not the intention. */+ {+ size_t stride=(size_t)wide+8192;+ uint8_t *arena=NULL;+ CHECK(posix_memalign((void**)&arena,4096,stride)==0);+ float *farena=calloc(1<<16,sizeof(float));+ ESlot a; memset(&a,0,sizeof a);+ a.slab=arena; a.aslab=arena; a.slab_cap=(int64_t)stride;+ a.fslab=farena; a.afslab=farena; a.fslab_cap=1<<16;+ CHECK(expert_load(&m,FIRST_DENSE,0,&a,0,0)==0); /* narrow expert in a wide arena slice */+ printf("C. arena slot: slab %s, cap %lld (was %lld)\n",+ a.slab==arena?"untouched":"MOVED", (long long)a.slab_cap,(long long)stride);+ CHECK(a.slab==arena); /* not freed, not reallocated */+ CHECK(a.slab_cap==(int64_t)stride); /* and its capacity was left alone */+ CHECK(a.fslab==farena);+ free(farena); compat_aligned_free(arena);+ }++ /* 5 MB of zero payload: leave the tree as we found it. */+ { char path[256]; snprintf(path,sizeof path,"%s/model.safetensors",dir);+ remove(path); rmdir(dir); }++ printf("test_cap_mixed_width: %s\n", fails?"FAILED":"ok");+ return fails?1:0;+}