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

perf(qwen): batch dense and shared prefill

JustVugg92cde9120878
diff --git a/c/Makefile b/c/Makefile
index d221d37c..830bcbc4 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -988,6 +988,13 @@ qwen36$(EXE): qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(C
tests/test_qwen36_ctx$(EXE): tests/test_qwen36_ctx.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
$(CC) $(CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(LDFLAGS)
+tests/test_qwen36_dense_batch$(EXE): tests/test_qwen36_dense_batch.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+ $(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)
+
+# Reproducible local timing evidence; intentionally not a noisy CI perf gate.
+tests/bench_qwen36_dense_batch$(EXE): tests/bench_qwen36_dense_batch.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+ $(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)
+
inkling$(EXE): inkling.c st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h omp_tune.h route_trace.h kv_prefix.h serve_codec.h $(INK_CUDA_OBJ) $(METAL_OBJ)
$(CC) $(CFLAGS) inkling.c $(INK_CUDA_OBJ) $(METAL_OBJ) -o inkling$(EXE) $(LDFLAGS)
diff --git a/c/qwen36.c b/c/qwen36.c
index 53cc667e..51c54b30 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -786,6 +786,93 @@ static void matmul_q(float *y, const float *x, const int8_t *q, const float *sca
#endif
}
+/* Multi-row dense-int8 prefill kernel. matmul_q() above is deliberately kept
+ * as the S=1 decode implementation: its four AVX accumulators stay in
+ * registers and its reduction order is covered by the token-exact oracle.
+ *
+ * For prompt rows, process two independent activations per weight decode. A
+ * two-row tile leaves enough AVX2 registers for both sets of four accumulators
+ * plus the converted weights; a four-row tile spills on the x86-64-v3 target.
+ * Each row uses the exact same FMA streams and reduction tree as matmul_q(), so
+ * batching changes neither a float bit nor the decode path. */
+static void matmul_q_batch(float *y, const float *x, const int8_t *q,
+ const float *scale, int S, int I, int O) {
+#if defined(__AVX2__) && defined(__FMA__)
+ /* Every shipping Qwen3.6 dense input width is 32-aligned. Keep unusual
+ * checkpoint shapes on the literal historical kernel instead of trying
+ * to make two interleaved scalar tails depend on compiler contraction. */
+ if (I & 31) {
+ for (int s = 0; s < S; s++)
+ matmul_q(y+(int64_t)s*O, x+(int64_t)s*I, q, scale, I, O);
+ return;
+ }
+ #pragma omp parallel for schedule(static) if(O >= 256)
+ for (int o = 0; o < O; o++) {
+ const int8_t *w = q + (int64_t)o * I;
+ int row = 0;
+ for (; row + 1 < S; row += 2) {
+ const float *x0 = x + (int64_t)row * I;
+ const float *x1 = x0 + I;
+ __m256 a00 = _mm256_setzero_ps(), a01 = _mm256_setzero_ps();
+ __m256 a02 = _mm256_setzero_ps(), a03 = _mm256_setzero_ps();
+ __m256 a10 = _mm256_setzero_ps(), a11 = _mm256_setzero_ps();
+ __m256 a12 = _mm256_setzero_ps(), a13 = _mm256_setzero_ps();
+ int i = 0;
+ for (; i + 32 <= I; i += 32) {
+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));
+ __m128i b1 = _mm_loadu_si128((const __m128i*)(w + i + 16));
+ __m256 w0 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0));
+ __m256 w1 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8)));
+ __m256 w2 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1));
+ __m256 w3 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b1,8)));
+ a00 = _mm256_fmadd_ps(_mm256_loadu_ps(x0+i), w0, a00);
+ a01 = _mm256_fmadd_ps(_mm256_loadu_ps(x0+i+8), w1, a01);
+ a02 = _mm256_fmadd_ps(_mm256_loadu_ps(x0+i+16), w2, a02);
+ a03 = _mm256_fmadd_ps(_mm256_loadu_ps(x0+i+24), w3, a03);
+ a10 = _mm256_fmadd_ps(_mm256_loadu_ps(x1+i), w0, a10);
+ a11 = _mm256_fmadd_ps(_mm256_loadu_ps(x1+i+8), w1, a11);
+ a12 = _mm256_fmadd_ps(_mm256_loadu_ps(x1+i+16), w2, a12);
+ a13 = _mm256_fmadd_ps(_mm256_loadu_ps(x1+i+24), w3, a13);
+ }
+ a00 = _mm256_add_ps(_mm256_add_ps(a00,a01), _mm256_add_ps(a02,a03));
+ a10 = _mm256_add_ps(_mm256_add_ps(a10,a11), _mm256_add_ps(a12,a13));
+ __m128 s0 = _mm_add_ps(_mm256_castps256_ps128(a00), _mm256_extractf128_ps(a00,1));
+ __m128 s1 = _mm_add_ps(_mm256_castps256_ps128(a10), _mm256_extractf128_ps(a10,1));
+ s0 = _mm_add_ps(s0, _mm_movehl_ps(s0,s0));
+ s1 = _mm_add_ps(s1, _mm_movehl_ps(s1,s1));
+ s0 = _mm_add_ss(s0, _mm_shuffle_ps(s0,s0,1));
+ s1 = _mm_add_ss(s1, _mm_shuffle_ps(s1,s1,1));
+ y[(int64_t)row*O + o] = _mm_cvtss_f32(s0) * scale[o];
+ y[(int64_t)(row+1)*O + o] = _mm_cvtss_f32(s1) * scale[o];
+ }
+ if (row < S) {
+ const float *xs = x + (int64_t)row * I;
+ __m256 a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();
+ __m256 a2 = _mm256_setzero_ps(), a3 = _mm256_setzero_ps();
+ int i = 0;
+ for (; i + 32 <= I; i += 32) {
+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));
+ __m128i b1 = _mm_loadu_si128((const __m128i*)(w + i + 16));
+ a0 = _mm256_fmadd_ps(_mm256_loadu_ps(xs+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);
+ a1 = _mm256_fmadd_ps(_mm256_loadu_ps(xs+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);
+ a2 = _mm256_fmadd_ps(_mm256_loadu_ps(xs+i+16), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1)), a2);
+ a3 = _mm256_fmadd_ps(_mm256_loadu_ps(xs+i+24), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b1,8))), a3);
+ }
+ a0 = _mm256_add_ps(_mm256_add_ps(a0,a1), _mm256_add_ps(a2,a3));
+ __m128 ss = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));
+ ss = _mm_add_ps(ss, _mm_movehl_ps(ss,ss));
+ ss = _mm_add_ss(ss, _mm_shuffle_ps(ss,ss,1));
+ y[(int64_t)row*O + o] = _mm_cvtss_f32(ss) * scale[o];
+ }
+ }
+#else
+ /* Other ISAs retain the established implementation until they have an
+ * independently exact multi-row kernel. */
+ for (int s = 0; s < S; s++)
+ matmul_q(y+(int64_t)s*O, x+(int64_t)s*I, q, scale, I, O);
+#endif
+}
+
/* Group-scaled int8 GEMV: one f32 scale per `gs` input elements per row
* (gs64 expert containers). Row layout of `scale`: [O][I/gs] row-major. */
static int g_expert_gs = 0; /* set from qwen36_meta.json (expert_gs) at load */
@@ -844,7 +931,11 @@ static void matmul_qe(float *y, const float *x, const int8_t *q, const float *sc
#define QDW_MAX 1024
static struct { const float *w; int8_t *q; float *sc; int I, O; } g_qdw[QDW_MAX];
static int g_qdw_n = 0;
+#ifdef COLI_QWEN_BATCH_TEST
+static uint64_t g_qwen_matmul_d_calls;
+#endif
static int dense_i8_on(void){ static int v=-1; if(v<0){ const char *e=getenv("COLI_DENSE_I8"); v=!(e&&*e=='0'); } return v; }
+static int dense_batch_on(void){ const char *e=getenv("QWEN_DENSE_BATCH"); return !(e&&*e=='0'); }
static void qdw_register(const float *W, int I, int O){
if (!W || !dense_i8_on() || g_qdw_n >= QDW_MAX) return;
int8_t *q = malloc((size_t)O*I); float *sc = malloc((size_t)O*sizeof(float));
@@ -860,8 +951,14 @@ static void qdw_register(const float *W, int I, int O){
g_qdw[g_qdw_n].w=W; g_qdw[g_qdw_n].q=q; g_qdw[g_qdw_n].sc=sc; g_qdw[g_qdw_n].I=I; g_qdw[g_qdw_n].O=O; g_qdw_n++;
}
static void matmul_d(float *y, const float *x, const float *W, int S, int I, int O){
+#ifdef COLI_QWEN_BATCH_TEST
+ g_qwen_matmul_d_calls++;
+#endif
for (int i = 0; i < g_qdw_n; i++) if (g_qdw[i].w == W && g_qdw[i].I == I) {
- for (int s = 0; s < S; s++) matmul_q(y+(int64_t)s*O, x+(int64_t)s*I, g_qdw[i].q, g_qdw[i].sc, I, O);
+ if (S > 1 && dense_batch_on())
+ matmul_q_batch(y, x, g_qdw[i].q, g_qdw[i].sc, S, I, O);
+ else
+ for (int s = 0; s < S; s++) matmul_q(y+(int64_t)s*O, x+(int64_t)s*I, g_qdw[i].q, g_qdw[i].sc, I, O);
return;
}
matmul(y, x, W, S, I, O);
@@ -1553,6 +1650,66 @@ static void attention(Model *m, Layer *l, int layer, float *x, int S, int pos_ba
free(q); free(k); free(vv); free(query); free(gate); free(ctx); free(ag);
}
+/* Batch the CPU shared expert across prompt rows. The three resident matrices
+ * are otherwise traversed S times even though every row uses the same weights.
+ * Decode (S=1) stays on the scalar matmul_d -> matmul_q path above. Long
+ * prompts are chunked so the additional activations consume at most 32 MiB;
+ * QWEN_SHARED_BATCH=0 is an exact scalar A/B switch, while a positive value
+ * sets a smaller row cap. */
+static int qwen_shared_batch_rows(int S, int D, int I) {
+ if (S <= 1) return 1;
+ const char *env = getenv("QWEN_SHARED_BATCH");
+ if (env) {
+ int requested = atoi(env);
+ if (requested <= 0) return 1;
+ if (requested < S) S = requested;
+ }
+ int64_t row_bytes = ((int64_t)2*I + D) * (int64_t)sizeof(float);
+ int64_t bounded = (32LL << 20) / (row_bytes > 0 ? row_bytes : 1);
+ if (bounded < 1) bounded = 1;
+ if (S > bounded) S = (int)bounded;
+ return S;
+}
+
+static void qwen_shared_experts_cpu(Model *m, Layer *l, const float *x, int S,
+ float *out, float *g, float *u, float *hh) {
+ Cfg *c=&m->c; int D=c->hidden, I=c->shared_inter;
+ int B=qwen_shared_batch_rows(S,D,I);
+ double _ts=tm_on()?tm_now():0.0;
+ if (B == 1) {
+ for (int s=0;s<S;s++) {
+ const float *xs=x+(int64_t)s*D;
+ matmul_d(g,xs,l->sh_g,1,D,I);
+ matmul_d(u,xs,l->sh_u,1,D,I);
+ for(int i=0;i<I;i++){float sv=g[i];g[i]=(sv/(1.f+expf(-sv)))*u[i];}
+ matmul_d(hh,g,l->sh_d,1,I,D);
+ float sgate=1.f;
+ if(l->sh_gate){float sg=0.f;for(int i=0;i<D;i++)sg+=xs[i]*l->sh_gate[i];sgate=1.f/(1.f+expf(-sg));}
+ float *os=out+(int64_t)s*D;
+ for(int d=0;d<D;d++)os[d]+=sgate*hh[d];
+ }
+ } else {
+ float *bg=falloc((int64_t)2*B*I), *bu=bg+(int64_t)B*I;
+ float *bh=falloc((int64_t)B*D);
+ for(int base=0;base<S;base+=B){
+ int rows=S-base<B?S-base:B;
+ matmul_d(bg,x+(int64_t)base*D,l->sh_g,rows,D,I);
+ matmul_d(bu,x+(int64_t)base*D,l->sh_u,rows,D,I);
+ for(int64_t q=0;q<(int64_t)rows*I;q++){float sv=bg[q];bg[q]=(sv/(1.f+expf(-sv)))*bu[q];}
+ matmul_d(bh,bg,l->sh_d,rows,I,D);
+ for(int s=0;s<rows;s++){
+ const float *xs=x+(int64_t)(base+s)*D;
+ float sgate=1.f;
+ if(l->sh_gate){float sg=0.f;for(int i=0;i<D;i++)sg+=xs[i]*l->sh_gate[i];sgate=1.f/(1.f+expf(-sg));}
+ float *os=out+(int64_t)(base+s)*D;const float *hs=bh+(int64_t)s*D;
+ for(int d=0;d<D;d++)os[d]+=sgate*hs[d];
+ }
+ }
+ free(bg);free(bh);
+ }
+ if(tm_on())tm_add(S,3,tm_now()-_ts);
+}
+
/* MoE: grouped top-k routing (+ optional router bias) + shared expert.
* Mirrors HF Qwen3 MoE: softmax(gate), optional group-limited top-k, normalized
* weights, sum routed experts, then add the un-gated shared expert. */
@@ -1568,6 +1725,7 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
memset(out, 0, (int64_t)S*D*sizeof(float));
float *g = falloc(I), *u = falloc(I), *hh = falloc(D);
float *sh = falloc(I), *shu = falloc(I), *shd = falloc(D); /* shared expert scratch */
+ int use_qt = qt_ready();
for (int s = 0; s < S; s++) {
float *pr = logits + (int64_t)s*E;
if (m->momentum_logits && m->pilot_smooth > 0.f) {
@@ -1618,8 +1776,7 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
for (int kk = 0; kk < K; kk++) if (idx[kk] >= 0) freq_l[idx[kk]]++;
}
const float *xs = x + (int64_t)s*D;
- int shared_done = 0;
- if (qt_ready()) {
+ if (use_qt) {
/* CUDA expert tier: run the resident experts as async groups on
* all devices, compute the misses on the CPU (overlapped), then
* collect the GPU results. */
@@ -1660,7 +1817,6 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
for (int d = 0; d < D; d++) os[d] += sgate * shd[d];
if (tm_on()) tm_add(S, 3, tm_now()-_ts2);
}
- shared_done = 1;
double _q2 = tm_on()? tm_now():0;
qt_take(qmask, val, K, out + (int64_t)s*D);
if (tm_on() && S==1) {
@@ -1680,24 +1836,11 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
for (int d = 0; d < D; d++) os[d] += w * hh[d];
}
}
- /* shared expert (SwiGLU), sigmoid-gated by shared_expert_gate */
- if (shared_done) { if (0) goto shared_skip_dummy; shared_skip_dummy: continue; }
- double _ts = tm_on() ? tm_now() : 0.0;
- int Ish = c->shared_inter;
- matmul_d(sh, xs, l->sh_g, 1, D, Ish);
- matmul_d(shu, xs, l->sh_u, 1, D, Ish);
- for (int i = 0; i < Ish; i++) { float sv = sh[i]; sh[i] = (sv / (1.f + expf(-sv))) * shu[i]; }
- matmul_d(shd, sh, l->sh_d, 1, Ish, D);
- float sgate = 1.f;
- if (l->sh_gate) {
- float sg = 0.f; const float *wg = l->sh_gate;
- for (int i = 0; i < D; i++) sg += xs[i] * wg[i];
- sgate = 1.f / (1.f + expf(-sg));
- }
- float *os = out + (int64_t)s*D;
- for (int d = 0; d < D; d++) os[d] += sgate * shd[d];
- if (tm_on()) tm_add(S, 3, tm_now()-_ts);
}
+ /* The CUDA tier keeps its per-token shared block above because it overlaps
+ * resident GPU experts. CPU prefill instead traverses each shared matrix
+ * once per bounded chunk. */
+ if (!use_qt) qwen_shared_experts_cpu(m,l,x,S,out,sh,shu,shd);
free(logits); free(g); free(u); free(hh); free(sh); free(shu); free(shd);
}
diff --git a/c/tests/bench_qwen36_dense_batch.c b/c/tests/bench_qwen36_dense_batch.c
new file mode 100644
index 00000000..39999f6b
--- /dev/null
+++ b/c/tests/bench_qwen36_dense_batch.c
@@ -0,0 +1,102 @@
+/* Optional local A/B for Qwen's default dense-int8 prefill path. These are
+ * the real Qwen3.6 shared-expert dimensions; one matrix is benchmarked at a
+ * time so peak RSS stays below 10 MiB.
+ *
+ * make tests/bench_qwen36_dense_batch ARCH=native
+ * OMP_NUM_THREADS=<physical cores> ./tests/bench_qwen36_dense_batch
+ */
+#define main qwen36_main_unused
+#include "../qwen36.c"
+#undef main
+
+enum { S=16, I=2048, O=512, REPS=7 };
+
+static float value(int64_t i, int salt) {
+ int v=(int)((i*31+salt*17)%251); return (float)(v-125)/(float)(109+salt);
+}
+
+static double scalar(float *y,const float *x,const int8_t *q,const float *sc) {
+ double t0=now_s();
+ for(int s=0;s<S;s++)matmul_q(y+(int64_t)s*O,x+(int64_t)s*I,q,sc,I,O);
+ return now_s()-t0;
+}
+static double batch(float *y,const float *x,const int8_t *q,const float *sc) {
+ double t0=now_s();matmul_q_batch(y,x,q,sc,S,I,O);return now_s()-t0;
+}
+
+static void env_set(const char *name,const char *value) {
+#ifdef _WIN32
+ _putenv_s(name,value);
+#else
+ setenv(name,value,1);
+#endif
+}
+static void env_unset(const char *name) {
+#ifdef _WIN32
+ _putenv_s(name,"");
+#else
+ unsetenv(name);
+#endif
+}
+
+static double shared_run(Model *m,Layer *l,const float *x,const float *seed,
+ float *out,const char *mode) {
+ float *g=falloc(O),*u=falloc(O),*hh=falloc(I);
+ if(mode){env_set("QWEN_SHARED_BATCH",mode);env_set("QWEN_DENSE_BATCH",mode);}
+ else{env_unset("QWEN_SHARED_BATCH");env_unset("QWEN_DENSE_BATCH");}
+ memcpy(out,seed,(size_t)S*I*sizeof(float));double t0=now_s();
+ qwen_shared_experts_cpu(m,l,x,S,out,g,u,hh);double dt=now_s()-t0;
+ free(g);free(u);free(hh);return dt;
+}
+
+static int shared_benchmark(void) {
+ Model m;memset(&m,0,sizeof(m));m.c.hidden=I;m.c.shared_inter=O;
+ Layer l;memset(&l,0,sizeof(l));
+ l.sh_g=falloc((int64_t)O*I);l.sh_u=falloc((int64_t)O*I);
+ l.sh_d=falloc((int64_t)I*O);l.sh_gate=falloc(I);
+ for(int64_t i=0;i<(int64_t)O*I;i++){l.sh_g[i]=value(i,2);l.sh_u[i]=value(i,3);}
+ for(int64_t i=0;i<(int64_t)I*O;i++)l.sh_d[i]=value(i,4);
+ for(int i=0;i<I;i++)l.sh_gate[i]=value(i,5);
+ qdw_register(l.sh_g,I,O);qdw_register(l.sh_u,I,O);qdw_register(l.sh_d,O,I);
+ if(g_qdw_n!=3){fprintf(stderr,"FAIL: expected three dense-int8 copies, got %d\n",g_qdw_n);return 1;}
+ float *x=falloc((int64_t)S*I),*seed=falloc((int64_t)S*I);
+ float *a=falloc((int64_t)S*I),*b=falloc((int64_t)S*I);
+ for(int64_t i=0;i<(int64_t)S*I;i++){x[i]=value(i,6);seed[i]=value(i,7);}
+ shared_run(&m,&l,x,seed,a,"0");shared_run(&m,&l,x,seed,b,NULL);
+ if(memcmp(a,b,(size_t)S*I*sizeof(float))){fputs("FAIL: shared batch is not exact\n",stderr);return 1;}
+ double ts=0,tb=0;enum{R=5};
+ for(int r=0;r<R;r++){
+ if(r&1){tb+=shared_run(&m,&l,x,seed,b,NULL);ts+=shared_run(&m,&l,x,seed,a,"0");}
+ else{ts+=shared_run(&m,&l,x,seed,a,"0");tb+=shared_run(&m,&l,x,seed,b,NULL);}
+ }
+ ts/=R;tb/=R;
+ printf("qwen shared int8: S=%d D=%d I=%d weights=%.1f MiB\n",S,I,O,
+ 3.0*I*O/1048576.0);
+ printf("scalar %.6f s batch %.6f s speedup %.2fx calls %d -> 3\n",ts,tb,ts/tb,S*3);
+ for(int i=0;i<g_qdw_n;i++){free(g_qdw[i].q);free(g_qdw[i].sc);}g_qdw_n=0;
+ free(l.sh_g);free(l.sh_u);free(l.sh_d);free(l.sh_gate);
+ free(x);free(seed);free(a);free(b);env_unset("QWEN_SHARED_BATCH");env_unset("QWEN_DENSE_BATCH");
+ return 0;
+}
+
+int main(void) {
+ env_unset("COLI_DENSE_I8");
+ float *x=falloc((int64_t)S*I),*a=falloc((int64_t)S*O),*b=falloc((int64_t)S*O);
+ int8_t *q=malloc((size_t)O*I);float *sc=falloc(O);
+ if(!q){fputs("OOM qwen dense benchmark\n",stderr);return 2;}
+ for(int64_t i=0;i<(int64_t)S*I;i++)x[i]=value(i,1);
+ for(int64_t i=0;i<(int64_t)O*I;i++)q[i]=(int8_t)((i*13+5)%255-127);
+ for(int o=0;o<O;o++)sc[o]=0.001f*(float)(1+(o*7)%29);
+ scalar(a,x,q,sc);batch(b,x,q,sc);
+ if(memcmp(a,b,(size_t)S*O*sizeof(float))){fputs("FAIL: batch is not exact\n",stderr);return 1;}
+ double ts=0,tb=0;
+ for(int r=0;r<REPS;r++){
+ if(r&1){tb+=batch(b,x,q,sc);ts+=scalar(a,x,q,sc);}
+ else{ts+=scalar(a,x,q,sc);tb+=batch(b,x,q,sc);}
+ }
+ ts/=REPS;tb/=REPS;
+ printf("qwen dense int8: S=%d I=%d O=%d weights=%.1f MiB\n",S,I,O,
+ (double)I*O/1048576.0);
+ printf("scalar %.6f s batch %.6f s speedup %.2fx\n",ts,tb,ts/tb);
+ free(x);free(a);free(b);free(q);free(sc);return shared_benchmark();
+}
diff --git a/c/tests/test_qwen36_dense_batch.c b/c/tests/test_qwen36_dense_batch.c
new file mode 100644
index 00000000..fd338210
--- /dev/null
+++ b/c/tests/test_qwen36_dense_batch.c
@@ -0,0 +1,120 @@
+/* Model-free exactness gate for Qwen's dense-int8 prefill kernel. The old
+ * path calls matmul_q once per prompt row; the new path shares every int8
+ * weight decode between two rows. Compare raw float bytes across even/odd
+ * row counts, vector tails, and both sides of the OpenMP threshold. */
+#define COLI_QWEN_BATCH_TEST 1
+#define main qwen36_main_unused
+#include "../qwen36.c"
+#undef main
+
+static int failures;
+#define CHECK(cond, ...) do { if (!(cond)) { \
+ fprintf(stderr,"FAIL %s:%d: ",__FILE__,__LINE__); \
+ fprintf(stderr,__VA_ARGS__); fputc('\n',stderr); failures++; } } while (0)
+
+static float input_value(int64_t i, int salt) {
+ int v = (int)((i * 37 + salt * 19) % 251);
+ return (float)(v - 125) / (float)(97 + salt);
+}
+
+static void one_shape(int S, int I, int O) {
+ float *x = falloc((int64_t)S*I);
+ int8_t *q = malloc((size_t)O*I);
+ float *sc = falloc(O);
+ float *ref = falloc((int64_t)S*O), *got = falloc((int64_t)S*O);
+ CHECK(q != NULL, "weight allocation failed");
+ if (!q) exit(2);
+ for (int64_t i=0;i<(int64_t)S*I;i++) x[i]=input_value(i,1);
+ for (int64_t i=0;i<(int64_t)O*I;i++) q[i]=(int8_t)((i*29+7)%255-127);
+ for (int o=0;o<O;o++) sc[o]=0.001f*(float)(1+(o*11)%31);
+
+ for (int s=0;s<S;s++)
+ matmul_q(ref+(int64_t)s*O,x+(int64_t)s*I,q,sc,I,O);
+ matmul_q_batch(got,x,q,sc,S,I,O);
+ if (memcmp(ref,got,(size_t)S*O*sizeof(float))) {
+ int shown=0, different=0; float worst=0.f;
+ for (int64_t i=0;i<(int64_t)S*O;i++) if (ref[i]!=got[i]) {
+ float d=fabsf(ref[i]-got[i]); if(d>worst)worst=d;
+ if(shown++<4)fprintf(stderr,"diff[%lld] ref=%a batch=%a delta=%g\n",
+ (long long)i,ref[i],got[i],d);
+ different++;
+ }
+ CHECK(0,"S=%d I=%d O=%d differs at %d values, worst=%g",
+ S,I,O,different,worst);
+ }
+ printf("qwen dense batch exact: S=%d I=%d O=%d\n",S,I,O);
+ free(x);free(q);free(sc);free(ref);free(got);
+}
+
+static void env_set(const char *name,const char *value) {
+#ifdef _WIN32
+ _putenv_s(name,value);
+#else
+ setenv(name,value,1);
+#endif
+}
+static void env_unset(const char *name) {
+#ifdef _WIN32
+ _putenv_s(name,"");
+#else
+ unsetenv(name);
+#endif
+}
+
+static void clear_qdw(void) {
+ for(int i=0;i<g_qdw_n;i++){free(g_qdw[i].q);free(g_qdw[i].sc);}
+ g_qdw_n=0;
+}
+
+static void shared_case(const char *format,int quantized) {
+ enum { S=12,D=64,I=32 };
+ Model m;memset(&m,0,sizeof(m));m.c.hidden=D;m.c.shared_inter=I;
+ Layer l;memset(&l,0,sizeof(l));
+ l.sh_g=falloc((int64_t)I*D);l.sh_u=falloc((int64_t)I*D);
+ l.sh_d=falloc((int64_t)D*I);l.sh_gate=falloc(D);
+ for(int64_t i=0;i<(int64_t)I*D;i++){l.sh_g[i]=input_value(i,2);l.sh_u[i]=input_value(i,3);}
+ for(int64_t i=0;i<(int64_t)D*I;i++)l.sh_d[i]=input_value(i,4);
+ for(int i=0;i<D;i++)l.sh_gate[i]=input_value(i,5);
+ if(quantized){qdw_register(l.sh_g,D,I);qdw_register(l.sh_u,D,I);qdw_register(l.sh_d,I,D);}
+ float *x=falloc((int64_t)S*D),*seed=falloc((int64_t)S*D);
+ float *ref=falloc((int64_t)S*D),*got=falloc((int64_t)S*D);
+ float *g=falloc(I),*u=falloc(I),*hh=falloc(D);
+ for(int64_t i=0;i<(int64_t)S*D;i++){x[i]=input_value(i,6);seed[i]=input_value(i,7);}
+
+ memcpy(ref,seed,(size_t)S*D*sizeof(float));env_set("QWEN_SHARED_BATCH","0");
+ env_set("QWEN_DENSE_BATCH","0");g_qwen_matmul_d_calls=0;
+ qwen_shared_experts_cpu(&m,&l,x,S,ref,g,u,hh);
+ CHECK(g_qwen_matmul_d_calls==(uint64_t)S*3,"%s scalar calls=%llu expected=%d",format,
+ (unsigned long long)g_qwen_matmul_d_calls,S*3);
+
+ memcpy(got,seed,(size_t)S*D*sizeof(float));env_unset("QWEN_SHARED_BATCH");
+ env_unset("QWEN_DENSE_BATCH");g_qwen_matmul_d_calls=0;
+ qwen_shared_experts_cpu(&m,&l,x,S,got,g,u,hh);
+ CHECK(!memcmp(ref,got,(size_t)S*D*sizeof(float)),"%s shared batch is not scalar bit-exact",format);
+ CHECK(g_qwen_matmul_d_calls==3,"%s batch calls=%llu expected=3",format,
+ (unsigned long long)g_qwen_matmul_d_calls);
+
+ memcpy(got,seed,(size_t)D*sizeof(float));g_qwen_matmul_d_calls=0;
+ qwen_shared_experts_cpu(&m,&l,x,1,got,g,u,hh);
+ CHECK(!memcmp(ref,got,(size_t)D*sizeof(float)),"%s decode row changed",format);
+ CHECK(g_qwen_matmul_d_calls==3,"%s decode calls=%llu expected=3",format,
+ (unsigned long long)g_qwen_matmul_d_calls);
+ printf("qwen shared batch exact: format=%s S=%d calls=%d -> 3\n",format,S,S*3);
+
+ clear_qdw();free(l.sh_g);free(l.sh_u);free(l.sh_d);free(l.sh_gate);
+ free(x);free(seed);free(ref);free(got);free(g);free(u);free(hh);
+}
+
+int main(void) {
+ /* This gate owns the dense-int8 mode regardless of the caller's shell. */
+ env_unset("COLI_DENSE_I8");
+ one_shape(1, 17, 13); /* decode-shaped fallback */
+ one_shape(2, 32, 31); /* one vector block, one row pair */
+ one_shape(4, 64, 73); /* even prompt, serial OpenMP clause */
+ one_shape(5, 67, 259); /* odd prompt + scalar tail + parallel clause */
+ shared_case("f32",0);
+ shared_case("int8",1);
+ env_unset("QWEN_SHARED_BATCH");env_unset("QWEN_DENSE_BATCH");
+ if(failures){fprintf(stderr,"qwen dense batch: %d failure(s)\n",failures);return 1;}
+ puts("qwen dense batch: ok");return 0;
+}
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index 4dadc877..bc45e51d 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -6,7 +6,7 @@ Reference for the environment variables read by the colibrì engine.
## Which program reads these?
-**There are five engine binaries, and they do not share a knob set.** The main
+**There are six engine binaries, and they do not share a knob set.** The main
engine `c/colibri` (built from `c/colibri.c`, formerly `glm.c`) reads most of
what follows, but the sister engines read their own:
@@ -15,6 +15,7 @@ what follows, but the sister engines read their own:
| `colibri` | `c/colibri.c` | everything below except the three sections named for another engine |
| `kimi_k3` | `c/kimi_k3.c` | the `K3_*` family — see [Kimi K3 engine](#kimi-k3-engine-kimi_k3) |
| `inkling` | `c/inkling.c` | `INK_*`, plus `CTX_MAX`, `PIN_N`, `REP_PEN`, `GPU_DEV`, `NOGPU` — see [Inkling engine](#inkling-engine-inkling) |
+| `qwen36` | `c/qwen36.c` | `QWEN_*`, `Q36_*`, and its dense/CUDA-tier controls — see [Qwen3.6 engine](#qwen36-engine-qwen36) |
| `olmoe` | `c/olmoe.c` | `HOT`, `WIDE`, `SMOOTH`, `CONF_LIMIT`, `MAX_NEW`, `CHAT`, `EXPERT_DROP`, `WARMUP` — see [OLMoE engine](#olmoe-engine-olmoe) |
| `deepseek_v4` | `c/deepseek_v4.c` | `CTX`, the `V4_*` / `DSV4_*` families and the two `COLI_CUDA_*_BATCH` gates — see [DeepSeek V4 engine](#deepseek-v4-engine-deepseek_v4); note that the CUDA section below describes `colibri.c` knobs (`COLI_CUDA`, `CUDA_DENSE`, ...) which the V4 engine does not read — its GPU switch is `DSV4_CUDA` |
@@ -357,6 +358,18 @@ Read **only** by `c/inkling.c`.
| `GPU_DEV` | `0` | CUDA device index for the inkling CUDA backend. |
| `NOGPU` | unset | If set, skip GPU init entirely (both CUDA and Metal), regardless of the other GPU variables. |
+## Qwen3.6 engine (`qwen36`)
+
+Read **only** by `c/qwen36.c`. See [qwen36.md](qwen36.md) for the model layout
+and the CPU/GPU execution split.
+
+| Variable | Default | Effect |
+|---|---|---|
+| `COLI_DENSE_I8` | `1` (on) | Quantize resident dense matrices to per-row int8 at startup. `=0` keeps the f32 reference path for quality A/Bs. |
+| `QWEN_DENSE_BATCH` | `1` (on) | On AVX2/FMA, reuse each dense-int8 weight decode across two prompt rows. `=0` restores one GEMV call per row. Decode `S=1` is unchanged. |
+| `QWEN_SHARED_BATCH` | bounded by 32 MiB scratch | Batch the CPU shared expert across prompt rows. `=0` restores scalar calls; a positive integer caps rows per chunk. The CUDA-tier overlap path is unchanged. |
+| `Q36_MAXT` | conservative engine default | Lower the served/context capacity; it cannot raise the model's compiled safety ceiling. |
+
## DeepSeek V4 engine (`deepseek_v4`)
The V4 engine has its own knob set (~70 variables: GPU tier, prefill segments/
diff --git a/docs/qwen36.md b/docs/qwen36.md
index 7fe8391e..4644774b 100644
--- a/docs/qwen36.md
+++ b/docs/qwen36.md
@@ -48,10 +48,25 @@ SNAP=~/Models/qwen36_i4_gs64 TOK=~/Models/qwen36_i4_gs64/tokenizer.json \
N_NEW=200 ./c/qwen36 256 4 prompt.txt
```
-Requirements: ~30 GB RAM for comfortable expert caching, NVMe storage for the
-container. CPU-only in this build; the CUDA VRAM expert tier is a separate PR
-([#713](https://github.com/JustVugg/colibri/pull/713)), which brings its own
-`docs/qwen36-cuda-tier.md` — the file does not exist in this PR.
+## CPU prefill batching
+
+On AVX2/FMA CPUs, dense int8 projections process two prompt rows per weight
+decode. The same kernel is used by attention, the router, DeltaNet projections,
+and the CPU shared expert. `S=1` decode keeps the original four-register GEMV,
+and non-AVX2 builds retain the established per-row implementation. The shared
+expert additionally batches gate/up/down calls across prompt rows with at most
+32 MiB of temporary activations; the CUDA expert tier keeps its per-token shared
+work so it can continue to overlap the in-flight GPU groups.
+
+Both optimizations are bit-exact and on by default. For controlled A/Bs,
+`QWEN_DENSE_BATCH=0` restores per-row dense-int8 GEMVs and
+`QWEN_SHARED_BATCH=0` restores per-row shared-expert calls. A positive
+`QWEN_SHARED_BATCH=N` limits each shared chunk to `N` rows.
+
+Requirements: ~30 GB RAM for comfortable expert caching and NVMe storage for
+the container. The default build is CPU-only; `make -C c qwen36 CUDA=1` adds
+the optional CUDA VRAM expert tier documented in
+[`qwen36-cuda-tier.md`](qwen36-cuda-tier.md).
## Which container?