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

qwen38: int8 trunk with integer dot products, vector FP8 expert kernel

JustVugg0137b8f8c77c
diff --git a/c/Makefile b/c/Makefile
index 55a8bfeb..2d487fa1 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1295,6 +1295,9 @@ tests/test_qwen38_tokenizer$(EXE): tests/test_qwen38_tokenizer.c qwen38.c qwen38
tests/test_qwen38_config$(EXE): tests/test_qwen38_config.c qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h idot.h route_trace.h tok_unicode.h tok_unicode_o200k.h
$(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)
+tests/test_qwen38_idot$(EXE): tests/test_qwen38_idot.c qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h idot.h route_trace.h tok_unicode.h tok_unicode_o200k.h
+ $(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)
+
tests/test_qwen38_serve_framing$(EXE): tests/test_qwen38_serve_framing.c qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h idot.h route_trace.h serve_codec.h tok_unicode.h tok_unicode_o200k.h
$(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)
diff --git a/c/idot.h b/c/idot.h
index 6738abeb..34eaf3eb 100644
--- a/c/idot.h
+++ b/c/idot.h
@@ -73,6 +73,56 @@ static inline float qrow_i8(const float *x, int8_t *q, int I){
return s;
}
+/* Activation -> int8 with one scale (shared by every engine whose trunk
+ * meets the integer kernels below), plus the int32 sum of every block of 64
+ * (the K1b kernel subtracts 8*sum per group because its nibbles are unsigned).
+ * Vectorized: the scalar lrintf loop was measured at ~7 us for 4096 values,
+ * which times ~150 GEMVs per token is a millisecond thrown away. Rounding is
+ * to nearest even in both paths, so the vector path equals qrow_i8 bit for bit. */
+static float dense_act_i8(const float *x, int I, int8_t *xq, int32_t *xsg){
+ float amax = 0.f;
+ int i = 0;
+#ifdef __AVX2__
+ {
+ __m256 am = _mm256_setzero_ps();
+ const __m256 sign = _mm256_set1_ps(-0.0f);
+ for (; i + 8 <= I; i += 8) am = _mm256_max_ps(am, _mm256_andnot_ps(sign, _mm256_loadu_ps(x + i)));
+ float tmp[8]; _mm256_storeu_ps(tmp, am);
+ for (int k = 0; k < 8; k++) if (tmp[k] > amax) amax = tmp[k];
+ }
+#endif
+ for (; i < I; i++) { float a = fabsf(x[i]); if (a > amax) amax = a; }
+ float s = amax / 127.f; if (s < 1e-12f) s = 1e-12f;
+ float inv = 1.f / s;
+ i = 0;
+#ifdef __AVX2__
+ {
+ const __m256 vinv = _mm256_set1_ps(inv);
+ for (; i + 32 <= I; i += 32) {
+ __m256i a = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i), vinv));
+ __m256i b = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i + 8), vinv));
+ __m256i c = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i + 16), vinv));
+ __m256i d = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i + 24), vinv));
+ /* packs interleave 128-bit lanes: fix the order with one permute */
+ __m256i ab = _mm256_packs_epi32(a, b), cd = _mm256_packs_epi32(c, d);
+ __m256i abcd = _mm256_packs_epi16(ab, cd);
+ abcd = _mm256_permutevar8x32_epi32(abcd, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
+ _mm256_storeu_si256((__m256i *)(xq + i), abcd);
+ }
+ }
+#endif
+ for (; i < I; i++) xq[i] = (int8_t)lrintf(x[i] * inv);
+ if (xsg) {
+ int ng = I / 64;
+ for (int g = 0; g < ng; g++) {
+ int32_t sum = 0;
+ for (int k = 0; k < 64; k++) sum += xq[g * 64 + k];
+ xsg[g] = sum;
+ }
+ }
+ return s;
+}
+
/* dot int8*int8 */
static inline int32_t dot_i8i8(const int8_t *w, const int8_t *x, int I){
int32_t sum=0; int i=0;
diff --git a/c/qwen36.c b/c/qwen36.c
index 49ced244..8fa7c56b 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -1076,55 +1076,6 @@ static int g_qdw_n = 0;
static int dense_idot_on(void){ static int v=-1; if(v<0){ const char *e=getenv("COLI_DENSE_IDOT"); v=!(e&&*e=='0'); } return v; }
static int dense_bits(void){ static int v=-1; if(v<0){ const char *e=getenv("COLI_DENSE_BITS"); v=(e&&atoi(e)==4)?4:8; } return v; }
-/* Activation -> int8 with one scale, plus the int32 sum of every block of 64
- * (the K1b kernel subtracts 8*sum per group because its nibbles are unsigned).
- * Vectorized: the scalar lrintf loop was measured at ~7 us for 4096 values,
- * which times ~150 GEMVs per token is a millisecond thrown away. Rounding is
- * to nearest even in both paths, so the vector path equals qrow_i8 bit for bit. */
-static float dense_act_i8(const float *x, int I, int8_t *xq, int32_t *xsg){
- float amax = 0.f;
- int i = 0;
-#ifdef __AVX2__
- {
- __m256 am = _mm256_setzero_ps();
- const __m256 sign = _mm256_set1_ps(-0.0f);
- for (; i + 8 <= I; i += 8) am = _mm256_max_ps(am, _mm256_andnot_ps(sign, _mm256_loadu_ps(x + i)));
- float tmp[8]; _mm256_storeu_ps(tmp, am);
- for (int k = 0; k < 8; k++) if (tmp[k] > amax) amax = tmp[k];
- }
-#endif
- for (; i < I; i++) { float a = fabsf(x[i]); if (a > amax) amax = a; }
- float s = amax / 127.f; if (s < 1e-12f) s = 1e-12f;
- float inv = 1.f / s;
- i = 0;
-#ifdef __AVX2__
- {
- const __m256 vinv = _mm256_set1_ps(inv);
- for (; i + 32 <= I; i += 32) {
- __m256i a = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i), vinv));
- __m256i b = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i + 8), vinv));
- __m256i c = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i + 16), vinv));
- __m256i d = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(x + i + 24), vinv));
- /* packs interleave 128-bit lanes: fix the order with one permute */
- __m256i ab = _mm256_packs_epi32(a, b), cd = _mm256_packs_epi32(c, d);
- __m256i abcd = _mm256_packs_epi16(ab, cd);
- abcd = _mm256_permutevar8x32_epi32(abcd, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
- _mm256_storeu_si256((__m256i *)(xq + i), abcd);
- }
- }
-#endif
- for (; i < I; i++) xq[i] = (int8_t)lrintf(x[i] * inv);
- if (xsg) {
- int ng = I / 64;
- for (int g = 0; g < ng; g++) {
- int32_t sum = 0;
- for (int k = 0; k < 64; k++) sum += xq[g * 64 + k];
- xsg[g] = sum;
- }
- }
- return s;
-}
-
/* f32 rows -> int4 in blocks of 64 with one f32 scale per block, packed as the
* K1b planar layout (unsigned nibbles v+8, block b: lo nibbles = elements
* b*64..b*64+31, hi = b*64+32..b*64+63). The quantizer is the symmetric
diff --git a/c/qwen38.c b/c/qwen38.c
index eb4e2c64..df6e2c47 100644
--- a/c/qwen38.c
+++ b/c/qwen38.c
@@ -1939,7 +1939,7 @@ int main(int argc, char **argv) {
Model m; model_init(&m, snap, cap, bits);
q38_tier_start(&m, cap); /* COLI_CUDA=1: hot experts stream to VRAM (qwen36_tier.c) */
- q38_trunk_cpu_int8(&m); /* Q38_TRUNK_CPU_INT8=1: the trunk's int8 rows on the CPU (reference) */
+ q38_trunk_cpu_int8(&m); /* the trunk's int8 rows on the CPU, BF16 released (Q38_TRUNK_CPU_INT8=0 keeps BF16) */
if(is_ref)ref_logits=read_reference_logits(ref_root,m.c.vocab);
g_capture_last_logit=ref_logits!=NULL||getenv("DUMP")!=NULL;
q38_telemetry_init(snap, &m);
diff --git a/c/qwen38_core.h b/c/qwen38_core.h
index 30dcfdb2..34052a0d 100644
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@ -50,7 +50,7 @@ typedef struct {
Q38WeightKind kind;
unsigned owns_data:1, owns_scales:1;
int gpu; /* 0 = CPU; else 1 + tier handle of an int8 copy resident in VRAM (decode, S == 1) */
- int8_t *q8; float *q8sc; /* Q38_TRUNK_CPU_INT8=1: the same int8 rows kept on the CPU (reference for the GPU path, no GPU needed) */
+ int8_t *q8; float *q8sc; /* the trunk's int8 rows on the CPU (default; Q38_TRUNK_CPU_INT8=0 keeps BF16): the same rows the GPU holds, met by an int8 activation in idot.h */
} Q38Weight;
typedef struct { float *norm; Q38Weight down, up, inject; } GatedResidual;
@@ -264,6 +264,75 @@ static void q38_matmul_bf16(float *y,const float *x,const uint16_t *W,
}
}
+/* The routed experts as the checkpoint ships them: e4m3 bytes with one f32
+ * scale per 128x128 block. quant.h's matmul_fp8 decodes every byte through a
+ * 256-entry table, one gather per weight; this kernel decodes eight bytes at a
+ * time in registers (quant.h e4m3_decode8: a shift and one multiply, NaNs
+ * kept) and multiplies them with FMA. The block scale still applies once per
+ * block and the blocks still add in double, so the result differs from the
+ * scalar kernel only by the float summation order inside a block. For a
+ * batch of rows (prefill) the block is decoded once and held while every row
+ * runs through it: the matrix streams past once, not once per row.
+ * Q38_FP8_KERNEL=scalar restores the table kernel (bisecting a difference). */
+static int q38_fp8_vector_on(void) {
+ static int v=-1;
+ if(v<0){ const char *e=getenv("Q38_FP8_KERNEL"); v=!(e&&!strcmp(e,"scalar")); }
+ return v;
+}
+#ifdef __AVX2__
+#define Q38_FP8_ROWS 8
+static void q38_matmul_fp8_vec(float *y,const float *x,const uint8_t *q8,
+ const float *bscale,int S,int I,int O) {
+ int64_t nblkI=fp8_nblk(I);
+ #pragma omp parallel for schedule(static)
+ for(int o=0;o<O;o++){
+ const uint8_t *w=q8+(int64_t)o*I;
+ const float *scl=bscale+((int64_t)o/FP8_BLOCK)*nblkI;
+ if(S==1){
+ /* decode: the weight bytes are the traffic, so decode and multiply in one pass */
+ double a=0;
+ for(int64_t bi=0;bi*FP8_BLOCK<I;bi++){
+ int base=(int)(bi*FP8_BLOCK),blen=I-base<FP8_BLOCK?I-base:FP8_BLOCK,i=0;
+ __m256 acc=_mm256_setzero_ps();
+ for(;i+8<=blen;i+=8)
+ acc=_mm256_fmadd_ps(e4m3_decode8(w+base+i),_mm256_loadu_ps(x+base+i),acc);
+ float part=hsum256(acc);
+ for(;i<blen;i++)part+=e4m3_decode(w[base+i])*x[base+i];
+ a+=(double)part*scl[bi];
+ }
+ y[o]=(float)a; continue;
+ }
+ for(int s0=0;s0<S;s0+=Q38_FP8_ROWS){
+ int ns=S-s0<Q38_FP8_ROWS?S-s0:Q38_FP8_ROWS; double a[Q38_FP8_ROWS]={0};
+ for(int64_t bi=0;bi*FP8_BLOCK<I;bi++){
+ int base=(int)(bi*FP8_BLOCK),blen=I-base<FP8_BLOCK?I-base:FP8_BLOCK,i=0;
+ float wf[FP8_BLOCK];
+ for(;i+8<=blen;i+=8)_mm256_storeu_ps(wf+i,e4m3_decode8(w+base+i));
+ for(;i<blen;i++)wf[i]=e4m3_decode(w[base+i]);
+ float sc=scl[bi];
+ for(int r=0;r<ns;r++){
+ const float *xs=x+(int64_t)(s0+r)*I+base; int k=0;
+ __m256 acc=_mm256_setzero_ps();
+ for(;k+8<=blen;k+=8)
+ acc=_mm256_fmadd_ps(_mm256_loadu_ps(wf+k),_mm256_loadu_ps(xs+k),acc);
+ float part=hsum256(acc);
+ for(;k<blen;k++)part+=wf[k]*xs[k];
+ a[r]+=(double)part*sc;
+ }
+ }
+ for(int r=0;r<ns;r++)y[(int64_t)(s0+r)*O+o]=(float)a[r];
+ }
+ }
+}
+#endif
+static void q38_matmul_fp8(float *y,const float *x,const uint8_t *q8,const float *bscale,
+ int S,int I,int O) {
+#ifdef __AVX2__
+ if(q38_fp8_vector_on()){ q38_matmul_fp8_vec(y,x,q8,bscale,S,I,O); return; }
+#endif
+ matmul_fp8(y,x,q8,bscale,S,I,O);
+}
+
static void q38_weight_matmul(float *y,const float *x,const Q38Weight *weight,
int S,int I,int O) {
/* A matrix the tier placed in VRAM (q38_trunk_place) answers a decode
@@ -271,16 +340,17 @@ static void q38_weight_matmul(float *y,const float *x,const Q38Weight *weight,
* so the BF16 copy stays the reference for everything but S == 1. */
if(S==1&&weight&&weight->gpu&&weight->rows==O&&weight->cols==I&&
qt_dense_matmul(weight->gpu-1,y,x,I,O))return;
- if(S==1&&weight&&weight->q8&&weight->rows==O&&weight->cols==I){
- /* the int8 rows the GPU would hold, computed here: what the trunk
- * quantization alone does to the output, GPU or not */
- const int8_t *q=weight->q8; const float *sc=weight->q8sc;
- #pragma omp parallel for schedule(static)
- for(int o=0;o<O;o++){
- const int8_t *w=q+(size_t)o*I; float a=0.f;
- for(int i=0;i<I;i++)a+=x[i]*(float)w[i];
- y[o]=a*sc[o];
- }
+ if(weight&&weight->q8&&weight->rows==O&&weight->cols==I){
+ /* the trunk's int8 rows (the same the GPU holds) meet an int8
+ * activation in the integer kernel: x quantized once per row with one
+ * scale, then maddubs / vpdpbusd dot products (idot.h). Decode and
+ * prefill take the same path, so GPU or not the trunk quantization is
+ * the only thing that separates the output from the BF16 run. */
+ int8_t *xq=(int8_t*)malloc((size_t)S*I); float *sx=(float*)malloc((size_t)S*sizeof(float));
+ if(!xq||!sx){fprintf(stderr,"OOM activation quantization\n");exit(1);}
+ for(int s=0;s<S;s++)sx[s]=dense_act_i8(x+(int64_t)s*I,I,xq+(int64_t)s*I,NULL);
+ matmul_q_idot(y,xq,sx,weight->q8,weight->q8sc,S,I,O);
+ free(xq);free(sx);
return;
}
if(!weight||weight->rows!=O||weight->cols!=I||!weight->data){
@@ -293,7 +363,7 @@ static void q38_weight_matmul(float *y,const float *x,const Q38Weight *weight,
else if(weight->kind==Q38_WEIGHT_BF16)
q38_matmul_bf16(y,x,(const uint16_t*)weight->data,S,I,O);
else if(weight->kind==Q38_WEIGHT_FP8&&weight->scales)
- matmul_fp8(y,x,(const uint8_t*)weight->data,weight->scales,S,I,O);
+ q38_matmul_fp8(y,x,(const uint8_t*)weight->data,weight->scales,S,I,O);
else {fprintf(stderr,"unsupported matmul weight kind %d\n",(int)weight->kind);exit(1);}
}
@@ -1725,7 +1795,7 @@ static void q38_tier_note(int layer,int eid,const Slot *ex) {
* stays for prefill and as fallback. Q38_TRUNK_GPU=0 keeps the trunk on the
* CPU (parity runs against the BF16 reference). */
typedef struct { Q38Weight *w; char name[16]; int layer; } Q38TrunkItem;
-static Q38TrunkItem *g_trunk; static int g_trunk_n, g_trunk_cap;
+static Q38TrunkItem *g_trunk; static int g_trunk_n, g_trunk_cap, g_trunk_offer_gpu;
static void q38_trunk_add(Q38Weight *w,const char *name,int layer) {
if(!w||!w->data||(w->kind!=Q38_WEIGHT_BF16&&w->kind!=Q38_WEIGHT_F32))return;
size_t bytes=(size_t)w->rows*w->cols+(size_t)w->rows*sizeof(float);
@@ -1747,15 +1817,18 @@ static void q38_trunk_add(Q38Weight *w,const char *name,int layer) {
}
Q38TrunkItem *it=&g_trunk[g_trunk_n++]; it->w=w; it->layer=layer;
snprintf(it->name,sizeof it->name,"%s",name);
- qt_trunk_offer(it->name,layer,bytes);
+ if(g_trunk_offer_gpu)qt_trunk_offer(it->name,layer,bytes);
}
static int q38_trunk_enabled(void) {
const char *e=getenv("Q38_TRUNK_GPU"); return !(e&&e[0]=='0'&&!e[1]);
}
-/* offers, before qt_init: lm_head first (the placer takes it first), then the
- * layers in order so a partial placement is a prefix of the layers */
+/* the trunk table, built once: lm_head first (the placer takes it first),
+ * then the layers in order so a partial placement is a prefix of the layers.
+ * The same table feeds the CPU's int8 rows; the placer is told about the
+ * matrices only when the GPU trunk is enabled (Q38_TRUNK_GPU). */
static void q38_trunk_offer_all(Model *m) {
- if(!q38_trunk_enabled())return;
+ if(g_trunk_n)return;
+ g_trunk_offer_gpu=q38_trunk_enabled();
Cfg *c=&m->c;
q38_trunk_add(&m->lm_head,"lmhead",0);
for(int l=0;l<c->layers;l++){
@@ -1794,19 +1867,33 @@ static void q38_trunk_quantize(const Q38Weight *w,int8_t **qp,float **scp) {
}
*qp=q; *scp=sc;
}
-/* Q38_TRUNK_CPU_INT8=1: keep the int8 rows on the CPU instead (or as well),
- * so the quantization can be judged without a GPU (PPL, token parity) */
+/* The trunk on the CPU: int8 rows with one scale per row, and the BF16 copy
+ * released. The trunk is read whole on every token (3.6 G weights on the
+ * released checkpoint, more than the ten routed experts), so its bytes are
+ * the decode's floor: int8 halves them and the integer kernel keeps up with
+ * the memory. Default on; Q38_TRUNK_CPU_INT8=0 keeps the BF16 rows and the
+ * f32 kernel, the numeric reference. A matrix the tier already quantized for
+ * the GPU keeps those same rows here (prefill rows run on the CPU). */
+static int q38_trunk_cpu_int8_wanted(void) {
+ const char *e=getenv("Q38_TRUNK_CPU_INT8"); return !(e&&e[0]=='0'&&!e[1]);
+}
static void q38_trunk_cpu_int8(Model *m) {
- const char *e=getenv("Q38_TRUNK_CPU_INT8");
- if(!e||e[0]!='1'||e[1])return;
- if(!g_trunk_n) q38_trunk_offer_all(m);
- double t0=now_s(); size_t bytes=0;
+ if(!q38_trunk_cpu_int8_wanted())return;
+ q38_trunk_offer_all(m);
+ double t0=now_s(); size_t bytes=0,released=0; int n=0;
for(int i=0;i<g_trunk_n;i++){
- Q38Weight *w=g_trunk[i].w; if(w->q8)continue;
- q38_trunk_quantize(w,&w->q8,&w->q8sc); bytes+=(size_t)w->rows*w->cols;
+ Q38Weight *w=g_trunk[i].w;
+ if(!w->q8)q38_trunk_quantize(w,&w->q8,&w->q8sc);
+ bytes+=(size_t)w->rows*w->cols+(size_t)w->rows*sizeof(float); n++;
+ if(w->owns_data&&w->data){
+ /* every path that reads this matrix now goes through q8 */
+ uint64_t was=q38_weight_bytes(w);
+ free(w->data); w->data=NULL; w->owns_data=0; released+=was;
+ m->resident_weight_bytes-=was; m->resident_weight_bytes+=(size_t)w->rows*w->cols+(size_t)w->rows*sizeof(float);
+ }
}
- fprintf(stderr,"[qwen38] trunk: %d matrices int8 on the CPU (%.2f GiB) in %.1fs (Q38_TRUNK_CPU_INT8)\n",
- g_trunk_n,bytes/1073741824.0,now_s()-t0);
+ fprintf(stderr,"[qwen38] trunk: %d matrices int8 on the CPU (%.2f GiB, %.2f GiB of BF16 released) in %.1fs; Q38_TRUNK_CPU_INT8=0 keeps BF16\n",
+ n,bytes/1073741824.0,released/1073741824.0,now_s()-t0);
}
/* after qt_init: quantize and upload what the placer accepted */
static void q38_trunk_place_all(Model *m) {
@@ -1817,7 +1904,8 @@ static void q38_trunk_place_all(Model *m) {
int dev=qt_place_of(it->name,it->layer);
if(dev==QT_PLACE_CPU)continue;
int O=w->rows,I=w->cols;
- int8_t *q; float *sc; q38_trunk_quantize(w,&q,&sc);
+ if(!w->q8)q38_trunk_quantize(w,&w->q8,&w->q8sc); /* kept: the CPU answers prefill rows from the same bytes */
+ const int8_t *q=w->q8; const float *sc=w->q8sc;
int h=qt_dense_init(q,sc,I,O,dev);
if(h>=0&&getenv("Q38_TRUNK_SELFTEST")){
/* DIAG: GPU int8 GEMV against the same int8 matrix on the CPU */
@@ -1829,11 +1917,10 @@ static void q38_trunk_place_all(Model *m) {
fprintf(stderr,"[selftest] %-7s L%-2d [O=%d I=%d] ok=%d rel.err %.2e worst row %d gpu %.5g cpu %.5g\n",it->name,it->layer,O,I,ok,den>0?sqrt(num/den):-1.0,worst,yg[worst],yc[worst]);
free(x);free(yg);free(yc);
}
- free(q); free(sc);
if(h>=0){ w->gpu=h+1; placed++; placed_bytes+=(size_t)O*I; }
}
if(g_trunk_n)
- fprintf(stderr,"[qtier] qwen38 trunk: %d of %d offered matrices resident as int8 (%.2f GiB) in %.1fs; the rest stays BF16 on the CPU\n",
+ fprintf(stderr,"[qtier] qwen38 trunk: %d of %d offered matrices resident as int8 (%.2f GiB) in %.1fs; the rest answers from the CPU\n",
placed,g_trunk_n,placed_bytes/1073741824.0,now_s()-t0);
}
diff --git a/c/tests/test_qwen38_idot.c b/c/tests/test_qwen38_idot.c
new file mode 100644
index 00000000..3a683b63
--- /dev/null
+++ b/c/tests/test_qwen38_idot.c
@@ -0,0 +1,94 @@
+/* qwen38's trunk on the CPU as int8 rows met by an int8 activation in the
+ * integer kernel (idot.h), and the vector FP8 kernel for the routed experts.
+ *
+ * Pinned, with no model:
+ * - the int8 trunk is the default; Q38_TRUNK_CPU_INT8=0 is the only way off;
+ * - a BF16 matrix quantized as the loader does answers q38_weight_matmul from
+ * its int8 rows within what an int8 row and an int8 activation allow, for one
+ * row (decode) and for a batch (prefill), and keeps answering after the BF16
+ * copy is released, with the same bytes;
+ * - the vector FP8 kernel agrees with quant.h's table kernel to float
+ * summation order on a matrix with a partial last block and an odd number of
+ * rows, for one row and for a batch, and Q38_FP8_KERNEL=scalar routes the
+ * dispatch to the table kernel byte for byte. */
+#define _GNU_SOURCE
+#define QWEN38_NO_MAIN
+#include "../qwen38.c"
+#include "../compat.h" /* setenv/unsetenv: MinGW has neither */
+
+static int fails;
+static void ck(int ok,const char *what){ if(ok){printf(" ok %s\n",what);return;} printf(" FAIL %s\n",what); fails++; }
+
+static unsigned g_seed=777;
+static float rnd(void){ g_seed=g_seed*1103515245u+12345u; return ((g_seed>>8)&0xFFFF)/32768.f-1.f; }
+static double rel_gap(const float *a,const float *b,int n){
+ double worst=0,scale=1e-6;
+ for(int i=0;i<n;i++){ double d=fabs((double)a[i]-b[i]); if(d>worst)worst=d; if(fabs((double)b[i])>scale)scale=fabs((double)b[i]); }
+ return worst/scale;
+}
+static uint16_t f32_to_bf16(float f){ uint32_t u; memcpy(&u,&f,4); return (uint16_t)(u>>16); }
+
+int main(void){
+ printf("the flag\n");
+ unsetenv("Q38_TRUNK_CPU_INT8");
+ ck(q38_trunk_cpu_int8_wanted()==1,"int8 trunk on by default");
+ setenv("Q38_TRUNK_CPU_INT8","0",1);
+ ck(q38_trunk_cpu_int8_wanted()==0,"Q38_TRUNK_CPU_INT8=0 keeps BF16");
+ setenv("Q38_TRUNK_CPU_INT8","1",1);
+ ck(q38_trunk_cpu_int8_wanted()==1,"=1 still means on");
+ unsetenv("Q38_TRUNK_CPU_INT8");
+
+ printf("the int8 trunk\n");
+ {
+ enum { I=320, O=96, S=5 };
+ Q38Weight w={0}; q38_weight_reserve(&w,Q38_WEIGHT_BF16,O,I);
+ uint16_t *wb=(uint16_t*)w.data;
+ for(int64_t k=0;k<(int64_t)O*I;k++)wb[k]=f32_to_bf16(rnd());
+ float *x=malloc((size_t)S*I*sizeof(float)),*ref=malloc((size_t)S*O*sizeof(float));
+ float *y=malloc((size_t)S*O*sizeof(float)),*y2=malloc((size_t)S*O*sizeof(float));
+ for(int64_t k=0;k<(int64_t)S*I;k++)x[k]=rnd()*2.f;
+ q38_matmul_bf16(ref,x,wb,S,I,O);
+ q38_weight_matmul(y,x,&w,S,I,O);
+ ck(!memcmp(y,ref,(size_t)S*O*sizeof(float)),"without int8 rows the BF16 kernel answers, byte for byte");
+ q38_trunk_quantize(&w,&w.q8,&w.q8sc);
+ q38_weight_matmul(y,x,&w,S,I,O);
+ ck(rel_gap(y,ref,S*O)<3e-2,"int8 rows x int8 activation within 3% of the BF16 reference, 5 rows");
+ q38_weight_matmul(y2,x,&w,1,I,O);
+ ck(rel_gap(y2,ref,O)<3e-2,"same for one row");
+ /* the loader releases the BF16 copy once the rows exist */
+ free(w.data); w.data=NULL; w.owns_data=0;
+ q38_weight_matmul(y2,x,&w,S,I,O);
+ ck(!memcmp(y,y2,(size_t)S*O*sizeof(float)),"after the BF16 copy is released the int8 rows answer with the same bytes");
+ free(w.q8); free(w.q8sc); free(x); free(ref); free(y); free(y2);
+ }
+
+ printf("the vector FP8 kernel\n");
+ {
+ enum { I=200, O=7, S=5 }; /* a partial last block, an odd row count */
+ int nbo=(O+127)/128, nbi=(I+127)/128;
+ uint8_t *q=malloc((size_t)O*I); float *sc=malloc((size_t)nbo*nbi*sizeof(float));
+ for(int64_t k=0;k<(int64_t)O*I;k++){ unsigned b=(unsigned)((rnd()+1.f)*127.99f); if((b&0x7F)==0x7F)b&=0x7E; q[k]=(uint8_t)b; }
+ for(int k=0;k<nbo*nbi;k++)sc[k]=0.5f+(rnd()+1.f)*0.75f;
+ float *x=malloc((size_t)S*I*sizeof(float)),*ref=malloc((size_t)S*O*sizeof(float)),*y=malloc((size_t)S*O*sizeof(float));
+ for(int64_t k=0;k<(int64_t)S*I;k++)x[k]=rnd();
+ matmul_fp8(ref,x,q,sc,S,I,O);
+ setenv("Q38_FP8_KERNEL","scalar",1);
+ q38_matmul_fp8(y,x,q,sc,S,I,O);
+ ck(!memcmp(y,ref,(size_t)S*O*sizeof(float)),"Q38_FP8_KERNEL=scalar: the table kernel, byte for byte");
+#ifdef __AVX2__
+ q38_matmul_fp8_vec(y,x,q,sc,S,I,O);
+ ck(rel_gap(y,ref,S*O)<1e-5,"vector kernel within float summation order of the table kernel, 5 rows");
+ q38_matmul_fp8_vec(y,x,q,sc,1,I,O);
+ ck(rel_gap(y,ref,O)<1e-5,"same for one row (the fused decode-and-multiply path)");
+ float one[O]; memcpy(one,y,sizeof one);
+ q38_matmul_fp8_vec(y,x,q,sc,2,I,O);
+ ck(!memcmp(one,y,sizeof one),"the first of two rows equals the one-row result to the byte");
+#else
+ printf(" skip vector kernel: not an AVX2 build\n");
+#endif
+ free(q); free(sc); free(x); free(ref); free(y);
+ }
+ if(fails){ printf("test_qwen38_idot: %d failure(s)\n",fails); return 1; }
+ printf("OK test_qwen38_idot: int8 trunk and vector FP8 kernel\n");
+ return 0;
+}