Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(qwen36): automatic placement of the dense trunk (COLI_PLACE=auto)
kreuzzelgff13134a46e5
diff --git a/c/Makefile b/c/Makefileindex ab9d41a0..86ddde1d 100644--- a/c/Makefile+++ b/c/Makefile@@ -1683,6 +1683,14 @@ tests/test_qwen36_tier_shutdown$(EXE): tests/test_qwen36_tier_shutdown.c tests/qtests/test_qwen36_tier_invariants$(EXE): tests/test_qwen36_tier_invariants.c tests/qwen36_fake_cuda.h qwen36_tier.c qwen36_tier.h backend_cuda.h$(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)+# Same fake backend: the automatic placement (COLI_PLACE unset/"auto") puts+# the offered dense trunk into VRAM by bytes-saved-per-byte, prices displaced+# experts by heat, keeps the trunk on the CPU when the marginal experts are+# hotter, honours an explicit list and "off", and takes placed bytes out of+# the expert budget -- on one and on two devices.+tests/test_qwen36_tier_autoplace$(EXE): tests/test_qwen36_tier_autoplace.c tests/qwen36_fake_cuda.h qwen36_tier.c qwen36_tier.h backend_cuda.h+ $(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)+tests/test_qwen36_tier_int8_engine$(EXE): tests/test_qwen36_tier_int8_engine.c tests/qwen36_fake_cuda.h qwen36.c qwen36_tier.c qwen36_tier.h backend_cuda.h cli_args.h st.h json.h compat.h$(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)diff --git a/c/qwen36.c b/c/qwen36.cindex e66c3e1d..26abfa35 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -2859,6 +2859,23 @@ int main(int argc, char **argv) {int64_t want = 2*(int64_t)m.c.inter*m.c.hidden + (int64_t)m.c.hidden*m.c.inter;if (pt && pt->nbytes == want) expert_is_int4 = 0; /* int8: un byte per elemento */}+ /* Offer the dense trunk to the placer before the tier decides its budget:+ * sizes only, from the same dense-i8 entries the uploads below will use.+ * No entry (dense-i8 off) means nothing to offer, and the CPU path stands. */+ {+ int O_qkv = m.c.dn_conv_dim, O_z = m.c.dn_vheads * m.c.dn_vdim;+ for (int i = 0; i < g_qdw_n; i++)+ if (g_qdw[i].w == m.lm_head)+ qt_trunk_offer("lmhead", 0, (size_t)g_qdw[i].I * g_qdw[i].O + (size_t)g_qdw[i].O * sizeof(float));+ for (int i = 0; i < m.c.n_layers; i++) {+ if (m.c.is_attn[i]) continue;+ int have = 0;+ for (int j = 0; j < g_qdw_n; j++)+ if (g_qdw[j].w == m.L[i].dn_qkv || g_qdw[j].w == m.L[i].dn_z) have++;+ if (have == 2)+ qt_trunk_offer("dnproj", i, (size_t)(O_qkv + O_z) * m.c.hidden + (size_t)(O_qkv + O_z) * sizeof(float));+ }+ }if (qt_init(m.c.n_layers, m.c.n_experts, m.c.hidden, m.c.inter, cap, m.c.topk,m.c.expert_gs, expert_is_int4)) {fprintf(stderr, "[gpu] MoE experts -> CUDA VRAM tier\n");diff --git a/c/qwen36_tier.c b/c/qwen36_tier.cindex d6724c95..29216b8e 100644--- a/c/qwen36_tier.c+++ b/c/qwen36_tier.c@@ -214,7 +214,54 @@ static int qt_place_named(const char *component){return 0;}+/* ---- DeltaNet input projections ----------------------------------------- */+/* One fused qkv++z tensor per DeltaNet layer. Indexed by model layer index,+ * so the array is n_layers wide and the attention slots stay empty. */+#define QT_DN_MAX_LAYERS 128+static struct { ColiCudaTensor *t; int dev, on; } G_dnp[QT_DN_MAX_LAYERS];++/* ---- automatic placement (COLI_PLACE unset or "auto") ------------------ */+/* The hand-written list above is a measurement tool. Nobody running a 6 GB+ * card should have to work out that 1.2 GB of dense trunk is worth more than+ * 800 experts (#1040); the engine knows every size involved and decides.+ *+ * Rule: bytes saved on the memory bus per token, per byte of VRAM spent.+ * dense component -> read on EVERY token: value 1.0 per byte.+ * routed expert -> read with the probability p_e that a token routes to+ * it (heat share when a HEAT_FILE exists, topk/n_experts+ * otherwise), and the CPU fallback reads the int8 slot,+ * which is twice the bytes an int4 expert occupies in+ * VRAM: value 2*p_e per byte (1*p_e on an int8 container).+ * A trunk item goes to the device with the most room if its value beats the+ * value of the coldest experts it would push out of that device -- the+ * experts at the tail of the heat order that still fit today. Without heat+ * that tail is worth 2*topk/n_experts per byte (0.06 on the 35B) and the+ * trunk always wins; with heat, a card whose marginal expert is routed on+ * more than every second token keeps its experts. That is the R4+ * measurement: on two near-full 8 GB cards, moving all projections onto one+ * card cost 0.7 GB of hot experts and lost 13 ms of savings again.+ *+ * The engine OFFERS the trunk before qt_init (qt_trunk_offer: component,+ * layer, bytes -- sizes only, pointers come later as before); the decision+ * lands in the same table qt_place_of() reads, so nothing downstream+ * changes. Placed bytes are subtracted from that device's expert budget,+ * which the hand-written list never did (the 0.7 GB above was the+ * discovery). COLI_PLACE=off keeps today's behaviour: nothing placed. */+#define QT_OFFER_MAX 1024+static struct { char name[16]; int layer; size_t bytes; } G_offer[QT_OFFER_MAX];+static int G_offer_n;+static int G_auto_on; /* auto placement decided */+static int G_auto_lmh = QT_PLACE_CPU;+static int G_auto_dnp[QT_DN_MAX_LAYERS]; /* per layer, or QT_PLACE_CPU */+static size_t G_trunk_bytes[QT_MAX_DEV]; /* placed trunk per device index */+int qt_place_of(const char *component, int layer){+ if(G_auto_on){+ if(!strcmp(component, "lmhead")) return G_auto_lmh;+ if(!strcmp(component, "dnproj"))+ return (layer >= 0 && layer < QT_DN_MAX_LAYERS) ? G_auto_dnp[layer] : QT_PLACE_CPU;+ return QT_PLACE_CPU; /* experts follow COLI_GPUS; dnout/attnproj not yet placed */+ }if(!G_place_done) place_parse();for(int i = 0; i < G_place_n; i++){if(strcmp(G_place[i].name, component)) continue;@@ -230,11 +277,100 @@ int qt_place_of(const char *component, int layer){return QT_PLACE_CPU;}-/* ---- DeltaNet input projections ----------------------------------------- */-/* One fused qkv++z tensor per DeltaNet layer. Indexed by model layer index,- * so the array is n_layers wide and the attention slots stay empty. */-#define QT_DN_MAX_LAYERS 128-static struct { ColiCudaTensor *t; int dev, on; } G_dnp[QT_DN_MAX_LAYERS];++void qt_trunk_offer(const char *component, int layer, size_t bytes){+ if(!component || !bytes || G_offer_n >= QT_OFFER_MAX) return;+ if(layer < 0 || layer >= QT_DN_MAX_LAYERS) return;+ snprintf(G_offer[G_offer_n].name, sizeof G_offer[0].name, "%s", component);+ G_offer[G_offer_n].layer = layer; G_offer[G_offer_n].bytes = bytes;+ G_offer_n++;+}++static int auto_mode(void){+ const char *e = getenv("COLI_PLACE");+ return !e || !*e || !strcmp(e, "auto");+}++/* p_e of the k coldest experts that still fit on device index di, summed as+ * bytes-per-token they save; heat from the HEAT_FILE table when present. */+static int cmp_double_desc(const void *a, const void *b){+ double x=*(const double*)a, y=*(const double*)b; return x<y ? 1 : x>y ? -1 : 0;+}+static int auto_dnp_count(int dev){+ int c = 0; for(int l = 0; l < QT_DN_MAX_LAYERS; l++) if(G_auto_dnp[l] == dev) c++; return c;+}++static double auto_displaced_value(int di, size_t room, int k, size_t exp_bytes,+ int nl, int ne, int topk, const uint32_t *heat0,+ double *p_marginal_out){+ size_t homed = 0;+ for(int e = 0; e < ne; e++) if(e % G.ndev == di) homed++;+ homed *= (size_t)nl;+ size_t fit = room / exp_bytes;+ if(fit >= homed){ *p_marginal_out = 0; return 0; } /* room to spare: displaces nothing */+ if(k <= 0){ *p_marginal_out = 0; return 0; }+ double cpu_factor = (G.wfmt == 1) ? 1.0 : 2.0; /* CPU reads the int8 slot */+ if(!heat0){+ double p = (double)topk / ne;+ *p_marginal_out = p;+ return (double)k * cpu_factor * p * (double)exp_bytes;+ }+ /* heat share per expert on this device, sorted descending; the marginal+ * ones sit at ranks [fit-k, fit) */+ size_t n = homed; double *p = malloc(n * sizeof *p); size_t m = 0;+ for(int l = 0; l < nl; l++){+ double sum = 0;+ for(int e = 0; e < ne; e++) sum += (double)heat0[(size_t)l*ne + e];+ for(int e = 0; e < ne; e++){+ if(e % G.ndev != di) continue;+ double pe = sum > 0 ? (double)topk * heat0[(size_t)l*ne + e] / sum : (double)topk / ne;+ p[m++] = pe > 1.0 ? 1.0 : pe;+ }+ }+ qsort(p, m, sizeof *p, cmp_double_desc);+ double value = 0, pm = 0; int cnt = 0;+ for(size_t r = (fit > (size_t)k ? fit - k : 0); r < fit && r < m; r++){ value += cpu_factor * p[r] * (double)exp_bytes; pm = p[r]; cnt++; }+ free(p);+ *p_marginal_out = pm;+ return value;+}++static void auto_place(int nl, int ne, int topk, const size_t *capacity, const uint32_t *heat0){+ size_t room[QT_MAX_DEV];+ for(int i = 0; i < G.ndev; i++){ room[i] = capacity[i]; G_trunk_bytes[i] = 0; }+ for(int l = 0; l < QT_DN_MAX_LAYERS; l++) G_auto_dnp[l] = QT_PLACE_CPU;+ G_auto_lmh = QT_PLACE_CPU;+ int placed = 0, kept = 0;+ /* lmhead first (one call per token, latency-tolerant), then the+ * projections in layer order */+ for(int pass = 0; pass < 2; pass++)+ for(int o = 0; o < G_offer_n; o++){+ int is_lmh = !strcmp(G_offer[o].name, "lmhead");+ if((pass == 0) != is_lmh) continue;+ if(!is_lmh && strcmp(G_offer[o].name, "dnproj")) continue; /* v1: these two */+ size_t bytes = G_offer[o].bytes;+ int di = 0;+ for(int i = 1; i < G.ndev; i++) if(room[i] > room[di]) di = i;+ if(room[di] < bytes){ kept++; continue; }+ int k = (int)((bytes + G.exp_bytes - 1) / G.exp_bytes);+ double pm = 0;+ double lose = auto_displaced_value(di, room[di], k, G.exp_bytes, nl, ne, topk, heat0, &pm);+ if((double)bytes < lose){+ fprintf(stderr,"[place] auto: %s layer %d stays on CPU -- %.1f MB would displace %d experts "+ "worth %.1f MB/token on dev %d (p_marginal %.3f)\n",+ G_offer[o].name, G_offer[o].layer, bytes/1048576.0, k, lose/1048576.0, G.dev[di], pm);+ kept++; continue;+ }+ if(is_lmh) G_auto_lmh = G.dev[di]; else G_auto_dnp[G_offer[o].layer] = G.dev[di];+ room[di] -= bytes; G_trunk_bytes[di] += bytes; placed++;+ }+ G_auto_on = 1;+ for(int i = 0; i < G.ndev; i++)+ fprintf(stderr,"[place] auto: dev %d holds %.1f MB of trunk (lmhead%s, %d dnproj layers), %.2f GB left for experts\n",+ G.dev[i], G_trunk_bytes[i]/1048576.0, G_auto_lmh == G.dev[i] ? " yes" : " no",+ auto_dnp_count(G.dev[i]), room[i]/1073741824.0);+ (void)placed; (void)kept;+}int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,@@ -248,6 +384,11 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,if(topk>32){ fprintf(stderr,"[qtier] topk>32 unsupported\n"); return 0; }memset(&G,0,sizeof G);G.nl=nl; G.ne=ne; G.D=D; G.Ih=Ih; G.topk=topk;+ /* Placement state is re-derived per init: the device fold-in below reads+ * COLI_PLACE before the automatic placement has decided anything, and a+ * parse latched from an earlier init (tests start the tier many times)+ * would otherwise stand in for the current environment. */+ G_place_done = 0; G_place_n = 0; G_auto_on = 0;/* devices: COLI_GPUS="0,1" (default: first two visible devices) */const char *gl=getenv("COLI_GPUS");@@ -282,6 +423,60 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,if(have<G.ndev){ G.ndev=have; }if(G.ndev<1){ fprintf(stderr,"[qtier] no CUDA devices -> CPU path\n"); return 0; }+ /* Weight format and bytes per expert come first now: the automatic+ * placement below needs them to price the experts a trunk item displaces. */+ G.wfmt = expert_is_int4 ? 4 : 1;+ if(G.wfmt==1 && expert_gs>0){+ fprintf(stderr,"[qtier] int8 experts with grouped scales (gs=%d) cannot be "+ "expressed on the GPU (fmt=1 is per-row only) -> CPU path\n", expert_gs);+ return 0;+ }+ G.egs = expert_gs;+ G.sc_gu = expert_gs ? (size_t)Ih * ((D + expert_gs - 1)/expert_gs) : (size_t)Ih;+ G.sc_d = expert_gs ? (size_t)D * ((Ih + expert_gs - 1)/expert_gs) : (size_t)D;+ G.exp_bytes = (G.wfmt==1 ? 3ull*D*Ih : 3ull*D*Ih/2)+ + (2*G.sc_gu+G.sc_d)*sizeof(float) + 4096; /* + allocation slack */++ /* Per-device allowance for tier + trunk: CUDA_EXPERT_GB when numeric,+ * else free minus 1 GB headroom. The heat table is loaded here too (it+ * used to be loaded after the budgets) because the placer prices+ * experts by heat. */+ size_t capacity[QT_MAX_DEV]; int capdev[QT_MAX_DEV]; int ncap = G.ndev;+ const char *bg=getenv("CUDA_EXPERT_GB");+ for(int i=0;i<G.ndev;i++){+ size_t freeb=0,totb=0; coli_cuda_mem_info(G.dev[i],&freeb,&totb);+ capdev[i] = G.dev[i];+ capacity[i] = (bg && strcmp(bg,"auto") && atof(bg)>0)+ ? (size_t)(atof(bg)*1024.0*1024.0*1024.0)+ : (freeb>(1ull<<30) ? freeb-(1ull<<30) : 0);+ fprintf(stderr,"[qtier] dev %d: %.1f GB free, allowance %.1f GB\n",+ G.dev[i], freeb/1073741824.0, capacity[i]/1073741824.0);+ }+ G.slot=calloc((size_t)nl*ne,sizeof(QSlot));+ if(!G.slot) return 0;+ const char *hf=getenv("HEAT_FILE");+ if(hf){+ FILE *f=fopen(hf,"rb");+ if(f){+ uint32_t hdr[3]={0,0,0};+ if(fread(hdr,4,3,f)==3 && hdr[0]==0x51544831u && hdr[1]==(uint32_t)nl && hdr[2]==(uint32_t)ne){+ G.heat0=malloc((size_t)nl*ne*4);+ if(G.heat0 && fread(G.heat0,4,(size_t)nl*ne,f)==(size_t)nl*ne){+ for(size_t i=0;i<(size_t)nl*ne;i++) G.slot[i].heat=G.heat0[i]>>1; /* decay */+ fprintf(stderr,"[qtier] HEAT_FILE loaded: %s\n",hf);+ } else { free(G.heat0); G.heat0=NULL; }+ }+ fclose(f);+ }+ }+ if(auto_mode()){+ if(G_offer_n) auto_place(nl, ne, topk, capacity, G.heat0);+ else { G_auto_on = 1; G_auto_lmh = QT_PLACE_CPU; for(int l=0;l<QT_DN_MAX_LAYERS;l++) G_auto_dnp[l]=QT_PLACE_CPU; }+ } else {+ const char *e = getenv("COLI_PLACE");+ if(e && !strcmp(e, "off")){ G_auto_on = 1; G_auto_lmh = QT_PLACE_CPU; for(int l=0;l<QT_DN_MAX_LAYERS;l++) G_auto_dnp[l]=QT_PLACE_CPU; }+ }+/* R4 role split: the lm_head device (COLI_LMHEAD_GPU) is initialized above* but removed from the expert PLACEMENT list. Zeroing its budget instead* is not enough: home() still hashes experts onto it, and those can never@@ -323,10 +518,10 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,G.dev[0]=ed; G.ndev=1;fprintf(stderr,"[place] Experten auf Device %d festgelegt\n",ed);} else fprintf(stderr,"[place] experts=%d nicht verfuegbar -> COLI_GPUS bleibt\n",ed);- } else if(G_place_n && qt_place_named("experts")){+ } else if(!G_auto_on && G_place_n && qt_place_named("experts")){fprintf(stderr,"[place] experts=cpu -> VRAM-Tier aus\n");return 0;- } else if(nres){+ } else if(nres && !G_auto_on){int w=0;for(int i=0;i<G.ndev;i++){int res=0; for(int r=0;r<nres;r++) if(G.dev[i]==reserved[r]) res=1;@@ -341,61 +536,25 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,}}- /* per-device budget: CUDA_EXPERT_GB, or auto = free minus 1 GB headroom.- * Scale counts follow the container: per-row (expert_gs=0) or grouped- * (gs64: [O, ceil(I/gs)] per projection). */- G.wfmt = expert_is_int4 ? 4 : 1;- /* fmt=1 non ha scale raggruppate: backend_cuda le onora solo per fmt=4- * (want_gs = (fmt==4 && ...)). Un container int8 con scale a gruppi non e'- * esprimibile sulla GPU, e promuoverlo lo stesso darebbe numeri sbagliati:- * meglio restare su CPU dicendolo. Rifiutare qui, PRIMA di riservare- * qualunque budget, e' il punto giusto -- il difetto di #1331 era proprio- * riservare per poi non promuovere. */- if(G.wfmt==1 && expert_gs>0){- fprintf(stderr,"[qtier] int8 experts with grouped scales (gs=%d) cannot be "- "expressed on the GPU (fmt=1 is per-row only) -> CPU path\n", expert_gs);- return 0;- }- G.egs = expert_gs;- G.sc_gu = expert_gs ? (size_t)Ih * ((D + expert_gs - 1)/expert_gs) : (size_t)Ih;- G.sc_d = expert_gs ? (size_t)D * ((Ih + expert_gs - 1)/expert_gs) : (size_t)D;- /* int8 occupa il doppio dell'int4 impacchettato: il budget deve saperlo,- * se no si promettono il doppio degli esperti che ci stanno. */- G.exp_bytes = (G.wfmt==1 ? 3ull*D*Ih : 3ull*D*Ih/2)- + (2*G.sc_gu+G.sc_d)*sizeof(float) + 4096; /* + allocation slack */- const char *bg=getenv("CUDA_EXPERT_GB");+ /* Expert budget per device: the allowance minus the trunk that landed+ * there. The hand-written list gets the same subtraction now: with+ * COLI_PLACE="dnproj=0" the 0.7 GB of projections used to come out of the+ * expert cache unannounced (the R4 measurement). Devices may have been+ * dropped from the expert list by the role split above; match by ordinal. */for(int i=0;i<G.ndev;i++){- size_t freeb=0,totb=0; coli_cuda_mem_info(G.dev[i],&freeb,&totb);- size_t b = (bg && strcmp(bg,"auto") && atof(bg)>0)- ? (size_t)(atof(bg)*1024.0*1024.0*1024.0)- : (freeb>(1ull<<30) ? freeb-(1ull<<30) : 0);- G.budget[i]=b;- fprintf(stderr,"[qtier] dev %d: %.1f GB free, budget %.1f GB (~%zu experts)\n",- G.dev[i], freeb/1073741824.0, b/1073741824.0, b/G.exp_bytes);+ size_t trunk = 0;+ for(int o=0;o<G_offer_n;o++)+ if(qt_place_of(G_offer[o].name, G_offer[o].layer)==G.dev[i]) trunk += G_offer[o].bytes;+ size_t cap_i = 0;+ for(int j=0;j<ncap;j++) if(capdev[j]==G.dev[i]) cap_i = capacity[j];+ G.budget[i] = cap_i > trunk ? cap_i - trunk : 0;+ fprintf(stderr,"[qtier] dev %d: budget %.2f GB for experts (~%zu experts)%s\n",+ G.dev[i], G.budget[i]/1073741824.0, G.budget[i]/G.exp_bytes,+ trunk ? " after trunk" : "");}- G.slot=calloc((size_t)nl*ne,sizeof(QSlot));- /* qt_issue strides each device's block by 32*D floats (its max row- * count), not 8*D: a device other than 0 with a full 32-row issue used- * to run past its own slice and off the end of this allocation (#1339). */G.is_x_floats=(size_t)G.ndev*32*D;G.is_x=malloc(G.is_x_floats*sizeof(float));- if(!G.slot||!G.is_x) return 0;- /* load learned heat (HEAT_FILE): warmstart order + initial values */- const char *hf=getenv("HEAT_FILE");- if(hf){- FILE *f=fopen(hf,"rb");- if(f){- uint32_t hdr[3]={0,0,0};- if(fread(hdr,4,3,f)==3 && hdr[0]==0x51544831u && hdr[1]==(uint32_t)nl && hdr[2]==(uint32_t)ne){- G.heat0=malloc((size_t)nl*ne*4);- if(G.heat0 && fread(G.heat0,4,(size_t)nl*ne,f)==(size_t)nl*ne){- for(size_t i=0;i<(size_t)nl*ne;i++) G.slot[i].heat=G.heat0[i]>>1; /* decay */- fprintf(stderr,"[qtier] HEAT_FILE loaded: %s\n",hf);- } else { free(G.heat0); G.heat0=NULL; }- }- fclose(f);- }- }+ if(!G.is_x) return 0;pthread_mutex_init(&G.mx,NULL); pthread_cond_init(&G.cv,NULL); pthread_cond_init(&G.cv_take,NULL);if(pthread_create(&G.th,NULL,uploader,NULL)!=0) return 0;G.on=1;diff --git a/c/qwen36_tier.h b/c/qwen36_tier.hindex 65e8bffb..b71bb730 100644--- a/c/qwen36_tier.h+++ b/c/qwen36_tier.h@@ -57,6 +57,14 @@ int qt_lmhead_matmul(float *y, const float *x, int I, int O);* components like lmhead. */#define QT_PLACE_CPU (-1)int qt_place_of(const char *component, int layer);+/* Automatic placement (COLI_PLACE unset or "auto"; "off" disables). The+ * engine offers each trunk component with its byte size BEFORE qt_init --+ * "lmhead" once (layer 0), "dnproj" per DeltaNet layer -- and qt_init decides+ * by bytes saved per token per byte of VRAM, pricing displaced experts by+ * heat. The decision is what qt_place_of() then returns, and the placed+ * bytes come out of that device's expert budget. Sizes only; the tensors+ * follow through qt_lmhead_init / qt_dnproj_init as before. */+void qt_trunk_offer(const char *component, int layer, size_t bytes);/* DeltaNet input projections, qkv ++ z fused into one resident tensor per* layer: one GEMV instead of two, and the engine's qkv/z buffers are laid out@@ -108,6 +116,7 @@ static inline int qt_lmhead_init(const int8_t*a,const float*b,int c,int d){(voistatic inline int qt_lmhead_matmul(float*a,const float*b,int c,int d){(void)a;(void)b;(void)c;(void)d;return 0;}#define QT_PLACE_CPU (-1)static inline int qt_place_of(const char*a,int b){(void)a;(void)b;return QT_PLACE_CPU;}+static inline void qt_trunk_offer(const char*a,int b,size_t c){(void)a;(void)b;(void)c;}static inline int qt_dnproj_init(int a,const int8_t*b,const float*c,int d,int e,int f){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;return 0;}static inline int qt_dnproj_matmul(int a,float*b,const float*c,int d,int e){(void)a;(void)b;(void)c;(void)d;(void)e;return 0;}static inline int qt_ready(void){return 0;}diff --git a/c/tests/qwen36_fake_cuda.h b/c/tests/qwen36_fake_cuda.hindex 7a516f61..196ef53b 100644--- a/c/tests/qwen36_fake_cuda.h+++ b/c/tests/qwen36_fake_cuda.h@@ -42,6 +42,7 @@ static unsigned char captured[4096];static size_t captured_len;static int fake_ndev = 1;+static size_t fake_free_bytes = 2ull << 30; /* what coli_cuda_mem_info reports as free */static int (*fake_issue_hook)(int device, int count, const float *x) = NULL;static int upload_common(ColiCudaTensor **t, const void *w, int fmt,@@ -73,7 +74,7 @@ int coli_cuda_init(const int *d, int n) { (void)d; (void)n; return 1; }void coli_cuda_shutdown(void) {}int coli_cuda_mem_info(int device, size_t *freeb, size_t *total) {(void)device;- *freeb = 2ull << 30; *total = 4ull << 30; /* 2 GiB liberi */+ *freeb = fake_free_bytes; *total = 4ull << 30; /* 2 GiB liberi by default */return 1;}int coli_cuda_expert_group_issue(ColiCudaTensor *const *g, ColiCudaTensor *const *u,diff --git a/c/tests/test_qwen36_tier_autoplace.c b/c/tests/test_qwen36_tier_autoplace.cnew file mode 100644index 00000000..14731b19--- /dev/null+++ b/c/tests/test_qwen36_tier_autoplace.c@@ -0,0 +1,186 @@+/* Automatic placement of the dense trunk (COLI_PLACE unset or "auto").+ *+ * The rule under test, stated once: a trunk component goes into VRAM when the+ * bytes it saves on the memory bus per token beat the bytes the experts it+ * displaces would have saved -- dense weights are read every token, an expert+ * with the probability a token routes to it, and the CPU reads an int4 expert+ * as an int8 slot (twice the VRAM bytes). Everything else here is that rule+ * applied: no heat means the trunk wins, hot marginal experts mean it loses,+ * an explicit list is obeyed, "off" places nothing, and whatever lands in+ * VRAM comes out of that device's expert budget, on one card and on two.+ *+ * Fake backend, no GPU: free VRAM is whatever the test says it is. */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#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 { D = 64, IH = 32 };+#define MiB (1024ull * 1024ull)++/* every case starts from a clean tier: no offers, no auto decision, env set */+static void fresh(const char *place, const char *gpus, int ndev, const char *budget_gb) {+ G_offer_n = 0; G_auto_on = 0;+ setenv("COLI_CUDA", "1", 1);+ setenv("COLI_GPUS", gpus, 1);+ setenv("QT_NO_WARMSTART", "1", 1);+ setenv("COLI_PLACE", place, 1); /* "" == unset == auto */+ setenv("CUDA_EXPERT_GB", budget_gb, 1); /* the per-device allowance */+ setenv("HEAT_FILE", "", 1);+ fake_ndev = ndev;+}++static int start(int nl, int ne, int topk) {+ return qt_init(nl, ne, D, IH, ne, topk, 0 /* per-row */, 1 /* int4 */);+}++/* HEAT_FILE with every expert at the same heat: p_e = topk / n_experts */+static const char *write_uniform_heat(int nl, int ne) {+ static char path[256];+ snprintf(path, sizeof path, "qwen36_autoplace_heat_%d_%d.bin", nl, ne);+ FILE *f = fopen(path, "wb");+ uint32_t hdr[3] = { 0x51544831u, (uint32_t)nl, (uint32_t)ne };+ fwrite(hdr, 4, 3, f);+ for (int i = 0; i < nl * ne; i++) { uint32_t h = 1000; fwrite(&h, 4, 1, f); }+ fclose(f);+ return path;+}++int main(void) {+ printf("qwen36 tier automatic placement\n");++ /* ---- 1. auto, one device: everything offered fits, budget shrinks by it ---- */+ printf(" 1. auto, one device, trunk fits\n");+ fresh("", "0", 1, "0.0625"); /* 64 MiB allowance */+ qt_trunk_offer("lmhead", 0, 10 * MiB);+ for (int l = 0; l < 8; l++) if (l % 4 != 3) qt_trunk_offer("dnproj", l, 2 * MiB);+ check(start(8, 16, 4), "tier starts in auto mode");+ check(qt_place_of("lmhead", 0) == 0, "lmhead lands on device 0");+ check(qt_place_of("dnproj", 0) == 0 && qt_place_of("dnproj", 6) == 0, "offered dnproj layers land on device 0");+ check(qt_place_of("dnproj", 3) == QT_PLACE_CPU, "an attention layer (never offered) stays on the CPU");+ check(qt_place_of("attnproj", 0) == QT_PLACE_CPU, "components not yet placed by auto stay on the CPU");+ check(G.ndev == 1 && G.on, "one card keeps experts and trunk together (no role-split reservation in auto)");+ check(G.budget[0] == 64 * MiB - 22 * MiB, "expert budget = allowance minus the 22 MiB of trunk placed");+ check(G_lmh.dev_ok && G_lmh.dev == 0, "lm_head device is armed for qt_lmhead_init");+ qt_shutdown();++ /* ---- 2. auto: a trunk item larger than the allowance stays on the CPU ---- */+ printf(" 2. auto, trunk does not fit\n");+ fresh("", "0", 1, "0.0625");+ qt_trunk_offer("lmhead", 0, 100 * MiB);+ qt_trunk_offer("dnproj", 0, 2 * MiB);+ check(start(8, 16, 4), "tier starts");+ check(qt_place_of("lmhead", 0) == QT_PLACE_CPU, "100 MiB lmhead cannot fit 64 MiB: CPU");+ check(qt_place_of("dnproj", 0) == 0, "the 2 MiB projection still fits and is placed");+ check(G.budget[0] == 64 * MiB - 2 * MiB, "budget shrinks only by what was placed");+ qt_shutdown();++ /* ---- 3. heat decides: hot marginal experts keep their VRAM ---- */+ printf(" 3. heat: hot marginal experts beat the trunk, cold ones do not\n");+ {+ /* nl=1, ne=48. Allowance for exactly 16 experts, so 32 of 48 do not fit+ * and the trunk would displace real residents. Offer one expert-sized+ * projection (k=1). Uniform heat -> p_e = topk/48. */+ enum { NL = 1, NE = 48 };+ const char *heat = write_uniform_heat(NL, NE);+ char gb[64];+ /* exp_bytes for D=64, IH=32, per-row int4: 3072 + 512 + 4096 = 7680 */+ size_t exp_bytes = 3ull * D * IH / 2 + (2 * IH + D) * sizeof(float) + 4096;+ snprintf(gb, sizeof gb, "%.15f", (double)(16 * exp_bytes + exp_bytes / 2) / 1073741824.0);+ /* the allowance as the tier will parse it back from the string */+ size_t allowance = (size_t)(atof(gb) * 1024.0 * 1024.0 * 1024.0);++ /* topk 32: p = 0.667, CPU factor 2 -> 1.33 bytes/token per VRAM byte > 1.0: trunk loses */+ fresh("", "0", 1, gb); setenv("HEAT_FILE", heat, 1);+ qt_trunk_offer("dnproj", 0, exp_bytes);+ check(start(NL, NE, 32), "tier starts with a heat file");+ check(G.heat0 != NULL, "heat table loaded");+ check(qt_place_of("dnproj", 0) == QT_PLACE_CPU,+ "with p_marginal 0.67 the displaced expert is worth 1.33 bytes/token per byte: trunk stays on CPU");+ check(G.budget[0] == allowance, "nothing placed, budget untouched");+ qt_shutdown();++ /* topk 8: p = 0.167 -> 0.33 < 1.0: trunk wins */+ fresh("", "0", 1, gb); setenv("HEAT_FILE", heat, 1);+ qt_trunk_offer("dnproj", 0, exp_bytes);+ check(start(NL, NE, 8), "tier starts");+ check(qt_place_of("dnproj", 0) == 0, "with p_marginal 0.17 the trunk item is worth more: placed");+ check(G.budget[0] == allowance - exp_bytes, "budget shrinks by the placed item");+ qt_shutdown();++ /* no heat, topk 32: uniform assumption p = 32/48 as well -- same answer as with the file */+ fresh("", "0", 1, gb);+ qt_trunk_offer("dnproj", 0, exp_bytes);+ check(start(NL, NE, 32), "tier starts without heat");+ check(qt_place_of("dnproj", 0) == QT_PLACE_CPU, "without a heat file the uniform estimate gives the same verdict");+ qt_shutdown();++ /* room to spare: allowance for 100 experts, only 48 exist -> displaces nothing, always placed */+ snprintf(gb, sizeof gb, "%.15f", (double)(100 * exp_bytes) / 1073741824.0);+ fresh("", "0", 1, gb); setenv("HEAT_FILE", heat, 1);+ qt_trunk_offer("dnproj", 0, exp_bytes);+ check(start(NL, NE, 32), "tier starts");+ check(qt_place_of("dnproj", 0) == 0, "VRAM nobody would use goes to the trunk regardless of heat");+ qt_shutdown();+ remove(heat);+ }++ /* ---- 4. an explicit list wins over auto, and still pays for its trunk ---- */+ printf(" 4. explicit COLI_PLACE\n");+ fresh("lmhead=cpu,dnproj=0", "0", 1, "0.0625");+ qt_trunk_offer("lmhead", 0, 10 * MiB);+ for (int l = 0; l < 8; l++) if (l % 4 != 3) qt_trunk_offer("dnproj", l, 2 * MiB);+ check(start(8, 16, 4), "tier starts with an explicit list");+ check(!G_auto_on, "auto is off when a list is given");+ check(qt_place_of("lmhead", 0) == QT_PLACE_CPU, "lmhead=cpu is obeyed even though it would fit");+ check(qt_place_of("dnproj", 2) == 0, "dnproj=0 is obeyed");+ check(G.budget[0] == 64 * MiB - 12 * MiB, "the explicit list's 12 MiB of projections come out of the expert budget too");+ qt_shutdown();++ /* ---- 5. off: nothing placed, full budget ---- */+ printf(" 5. COLI_PLACE=off\n");+ fresh("off", "0", 1, "0.0625");+ qt_trunk_offer("lmhead", 0, 10 * MiB);+ qt_trunk_offer("dnproj", 0, 2 * MiB);+ check(start(8, 16, 4), "tier starts with placement off");+ check(qt_place_of("lmhead", 0) == QT_PLACE_CPU && qt_place_of("dnproj", 0) == QT_PLACE_CPU, "off places nothing");+ check(G.budget[0] == 64 * MiB, "off leaves the whole allowance to the experts");+ qt_shutdown();++ /* ---- 6. auto, two devices: greedy by room, both keep experts ---- */+ printf(" 6. auto, two devices\n");+ fresh("", "0,1", 2, "0.0625");+ qt_trunk_offer("lmhead", 0, 10 * MiB);+ for (int l = 0; l < 8; l++) if (l % 4 != 3) qt_trunk_offer("dnproj", l, 9 * MiB);+ check(start(8, 16, 4), "tier starts on two fake devices");+ check(G.ndev == 2, "auto keeps experts on both devices");+ check(qt_place_of("lmhead", 0) == 0, "lmhead goes to the first device (both equal, first wins)");+ /* greedy by most room, 9 MiB each, after lmhead dev0=54 dev1=64:+ l0 -> dev1 (55), l1 -> dev1 (46), l2 -> dev0 (45), l4 -> dev1 (37),+ l5 -> dev0 (36), l6 -> dev1 (27): dev0 holds lmhead+2 = 28 MiB, dev1 4 = 36 MiB */+ check(qt_place_of("dnproj", 0) == 1 && qt_place_of("dnproj", 1) == 1 && qt_place_of("dnproj", 2) == 0 &&+ qt_place_of("dnproj", 4) == 1 && qt_place_of("dnproj", 5) == 0 && qt_place_of("dnproj", 6) == 1,+ "projections go to whichever device has the most room left");+ check(G.budget[0] == 64 * MiB - 28 * MiB && G.budget[1] == 64 * MiB - 36 * MiB,+ "each device's expert budget is its allowance minus its own trunk");+ qt_shutdown();++ /* ---- 7. nothing offered: auto is a no-op, budgets are the allowance ---- */+ printf(" 7. auto with nothing offered\n");+ fresh("", "0", 1, "0.0625");+ check(start(8, 16, 4), "tier starts");+ check(qt_place_of("lmhead", 0) == QT_PLACE_CPU && G.budget[0] == 64 * MiB, "no offers: nothing placed, full budget");+ qt_shutdown();++ if (fails) { printf("test_qwen36_tier_autoplace: %d failure(s)\n", fails); return 1; }+ printf("test_qwen36_tier_autoplace: ok\n");+ return 0;+}