Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fix(qwen36): the VRAM tier now promotes int8 experts instead of reserving for nothing (#1334)

Vincenzo Fornaro002bbc9462aa
diff --git a/c/Makefile b/c/Makefile
index 141b4260..5b7a3d62 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1637,6 +1637,13 @@ tests/test_route_trace$(EXE): tests/test_route_trace.c route_trace.h
tests/test_cli_args$(EXE): tests/test_cli_args.c cli_args.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+# Il tier CUDA con un backend finto: gira SENZA GPU perche' il test definisce i
+# coli_cuda_* e registra cosa riceve. E' il solo modo di provare in CI che un
+# esperto arriva davvero in VRAM e nel formato giusto (#1331) -- un test che si
+# fermasse a "qt_init ritorna 1" sarebbe passato anche col difetto.
+tests/test_qwen36_tier_int8$(EXE): tests/test_qwen36_tier_int8.c qwen36_tier.c qwen36_tier.h backend_cuda.h
+ $(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)
+
tests/test_798_guards$(EXE): tests/test_798_guards.c st.h json.h compat.h route_trace.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
diff --git a/c/qwen36.c b/c/qwen36.c
index 6ee29bf2..27596ad2 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -2721,7 +2721,23 @@ int main(int argc, char **argv) {
/* Optional CUDA VRAM expert tier (COLI_CUDA=1): hot experts live in
* DEVICE_LOCAL memory across the configured GPUs, misses fall back to the
* CPU int8 path. See qwen36_tier.h. */
- 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)) {
+ /* Formato degli esperti dalla TAGLIA SU DISCO del primo, non da meta.ebits:
+ * esiste un container i8 il cui meta dichiara ebits=4 (stesso motivo per cui
+ * il loader piu' sopra guarda nbytes). Il tier ne ha bisogno prima di
+ * riservare qualunque budget: e' int4 impacchettato che va in VRAM come
+ * fmt=4, int8 come fmt=1. Sbagliare qui era #1331 -- budget riservato,
+ * planned=1, e zero promozioni per tutta la vita del processo. */
+ int expert_is_int4 = 1;
+ {
+ char probe[256];
+ snprintf(probe, sizeof(probe),
+ "model.layers.%d.mlp.experts.0.merged_weight", m.active_of[0]);
+ st_tensor *pt = st_find(&m.S, probe);
+ 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 */
+ }
+ 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");
atexit(qt_shutdown);
/* Warmstart: fill the VRAM budget BEFORE the first token (heat order
@@ -2748,8 +2764,15 @@ int main(int argc, char **argv) {
for (int gi = 0; gi < cap_total; gi++) {
int l = gi / m.c.n_experts, eidw = gi % m.c.n_experts;
Slot *e; expert_get(&m, l, eidw, &e);
- if (planned[gi] && e->g4) {
- qt_note_planned(l, eidw, e->g4, e->u4, e->d4, e->gs, e->us, e->ds);
+ /* int4: i puntatori impacchettati; int8: i pesi stessi. Prima
+ * qui si esigeva e->g4, che su un container int8 e' NULL: la
+ * promozione non partiva mai e il budget restava riservato a
+ * vuoto (#1331). */
+ const uint8_t *wg = expert_is_int4 ? e->g4 : (const uint8_t *)e->g;
+ const uint8_t *wu = expert_is_int4 ? e->u4 : (const uint8_t *)e->u;
+ const uint8_t *wd = expert_is_int4 ? e->d4 : (const uint8_t *)e->d;
+ if (planned[gi] && wg) {
+ qt_note_planned(l, eidw, wg, wu, wd, e->gs, e->us, e->ds);
/* The staging copy is done; free the int8 copy RIGHT AWAY
* so it never shows up in peak RSS. On LFRU eviction
* slot_ensure_int8() rematerializes from g4 (no container
diff --git a/c/qwen36_tier.c b/c/qwen36_tier.c
index 89d60c46..9d8e8daa 100644
--- a/c/qwen36_tier.c
+++ b/c/qwen36_tier.c
@@ -23,6 +23,13 @@ typedef struct {
static struct {
int on, nl, ne, D, Ih, topk, ndev;
int egs; size_t sc_gu, sc_d; /* expert group size + per-matrix scale counts (gs64) */
+ /* Formato dei pesi che il tier spedisce in VRAM: 4 = int4 raggruppato
+ * (container gs64), 1 = int8 per-riga. Prima era cablato a 4 in ogni punto,
+ * e su un container int8 -- dove s->g4 e' NULL perche' non c'e' nulla da
+ * impacchettare -- il tier riservava budget, marcava planned=1 e non
+ * promuoveva mai niente, senza dire una parola (#1331). backend_cuda sa
+ * gia' leggere fmt=1: mancava solo che glielo offrissimo. */
+ int wfmt;
int dev[QT_MAX_DEV];
size_t budget[QT_MAX_DEV], used[QT_MAX_DEV];
size_t exp_bytes; /* estimated VRAM bytes per expert */
@@ -56,11 +63,20 @@ static int home(int eid){ return eid % G.ndev; }
static void stage(uint8_t *dw, float *dsc,
const uint8_t *g4,const uint8_t *u4,const uint8_t *d4,
const float *gs,const float *us,const float *ds){
- size_t mb = (size_t)G.D*G.Ih/2;
+ size_t mb = (size_t)G.D*G.Ih/(G.wfmt==1?1:2);
+ if(G.wfmt==1){
+ /* int8: il formato del backend e' gia' quello in RAM, si copia e basta.
+ * Niente XOR: quello serve a portare i nibble int4 da complemento a due
+ * a binario sfalsato, e su byte interi sarebbe corruzione. */
+ memcpy(dw, g4, mb);
+ memcpy(dw+mb, u4, mb);
+ memcpy(dw+2*mb, d4, mb);
+ } else {
const uint64_t X=0x8888888888888888ull;
const uint64_t *sg=(const uint64_t*)g4,*su=(const uint64_t*)u4,*sd=(const uint64_t*)d4;
uint64_t *w0=(uint64_t*)dw,*w1=(uint64_t*)(dw+mb),*w2=(uint64_t*)(dw+2*mb);
for(size_t i=0;i<mb/8;i++){ w0[i]=sg[i]^X; w1[i]=su[i]^X; w2[i]=sd[i]^X; }
+ }
memcpy(dsc, gs, G.sc_gu*sizeof(float));
memcpy(dsc+G.sc_gu, us, G.sc_gu*sizeof(float));
memcpy(dsc+2*G.sc_gu, ds, G.sc_d *sizeof(float));
@@ -88,10 +104,18 @@ static void *uploader(void *arg){
} else pthread_mutex_unlock(&G.mx);
int dv = G.dev[home(eid)];
- size_t mb=(size_t)G.D*G.Ih/2;
+ /* passo fra le tre matrici nello staging: int4 impacchettato = mezzo
+ * byte per elemento, int8 = uno. */
+ size_t mb=(size_t)G.D*G.Ih/(G.wfmt==1?1:2);
ColiCudaTensor *tg=NULL,*tu=NULL,*td=NULL;
int ok;
- if(G.egs){
+ if(G.wfmt==1){
+ /* int8, scale per riga: qt_init ha gia' rifiutato il caso raggruppato,
+ * che questo formato non sa esprimere. */
+ ok = coli_cuda_tensor_upload(&tg, w, sc, 1, G.D, G.Ih, dv)
+ && coli_cuda_tensor_upload(&tu, w+mb, sc+G.Ih, 1, G.D, G.Ih, dv)
+ && coli_cuda_tensor_upload(&td, w+2*mb, sc+2*G.Ih, 1, G.Ih, G.D, dv);
+ } else if(G.egs){
ok = coli_cuda_tensor_upload_g(&tg, w, sc, 4, G.D, G.Ih, dv, G.egs)
&& coli_cuda_tensor_upload_g(&tu, w+mb, sc+G.sc_gu, 4, G.D, G.Ih, dv, G.egs)
&& coli_cuda_tensor_upload_g(&td, w+2*mb, sc+2*G.sc_gu, 4, G.Ih, G.D, dv, G.egs);
@@ -111,7 +135,8 @@ static void *uploader(void *arg){
}
}
-int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs){
+int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,
+ int expert_is_int4){
const char *e=getenv("COLI_CUDA");
if(!(e && *e=='1')) return 0;
if(cap != ne){
@@ -143,10 +168,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;
- G.exp_bytes = 3ull*D*Ih/2 + (2*G.sc_gu+G.sc_d)*sizeof(float) + 4096; /* + allocation slack */
+ /* 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");
for(int i=0;i<G.ndev;i++){
size_t freeb=0,totb=0; coli_cuda_mem_info(G.dev[i],&freeb,&totb);
@@ -203,7 +243,7 @@ static int enqueue_locked(int layer,int eid,int v_layer,int v_eid,int reserved){
if(G.qn>=QT_QCAP){ G.q_full_skips++; return 0; }
int hd=home(eid);
if(!reserved && v_eid<0 && G.used[hd]+G.exp_bytes>G.budget[hd]) return 0;
- size_t mb=(size_t)G.D*G.Ih/2;
+ size_t mb=(size_t)G.D*G.Ih/(G.wfmt==1?1:2); /* buffer di staging: int8 = 1 byte/elemento */
uint8_t *w=malloc(3*mb); float *sc=malloc((2*G.sc_gu+G.sc_d)*sizeof(float));
if(!w||!sc){ free(w); free(sc); return 0; }
if(!reserved && v_eid<0) G.used[hd]+=G.exp_bytes;
@@ -307,6 +347,9 @@ int qt_plan_fill(int *layers,int *eids,int max){
/* Thread-safe (callable from multiple loader threads): stage + enqueue one
* expert reserved by qt_plan_fill; blocks only while the queue is full. */
+/* g/u/d: i pesi COME STANNO IN RAM -- int4 impacchettati su un container gs64,
+ * int8 su un container int8. Il formato lo decide qt_init dal container, e da
+ * li' in poi staging e upload lo seguono. */
void qt_note_planned(int layer,int eid,
const uint8_t *g4,const uint8_t *u4,const uint8_t *d4,
const float *gs,const float *us,const float *ds){
diff --git a/c/qwen36_tier.h b/c/qwen36_tier.h
index e424a168..0596eaba 100644
--- a/c/qwen36_tier.h
+++ b/c/qwen36_tier.h
@@ -26,8 +26,12 @@
/* Init after model load. Returns 1 when the tier is active.
* cap_experts_per_layer must equal n_experts (full RAM residency): the tier
* stores raw pointers into the expert slots, which must never be evicted. */
+/* expert_is_int4: 1 = pesi int4 impacchettati (fmt=4), 0 = int8 (fmt=1). Il
+ * chiamante lo determina dalla TAGLIA SU DISCO, non da meta.ebits, che su
+ * qualche container mente (cfr. il rilevamento in qwen36.c). */
int qt_init(int n_layers, int n_experts, int hidden, int inter,
- int cap_experts_per_layer, int topk, int expert_gs);
+ int cap_experts_per_layer, int topk, int expert_gs,
+ int expert_is_int4);
int qt_ready(void);
int qt_is_resident(int layer, int eid);
void qt_shutdown(void);
@@ -63,7 +67,7 @@ void qt_stats(void);
#else /* !COLI_CUDA: inline stubs, engine stays CPU-only */
-static inline int qt_init(int a,int b,int c,int d,int e,int f,int g){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;return 0;}
+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_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/test_qwen36_tier_int8.c b/c/tests/test_qwen36_tier_int8.c
new file mode 100644
index 00000000..61279f85
--- /dev/null
+++ b/c/tests/test_qwen36_tier_int8.c
@@ -0,0 +1,168 @@
+/* Il tier VRAM deve promuovere anche gli esperti int8 (#1331).
+ *
+ * Il difetto: qt_plan_fill riservava budget e metteva planned=1 senza guardare
+ * il formato, mentre la promozione esigeva i puntatori int4. Su un container
+ * int8 quei puntatori sono NULL perche' non c'e' niente da impacchettare, quindi
+ * il budget restava riservato, il flag alzato -- e "if(resident||queued||planned)
+ * continue" garantiva che quell'esperto non venisse piu' riconsiderato. Zero
+ * esperti in VRAM per tutta la vita del processo, nessun messaggio, e un tier
+ * che dall'esterno sembrava acceso e freddo.
+ *
+ * Il backend qui e' finto e REGISTRA cio' che riceve: e' l'unico modo di provare
+ * su CI senza GPU la cosa che conta davvero, cioe' che qualcosa arrivi davvero
+ * in VRAM e nel formato giusto. Un test che si fermasse a "qt_init ritorna 1"
+ * sarebbe passato anche col difetto. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* ---- backend CUDA finto: le firme vengono da backend_cuda.h, che il tier
+ include per conto suo; qui si definisce solo il corpo. ---- */
+#include <stdint.h>
+#include <time.h>
+
+/* MinGW non ha setenv: il tier legge la sua configurazione dall'ambiente, e il
+ * test deve poterla impostare anche su Windows. */
+#if defined(_WIN32)
+#include <stdlib.h>
+static int test_setenv(const char *name, const char *value, int overwrite) {
+ (void)overwrite; return _putenv_s(name, value);
+}
+#define setenv test_setenv
+#endif
+#include "../backend_cuda.h"
+
+struct ColiCudaTensor { int fmt, I, O, device, gs; const void *w; };
+
+static int fake_uploads;
+static int last_fmt = -1;
+static size_t last_bytes;
+static unsigned char captured[4096];
+static size_t captured_len;
+
+static int upload_common(ColiCudaTensor **t, const void *w, int fmt,
+ int I, int O, int device, int gs) {
+ 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;
+ *t = n;
+ fake_uploads++;
+ last_fmt = fmt;
+ last_bytes = (size_t)I * O / (fmt == 1 ? 1 : 2);
+ if (fake_uploads == 1) {
+ captured_len = last_bytes < sizeof captured ? last_bytes : sizeof captured;
+ memcpy(captured, w, captured_len);
+ }
+ return 1;
+}
+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);
+}
+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);
+}
+void coli_cuda_tensor_free(ColiCudaTensor *t) { free(t); }
+int coli_cuda_available_device_count(void) { return 1; }
+int coli_cuda_device_count(void) { return 1; }
+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 */
+ return 1;
+}
+int coli_cuda_expert_group_issue(ColiCudaTensor *const *g, ColiCudaTensor *const *u,
+ ColiCudaTensor *const *d, const int *rows,
+ int count, const float *x) {
+ (void)g; (void)u; (void)d; (void)rows; (void)count; (void)x; return 0;
+}
+const float *coli_cuda_expert_group_take(int device) { (void)device; return NULL; }
+void coli_cuda_group_stats(uint64_t *calls, uint64_t *experts, uint64_t *rows,
+ double *h2d, double *kernel, double *d2h) {
+ if (calls) *calls = 0; if (experts) *experts = 0; if (rows) *rows = 0;
+ if (h2d) *h2d = 0; if (kernel) *kernel = 0; if (d2h) *d2h = 0;
+}
+void coli_cuda_stats(int device, size_t *count, size_t *bytes) {
+ (void)device; if (count) *count = 0; if (bytes) *bytes = 0;
+}
+
+#include "../qwen36_tier.c"
+
+static int fails;
+static void check(int ok, const char *what) {
+ if (!ok) { printf(" FAIL: %s\n", what); fails++; }
+}
+
+/* Aspetta che l'uploader asincrono abbia svuotato la coda, senza dormire a caso. */
+static void drain(void) {
+ for (int i = 0; i < 500 && fake_uploads == 0; i++) {
+ struct timespec ts = {0, 2000000}; /* 2 ms */
+ nanosleep(&ts, NULL);
+ }
+}
+
+int main(void) {
+ enum { NL = 2, NE = 4, D = 64, IH = 32, TOPK = 2 };
+ setenv("COLI_CUDA", "1", 1);
+ setenv("COLI_GPUS", "0", 1);
+ setenv("QT_NO_WARMSTART", "1", 1);
+
+ /* ---- 1. container int8: il tier deve accendersi e promuovere ---- */
+ if (!qt_init(NL, NE, D, IH, NE, TOPK, 0 /* per-row */, 0 /* int8 */)) {
+ printf(" FAIL: il tier rifiuta un container int8 con scale per riga\n");
+ return 1;
+ }
+ check(G.wfmt == 1, "int8 deve usare fmt=1");
+ check(G.exp_bytes > 3ull * D * IH,
+ "il budget int8 deve contare un byte per elemento, non mezzo");
+
+ int layers[8], eids[8];
+ int planned = qt_plan_fill(layers, eids, 8);
+ check(planned > 0, "qt_plan_fill non ha pianificato nessun esperto");
+
+ /* pesi finti: valori riconoscibili, per vedere se arrivano intatti */
+ size_t mb = (size_t)D * IH;
+ unsigned char *g = malloc(mb), *u = malloc(mb), *d = malloc(mb);
+ for (size_t i = 0; i < mb; i++) { g[i] = (unsigned char)(i & 0x7f); u[i] = 0x11; d[i] = 0x22; }
+ float *sc = calloc(2 * G.sc_gu + G.sc_d, sizeof(float));
+
+ qt_note_planned(layers[0], eids[0], g, u, d, sc, sc + G.sc_gu, sc + 2 * G.sc_gu);
+ drain();
+
+ /* Il cuore del test: con il difetto, qui fake_uploads restava 0. */
+ check(fake_uploads > 0,
+ "nessun esperto e' arrivato in VRAM: e' esattamente #1331, il tier "
+ "riserva budget e non promuove niente");
+ check(last_fmt == 1, "il backend deve ricevere fmt=1 per un container int8");
+ check(last_bytes == mb, "int8: un byte per elemento, senza impacchettamento");
+ /* i byte devono arrivare COME SONO: lo XOR 0x88 serve ai nibble int4 e su
+ * byte interi sarebbe corruzione silenziosa */
+ int intact = 1;
+ for (size_t i = 0; i < captured_len; i++)
+ if (captured[i] != (unsigned char)(i & 0x7f)) { intact = 0; break; }
+ check(intact, "i pesi int8 sono stati alterati durante lo staging (XOR di troppo?)");
+
+ qt_shutdown();
+
+ /* ---- 2. int8 + scale raggruppate: il kernel non sa esprimerle ---- */
+ fake_uploads = 0;
+ check(qt_init(NL, NE, D, IH, NE, TOPK, 64 /* grouped */, 0 /* int8 */) == 0,
+ "int8 con scale raggruppate va rifiutato PRIMA di riservare budget, "
+ "non promosso con numeri sbagliati");
+
+ /* ---- 3. int4 non deve cambiare comportamento ---- */
+ if (!qt_init(NL, NE, D, IH, NE, TOPK, 64, 1 /* int4 */)) {
+ printf(" FAIL: regressione, il tier non parte piu' su int4-gs64\n");
+ return 1;
+ }
+ check(G.wfmt == 4, "int4 deve restare fmt=4");
+ check(G.exp_bytes < 3ull * D * IH + 4096 + (2 * G.sc_gu + G.sc_d) * sizeof(float),
+ "int4 impacchettato deve contare mezzo byte per elemento");
+ qt_shutdown();
+
+ free(g); free(u); free(d); free(sc);
+ if (fails) { printf("test_qwen36_tier_int8: %d fallimenti\n", fails); return 1; }
+ printf("test_qwen36_tier_int8: ok\n");
+ return 0;
+}