Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
R4 Schritt 2: DeltaNet-Projektionen auf GPU, Platzierung konfigurierbar
kreuzzelg85c90c4aded3
diff --git a/c/qwen36.c b/c/qwen36.cindex 04eedf18..e66c3e1d 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -2032,8 +2032,12 @@ static void deltanet(Model *m, Layer *l, int layer, float *x, int S, int pos_basfloat scale = 1.f / sqrtf((float)kdim);int H = c->hidden;- float *qkv = falloc(conv_dim);- float *z = falloc(value_dim);+ /* qkv and z live in ONE buffer: the fused GPU projection writes+ * [conv_dim ++ value_dim] in a single GEMV, and the CPU fallback fills the+ * same two regions. Either way the code below reads qkv/z unchanged. */+ float *qkvz = falloc((int64_t)conv_dim + value_dim);+ float *qkv = qkvz;+ float *z = qkvz + conv_dim;float *b = falloc(vh);float *a = falloc(vh);float *beta= falloc(vh);@@ -2053,9 +2057,12 @@ static void deltanet(Model *m, Layer *l, int layer, float *x, int S, int pos_basconst float *xs = x + (int64_t)s * H;extern double g_dn_sub[4];double _d0 = tm_on()? tm_now():0;- /* projections (single-token matmuls) */- matmul_d(qkv, xs, l->dn_qkv, 1, H, conv_dim);- matmul_d(z, xs, l->dn_z, 1, H, value_dim);+ /* projections (single-token matmuls). One fused GEMV when this layer's+ * dnproj is placed on a GPU, the two CPU matmuls otherwise. */+ if (!qt_dnproj_matmul(layer, qkvz, xs, H, conv_dim + value_dim)) {+ matmul_d(qkv, xs, l->dn_qkv, 1, H, conv_dim);+ matmul_d(z, xs, l->dn_z, 1, H, value_dim);+ }matmul(b, xs, l->dn_b, 1, H, vh);matmul(a, xs, l->dn_a, 1, H, vh);if (tm_on() && S==1){ double t=tm_now(); g_dn_sub[0]+=t-_d0; _d0=t; }@@ -2171,7 +2178,8 @@ static void deltanet(Model *m, Layer *l, int layer, float *x, int S, int pos_bas}}}- free(qkv); free(z); free(b); free(a); free(beta); free(gg);+ free(qkvz); /* qkv and z are regions of this one allocation */+ free(b); free(a); free(beta); free(gg);free(conv_out); free(q); free(k); free(outv); free(outr); free(kv); free(delta);}@@ -2863,6 +2871,41 @@ int main(int argc, char **argv) {qt_lmhead_init(g_qdw[i].q, g_qdw[i].sc, g_qdw[i].I, g_qdw[i].O);break;}+ /* R4 step 2: DeltaNet input projections, per layer, wherever+ * COLI_PLACE puts them. qkv and z are both [O_x, hidden] int8 with+ * per-row scales, so fusing them is a concatenation along O -- two+ * memcpys, no requantization, and the GPU sees one GEMV per layer+ * instead of two. The host copy is freed right after the upload. */+ {+ int placed = 0, O_qkv = m.c.dn_conv_dim, O_z = m.c.dn_vheads * m.c.dn_vdim;+ int Of = O_qkv + O_z, Hd = m.c.hidden;+ double vram = 0;+ for (int i = 0; i < m.c.n_layers; i++) {+ if (m.c.is_attn[i]) continue;+ int dev = qt_place_of("dnproj", i);+ if (dev == QT_PLACE_CPU) continue;+ const int8_t *q1 = NULL, *q2 = NULL; const float *s1 = NULL, *s2 = NULL;+ for (int j = 0; j < g_qdw_n; j++) {+ if (g_qdw[j].w == m.L[i].dn_qkv) { q1 = g_qdw[j].q; s1 = g_qdw[j].sc; }+ if (g_qdw[j].w == m.L[i].dn_z) { q2 = g_qdw[j].q; s2 = g_qdw[j].sc; }+ }+ if (!q1 || !q2) continue; /* dense-i8 off: CPU path stands */+ int8_t *qf = malloc((size_t)Of * Hd);+ float *sf = malloc((size_t)Of * sizeof(float));+ if (!qf || !sf) { free(qf); free(sf); break; }+ memcpy(qf, q1, (size_t)O_qkv * Hd);+ memcpy(qf + (size_t)O_qkv * Hd, q2, (size_t)O_z * Hd);+ memcpy(sf, s1, (size_t)O_qkv * sizeof(float));+ memcpy(sf + O_qkv, s2, (size_t)O_z * sizeof(float));+ if (qt_dnproj_init(i, qf, sf, Hd, Of, dev)) {+ placed++; vram += (double)Of * Hd;+ }+ free(qf); free(sf);+ }+ if (placed)+ fprintf(stderr, "[dnp] %d DeltaNet-Projektionen auf GPU (%.2f GB VRAM)\n",+ placed, vram / 1073741824.0);+ }/* Warmstart: fill the VRAM budget BEFORE the first token (heat order* when HEAT_FILE exists, natural order otherwise), loading all RAM* slots along the way. */diff --git a/c/qwen36_tier.c b/c/qwen36_tier.cindex 810f474f..d6724c95 100644--- a/c/qwen36_tier.c+++ b/c/qwen36_tier.c@@ -152,6 +152,90 @@ static void *uploader(void *arg){* so CPU and GPU compute the same numbers up to accumulation order. */static struct { ColiCudaTensor *t; int dev, dev_ok, on; } G_lmh;+/* ---- placement table (COLI_PLACE) --------------------------------------- */+/* Parsed lazily on first query and cached: qt_place_of runs per layer during+ * init and must not re-parse the environment 30 times. */+#define QT_PLACE_MAX 8+#define QT_SPLIT_MAX 8+static struct {+ char name[16];+ struct { int dev, count; } seg[QT_SPLIT_MAX]; /* count<=0: all remaining */+ int nseg;+} G_place[QT_PLACE_MAX];+static int G_place_n = 0, G_place_done = 0;++/* one component spec: "cpu" | "<dev>" | "<dev>:<n>+<dev>:<n>..." */+static void place_add(const char *name, size_t nlen, const char *spec){+ if(G_place_n >= QT_PLACE_MAX) return;+ if(nlen >= sizeof(G_place[0].name)) nlen = sizeof(G_place[0].name)-1;+ memcpy(G_place[G_place_n].name, name, nlen);+ G_place[G_place_n].name[nlen] = 0;+ int ns = 0;+ for(const char *p = spec; *p && ns < QT_SPLIT_MAX; ){+ while(*p==' ') p++;+ int dev, count = -1;+ if(!strncmp(p,"cpu",3)){ dev = QT_PLACE_CPU; p += 3; }+ else { dev = atoi(p); while(*p && *p!=':' && *p!='+') p++; }+ if(*p==':'){ count = atoi(p+1); p++; while(*p && *p!='+') p++; }+ G_place[G_place_n].seg[ns].dev = dev;+ G_place[G_place_n].seg[ns].count = count;+ ns++;+ if(*p=='+') p++; else break;+ }+ G_place[G_place_n].nseg = ns;+ G_place_n++;+}++static void place_parse(void){+ G_place_done = 1;+ const char *e = getenv("COLI_PLACE");+ if(!e || !*e) return;+ const char *p = e;+ while(*p){+ while(*p==' '||*p==','||*p==';') p++;+ const char *name = p;+ while(*p && *p!='=' && *p!=',' && *p!=';') p++;+ if(*p!='='){ while(*p && *p!=','&&*p!=';') p++; continue; }+ size_t nlen = (size_t)(p - name);+ p++; /* past '=' */+ char spec[64]; size_t si = 0;+ while(*p && *p!=',' && *p!=';' && si < sizeof(spec)-1) spec[si++] = *p++;+ spec[si] = 0;+ place_add(name, nlen, spec);+ }+ fprintf(stderr,"[place] COLI_PLACE=%s\n", e);+}++/* Was this component named at all? Distinguishes "experts=cpu" (an explicit+ * request to disable the tier) from "not mentioned" (keep today's default). */+static int qt_place_named(const char *component){+ if(!G_place_done) place_parse();+ for(int i=0;i<G_place_n;i++) if(!strcmp(G_place[i].name,component)) return 1;+ return 0;+}++int qt_place_of(const char *component, int layer){+ if(!G_place_done) place_parse();+ for(int i = 0; i < G_place_n; i++){+ if(strcmp(G_place[i].name, component)) continue;+ int seen = 0;+ for(int s = 0; s < G_place[i].nseg; s++){+ int cnt = G_place[i].seg[s].count;+ if(cnt <= 0) return G_place[i].seg[s].dev; /* rest of the layers */+ if(layer < seen + cnt) return G_place[i].seg[s].dev;+ seen += cnt;+ }+ return QT_PLACE_CPU; /* past the last segment: stay on CPU */+ }+ 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];+int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,int expert_is_int4){@@ -177,6 +261,21 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,for(int i=0;i<want && i<QT_MAX_DEV;i++) G.dev[G.ndev++]=i;fprintf(stderr,"[qtier] COLI_GPUS unset: selecting %d visible device(s)\n",G.ndev);}+ /* A device named only in COLI_PLACE still needs a CUDA context before+ * anything can be uploaded to it. Fold those in here rather than making+ * the caller repeat every device in COLI_GPUS as well -- forgetting that+ * would silently drop a component back to the CPU mid-A/B. */+ {+ static const char *comps[] = {"lmhead","dnproj","dnout","attnproj"};+ for(size_t ci=0; ci<sizeof comps/sizeof *comps; ci++)+ for(int l=0; l<nl && G.ndev<QT_MAX_DEV; l++){+ int d=qt_place_of(comps[ci],l);+ if(d==QT_PLACE_CPU) continue;+ int seen=0; for(int i=0;i<G.ndev;i++) if(G.dev[i]==d) seen=1;+ if(!seen){ G.dev[G.ndev++]=d;+ fprintf(stderr,"[place] dev %d aus COLI_PLACE zur CUDA-Init ergaenzt\n",d); }+ }+ }if(G.ndev<1){ fprintf(stderr,"[qtier] no visible CUDA devices -> CPU path\n"); return 0; }if(!coli_cuda_init(G.dev,G.ndev)){ fprintf(stderr,"[qtier] coli_cuda_init failed -> CPU path\n"); return 0; }int have=coli_cuda_device_count();@@ -192,20 +291,53 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,* while lm_head is one latency-tolerant call per token. If it is the ONLY* device, experts stay on it β a role split needs two cards. */{+ int reserved[QT_MAX_DEV], nres=0;+ /* lm_head: COLI_LMHEAD_GPU stays honoured, COLI_PLACE wins when both+ * are set (it is the newer, general form). */const char *lhx=getenv("COLI_LMHEAD_GPU");- if(lhx && *lhx){- int ld=atoi(lhx), w=0, present=0;- for(int i=0;i<G.ndev;i++){ if(G.dev[i]==ld) present=1; else G.dev[w++]=G.dev[i]; }+ int ld=qt_place_of("lmhead",0);+ if(ld==QT_PLACE_CPU && lhx && *lhx) ld=atoi(lhx);+ if(ld!=QT_PLACE_CPU){+ int present=0; for(int i=0;i<G.ndev;i++) if(G.dev[i]==ld) present=1;+ if(present){ G_lmh.dev=ld; G_lmh.dev_ok=1; reserved[nres++]=ld; }+ else fprintf(stderr,"[qtier] lm_head-Device %d nicht verfuegbar -> CPU\n",ld);+ }+ /* every other component's devices, deduplicated */+ static const char *comps[] = {"dnproj","dnout","attnproj"};+ for(size_t ci=0; ci<sizeof comps/sizeof *comps; ci++)+ for(int l=0; l<nl; l++){+ int d=qt_place_of(comps[ci],l);+ if(d==QT_PLACE_CPU) continue;+ int seen=0; for(int r=0;r<nres;r++) if(reserved[r]==d) seen=1;+ if(!seen && nres<QT_MAX_DEV) reserved[nres++]=d;+ }+ /* experts=<dev> pins the tier to one card, experts=cpu turns it off.+ * Explicit beats inference: with BOTH cards reserved for other+ * components, the fallback below would hand the experts back to both+ * -- including the slow card, whose take() paces every layer (the+ * measured reason asymmetric expert placement lost). */+ int ed=qt_place_of("experts",0);+ if(ed!=QT_PLACE_CPU){+ int present=0; for(int i=0;i<G.ndev;i++) if(G.dev[i]==ed) present=1;if(present){- /* remember: the device HAS a CUDA context even after it leaves- * the placement list β qt_lmhead_init keys on this, not on the- * compacted list */- G_lmh.dev=ld; G_lmh.dev_ok=1;- if(w>0){- G.ndev=w;- fprintf(stderr,"[qtier] dev %d reserved for lm_head: excluded from expert placement\n",ld);- } /* w==0: lm_head device is the only one β experts stay on it */- } else fprintf(stderr,"[qtier] COLI_LMHEAD_GPU=%d not in COLI_GPUS -> lm_head stays on CPU\n",ld);+ 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")){+ fprintf(stderr,"[place] experts=cpu -> VRAM-Tier aus\n");+ return 0;+ } else if(nres){+ 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;+ if(!res) G.dev[w++]=G.dev[i];+ }+ /* w==0: the reserved devices are the only ones -- experts stay on+ * them, exactly as the single-card lm_head case did. */+ if(w>0 && w<G.ndev){+ G.ndev=w;+ fprintf(stderr,"[qtier] %d Device(s) reserviert: aus der Experten-Platzierung genommen\n",nres);+ }}}@@ -287,6 +419,29 @@ int qt_lmhead_init(const int8_t *q, const float *sc, int I, int O){return 1;}+int qt_dnproj_init(int layer, const int8_t *q, const float *sc,+ int I, int O, int device){+ if(layer < 0 || layer >= QT_DN_MAX_LAYERS) return 0;+ if(device == QT_PLACE_CPU || !q || !sc) return 0;+ /* No G.on requirement: the projections are independent of the expert tier,+ * so they can be measured on a card that holds no experts at all. */+ if(!coli_cuda_tensor_upload(&G_dnp[layer].t, q, sc, 1, I, O, device)){+ fprintf(stderr,"[dnp] layer %d upload failed -> stays on CPU\n", layer);+ return 0;+ }+ G_dnp[layer].dev = device; G_dnp[layer].on = 1;+ return 1;+}++int qt_dnproj_matmul(int layer, float *y, const float *x, int I, int O){+ if(layer < 0 || layer >= QT_DN_MAX_LAYERS || !G_dnp[layer].on) return 0;+ if(coli_cuda_matmul(&G_dnp[layer].t,y,x,NULL,NULL,1,1,I,O,G_dnp[layer].dev,0))+ return 1;+ fprintf(stderr,"[dnp] layer %d GPU matmul failed; CPU from here on\n", layer);+ G_dnp[layer].on = 0;+ return 0;+}+int qt_lmhead_matmul(float *y, const float *x, int I, int O){if(!G_lmh.on) return 0;/* cached-tensor path: upload params are ignored once *t exists */diff --git a/c/qwen36_tier.h b/c/qwen36_tier.hindex b573147a..65e8bffb 100644--- a/c/qwen36_tier.h+++ b/c/qwen36_tier.h@@ -36,6 +36,35 @@int qt_lmhead_init(const int8_t *q, const float *sc, int I, int O);int qt_lmhead_matmul(float *y, const float *x, int I, int O);+/* ---- placement table (R4) ------------------------------------------------+ * Every movable piece of the forward pass can be pinned to the CPU or to a+ * specific CUDA device, so configurations can be A/B'd instead of argued+ * about. One variable, not one per component:+ *+ * COLI_PLACE="experts=0,lmhead=0,dnproj=1,dnout=1,attnproj=cpu"+ *+ * Target is `cpu` or a CUDA ordinal. A component may also be split across+ * cards by layer count, joined with '+' so it cannot be confused with the+ * component separator:+ *+ * COLI_PLACE="dnproj=0:15+1:15" first 15 DeltaNet layers on dev 0, rest on 1+ *+ * Unnamed components keep their default (CPU; experts keep following+ * COLI_GPUS). Splitting matters because the DeltaNet projections hang+ * serially in the layer chain anyway -- a slower card delays only its own+ * layers, never the whole stream, which is what sank asymmetric EXPERT+ * placement. `layer` is the model layer index; pass 0 for whole-model+ * components like lmhead. */+#define QT_PLACE_CPU (-1)+int qt_place_of(const char *component, int layer);++/* 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+ * contiguously so the result needs no split copy. */+int qt_dnproj_init(int layer, const int8_t *q, const float *sc,+ int I, int O, int device);+int qt_dnproj_matmul(int layer, float *y, const float *x, int I, int O);+int qt_init(int n_layers, int n_experts, int hidden, int inter,int cap_experts_per_layer, int topk, int expert_gs,int expert_is_int4);@@ -77,6 +106,10 @@ void qt_stats(void);static inline int qt_init(int a,int b,int c,int d,int e,int f,int g,int h){(void)h;(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;return 0;}static inline int qt_lmhead_init(const int8_t*a,const float*b,int c,int d){(void)a;(void)b;(void)c;(void)d;return 0;}static 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 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;}static inline int qt_is_resident(int a,int b){(void)a;(void)b;return 0;}static inline void qt_shutdown(void){}diff --git a/c/tests/qwen36_fake_cuda.h b/c/tests/qwen36_fake_cuda.hindex 525b6904..7a516f61 100644--- a/c/tests/qwen36_fake_cuda.h+++ b/c/tests/qwen36_fake_cuda.h@@ -93,4 +93,13 @@ void coli_cuda_stats(int device, size_t *count, size_t *bytes) {(void)device; if (count) *count = 0; if (bytes) *bytes = 0;}+/* dense GEMV on a resident tensor (lm_head / DeltaNet projections placed on a+ * device). Counted, never computed: the placement tests check WHERE work+ * went; the arithmetic has its own oracle in the CUDA build. Parameters are+ * 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;+}+#endif /* QWEN36_FAKE_CUDA_H */