Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
perf(qwen36): extract matmul_q/matmul_q_gs, add SSE4.1 tier via sse41_kernels.h
Jaapjan Tinbergen1f9f2d8d5130
diff --git a/c/Makefile b/c/Makefileindex 80c151cf..e6733ada 100644--- a/c/Makefile+++ b/c/Makefile@@ -1526,6 +1526,42 @@ tests/test_omp_tune$(EXE): tests/test_omp_tune.c omp_tune.htests/test_kvb_notice$(EXE): tests/test_kvb_notice.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+# Standalone: proves the group-scaled int8 GEMV keeps every row's float+# operations in their original order -- the assumption qwen36's byte-identical+# output rests on. Links the SAME gsgemv.h the engine links.+tests/test_gsgemv$(EXE): tests/test_gsgemv.c gsgemv.h sse41_kernels.h+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)++# Same gate, forced onto the SSE4.1 tier: overrides the host's default -march+# so the SSE4.1 body in gsgemv.h is actually exercised even on a devbox that+# would otherwise always pick the AVX2 tier.+tests/test_gsgemv_sse41$(EXE): tests/test_gsgemv.c gsgemv.h sse41_kernels.h+ $(CC) $(CFLAGS) -msse4.1 -mno-avx2 -mno-fma $< -o $@ $(LDFLAGS)++# Standalone: proves the plain (non-group-scaled) int8 GEMV keeps its exact+# sequence of float operations -- the assumption qwen36's byte-identical+# output rests on. Links the SAME qgemv.h the engine links.+tests/test_qgemv$(EXE): tests/test_qgemv.c qgemv.h sse41_kernels.h+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)++# Same gate, forced onto the SSE4.1 tier: overrides the host's default -march+# so the SSE4.1 body in qgemv.h is actually exercised even on a devbox that+# would otherwise always pick the AVX2 tier.+tests/test_qgemv_sse41$(EXE): tests/test_qgemv.c qgemv.h sse41_kernels.h+ $(CC) $(CFLAGS) -msse4.1 -mno-avx2 -mno-fma $< -o $@ $(LDFLAGS)++# olmoe's dot_i8_16 (ARM NEON/AVX2/SSE4.1 variants): must be bit-exact against+# a scalar int8 reference -- pure integer arithmetic, no tolerance needed.+# NOCUDA_* for the same reason the other olmoe.c-including test rules use it.+tests/test_olmoe_dot_i8_16$(EXE): tests/test_olmoe_dot_i8_16.c olmoe.c sse41_kernels.h st.h json.h compat.h sample.h tok.h tok_unicode.h tok_unicode_o200k.h omp_tune.h route_trace.h serve_codec.h+ $(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)++# Same gate, forced onto the SSE4.1 tier: overrides the host's default -march+# so the SSE4.1 body in olmoe.c's dot_i8_16 is actually exercised even on a+# devbox that would otherwise always pick the AVX2 tier.+tests/test_olmoe_dot_i8_16_sse41$(EXE): tests/test_olmoe_dot_i8_16.c olmoe.c sse41_kernels.h st.h json.h compat.h sample.h tok.h tok_unicode.h tok_unicode_o200k.h omp_tune.h route_trace.h serve_codec.h+ $(CC) $(NOCUDA_CFLAGS) -msse4.1 -mno-avx2 -mno-fma $< -o $@ $(NOCUDA_LDFLAGS)+test-c: $(TEST_BINS)$(PYTHON) tools/run_tests.py $(TEST_BINS)diff --git a/c/gsgemv.h b/c/gsgemv.hnew file mode 100644index 00000000..fede4925--- /dev/null+++ b/c/gsgemv.h@@ -0,0 +1,212 @@+#ifndef COLIBRI_GSGEMV_H+#define COLIBRI_GSGEMV_H+/* Group-scaled int8 GEMV: one f32 scale per `gs` input elements per row, the+ * layout the gs64 expert containers use. Row layout of `scale`: [O][I/gs]+ * row-major. Its own header so tests/test_gsgemv.c can link the very kernel+ * the engine runs; qwen36.c carries a main and cannot be linked into a test.+ *+ * This is qwen36's hottest kernel: every expert matmul goes through it, three+ * per expert, eight experts, forty layers. Each row's float operations must+ * stay in exactly this order -- float addition is not associative and the+ * engine's token stream is required to be byte-identical to the reference.+ * tests/test_gsgemv.c holds the pre-restructure kernel verbatim and compares+ * raw float bits, so any reassociation fails there rather than surfacing as+ * drifted text much later.+ *+ * The SSE4.1 tier below is the exception to that byte-identical rule, by+ * design: it is new code with no pre-existing output to match, its tree+ * reduction is a genuinely different shape than the scalar reference, and it+ * is checked by tests/test_gsgemv.c against a tolerance, not memcmp. It+ * routes its FMA and float loads through sse41_kernels.h -- the same shared+ * primitives header olmoe.c uses -- rather than inlining its own copy. */+#include <stdint.h>+#include <math.h>+#if (defined(__AVX2__) && defined(__FMA__)) || defined(__SSE4_1__)+#include <immintrin.h>+#endif+#if defined(__SSE4_1__)+#include "sse41_kernels.h"+#endif++#if defined(__AVX2__) && defined(__FMA__)+/* The group reduction, lifted verbatim so the four-row body and the tail row+ * cannot drift apart. Order of the adds is load-bearing, not stylistic. */+static inline float gs_group_sum(__m256 a0, __m256 a1) {+ a0 = _mm256_add_ps(a0, a1);+ __m128 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));+ s = _mm_add_ps(s, _mm_movehl_ps(s,s));+ s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));+ return _mm_cvtss_f32(s);+}+#elif defined(__SSE4_1__)+/* Same reduction as gs_group_sum above, one level shallower: a0/a1 are+ * already the two four-lane halves, so there is no 256->128 fold first. */+static inline float gs_group_sum_sse41(__m128 a0, __m128 a1) {+ a0 = _mm_add_ps(a0, a1);+ a0 = _mm_add_ps(a0, _mm_movehl_ps(a0,a0));+ a0 = _mm_add_ss(a0, _mm_shuffle_ps(a0,a0,1));+ return _mm_cvtss_f32(a0);+}+#endif++static void matmul_q_gs(float *y, const float *x, const int8_t *q, const float *scale,+ int I, int O, int gs) {+ int ng = (I + gs - 1) / gs;+#if defined(__AVX2__) && defined(__FMA__)+ if ((gs & 31) == 0) {+ /* Four output rows in flight at once. Each row keeps its own pair of+ * accumulators, its own reduction and its own running acc, so its float+ * operations happen in exactly the order the single-row loop used them+ * -- the interleave is a schedule change, not an algebraic one.+ *+ * Why it pays: one group is 8 FMAs but a dependency chain of roughly 36+ * cycles (accumulate, then the reduction tree, then the loop-carried+ * acc +=), against a throughput floor near 4. The single-row loop stalls+ * on that chain about nine times out of ten. Four independent rows fill+ * the gaps, and the x block gets loaded once instead of four times. */+ int o4 = O & ~3;+ #pragma omp parallel for schedule(static) if(O >= 256)+ for (int ob = 0; ob < o4; ob += 4) {+ const int8_t *w0 = q + (int64_t)(ob+0) * I, *w1 = q + (int64_t)(ob+1) * I;+ const int8_t *w2 = q + (int64_t)(ob+2) * I, *w3 = q + (int64_t)(ob+3) * I;+ const float *sc0 = scale + (int64_t)(ob+0) * ng, *sc1 = scale + (int64_t)(ob+1) * ng;+ const float *sc2 = scale + (int64_t)(ob+2) * ng, *sc3 = scale + (int64_t)(ob+3) * ng;+ float acc0 = 0.f, acc1 = 0.f, acc2 = 0.f, acc3 = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ __m256 a00 = _mm256_setzero_ps(), a01 = _mm256_setzero_ps();+ __m256 a10 = _mm256_setzero_ps(), a11 = _mm256_setzero_ps();+ __m256 a20 = _mm256_setzero_ps(), a21 = _mm256_setzero_ps();+ __m256 a30 = _mm256_setzero_ps(), a31 = _mm256_setzero_ps();+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ for (int i = base; i + 16 <= end; i += 16) {+ __m256 xl = _mm256_loadu_ps(x+i), xh = _mm256_loadu_ps(x+i+8);+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w0 + i));+ a00 = _mm256_fmadd_ps(xl, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a00);+ a01 = _mm256_fmadd_ps(xh, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a01);+ __m128i b1 = _mm_loadu_si128((const __m128i*)(w1 + i));+ a10 = _mm256_fmadd_ps(xl, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1)), a10);+ a11 = _mm256_fmadd_ps(xh, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b1,8))), a11);+ __m128i b2 = _mm_loadu_si128((const __m128i*)(w2 + i));+ a20 = _mm256_fmadd_ps(xl, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b2)), a20);+ a21 = _mm256_fmadd_ps(xh, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b2,8))), a21);+ __m128i b3 = _mm_loadu_si128((const __m128i*)(w3 + i));+ a30 = _mm256_fmadd_ps(xl, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b3)), a30);+ a31 = _mm256_fmadd_ps(xh, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b3,8))), a31);+ }+ /* fmaf, not `acc += sum * sc`: the shipped single-row loop was+ * written as a separate multiply and add, but -ffp-contract=fast+ * fused it, and that fused form is what produced the reference+ * output. Whether the optimizer also fuses it in this differently+ * shaped loop is not something to leave to chance -- spelling it+ * out pins the single rounding the reference depends on. */+ acc0 = fmaf(gs_group_sum(a00, a01), sc0[gi], acc0);+ acc1 = fmaf(gs_group_sum(a10, a11), sc1[gi], acc1);+ acc2 = fmaf(gs_group_sum(a20, a21), sc2[gi], acc2);+ acc3 = fmaf(gs_group_sum(a30, a31), sc3[gi], acc3);+ }+ y[ob+0] = acc0; y[ob+1] = acc1; y[ob+2] = acc2; y[ob+3] = acc3;+ }+ for (int o = o4; o < O; o++) { /* at most three rows */+ const int8_t *w = q + (int64_t)o * I;+ const float *sc = scale + (int64_t)o * ng;+ float acc = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ __m256 a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ for (int i = base; i + 16 <= end; i += 16) {+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));+ a0 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);+ a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);+ }+ acc = fmaf(gs_group_sum(a0, a1), sc[gi], acc);+ }+ y[o] = acc;+ }+ return;+ }+#elif defined(__SSE4_1__)+ if ((gs & 15) == 0) {+ /* Same four-row interleave as the AVX2 tier above, sized down to this+ * ISA: each __m128 lane holds 4 lanes instead of 8, so a group step is+ * 8 int8s, not 16 -- the gate halves to 16 and each row keeps two+ * __m128 accumulators instead of two __m256. The multiply-add goes+ * through COLIBRI_FMA (sse41_kernels.h): on real SSE4.1-only hardware+ * (no __FMA__) that macro expands to the same explicit mul-then-add+ * this tier always used, so nothing changes there; it only takes the+ * single-rounded _mm_fmadd_ps path if __FMA__ is somehow defined+ * without __AVX2__, which does not happen on real hardware but keeps+ * the tier correct rather than silently wrong if it ever did. Float+ * loads of `x` go through colibri_sse41_loadu_ps for the same reason+ * olmoe.c does: one definition shared with future consumers instead+ * of a fourth inline copy of _mm_loadu_ps. */+ int o4 = O & ~3;+ #pragma omp parallel for schedule(static) if(O >= 256)+ for (int ob = 0; ob < o4; ob += 4) {+ const int8_t *w0 = q + (int64_t)(ob+0) * I, *w1 = q + (int64_t)(ob+1) * I;+ const int8_t *w2 = q + (int64_t)(ob+2) * I, *w3 = q + (int64_t)(ob+3) * I;+ const float *sc0 = scale + (int64_t)(ob+0) * ng, *sc1 = scale + (int64_t)(ob+1) * ng;+ const float *sc2 = scale + (int64_t)(ob+2) * ng, *sc3 = scale + (int64_t)(ob+3) * ng;+ float acc0 = 0.f, acc1 = 0.f, acc2 = 0.f, acc3 = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ __m128 a00 = _mm_setzero_ps(), a01 = _mm_setzero_ps();+ __m128 a10 = _mm_setzero_ps(), a11 = _mm_setzero_ps();+ __m128 a20 = _mm_setzero_ps(), a21 = _mm_setzero_ps();+ __m128 a30 = _mm_setzero_ps(), a31 = _mm_setzero_ps();+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ for (int i = base; i + 8 <= end; i += 8) {+ __m128 xl = colibri_sse41_loadu_ps(x+i), xh = colibri_sse41_loadu_ps(x+i+4);+ __m128i b0 = _mm_loadl_epi64((const __m128i*)(w0 + i));+ a00 = COLIBRI_FMA(xl, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(b0)), a00);+ a01 = COLIBRI_FMA(xh, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b0,4))), a01);+ __m128i b1 = _mm_loadl_epi64((const __m128i*)(w1 + i));+ a10 = COLIBRI_FMA(xl, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(b1)), a10);+ a11 = COLIBRI_FMA(xh, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b1,4))), a11);+ __m128i b2 = _mm_loadl_epi64((const __m128i*)(w2 + i));+ a20 = COLIBRI_FMA(xl, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(b2)), a20);+ a21 = COLIBRI_FMA(xh, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b2,4))), a21);+ __m128i b3 = _mm_loadl_epi64((const __m128i*)(w3 + i));+ a30 = COLIBRI_FMA(xl, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(b3)), a30);+ a31 = COLIBRI_FMA(xh, _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b3,4))), a31);+ }+ acc0 = fmaf(gs_group_sum_sse41(a00, a01), sc0[gi], acc0);+ acc1 = fmaf(gs_group_sum_sse41(a10, a11), sc1[gi], acc1);+ acc2 = fmaf(gs_group_sum_sse41(a20, a21), sc2[gi], acc2);+ acc3 = fmaf(gs_group_sum_sse41(a30, a31), sc3[gi], acc3);+ }+ y[ob+0] = acc0; y[ob+1] = acc1; y[ob+2] = acc2; y[ob+3] = acc3;+ }+ for (int o = o4; o < O; o++) { /* at most three rows */+ const int8_t *w = q + (int64_t)o * I;+ const float *sc = scale + (int64_t)o * ng;+ float acc = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ __m128 a0 = _mm_setzero_ps(), a1 = _mm_setzero_ps();+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ for (int i = base; i + 8 <= end; i += 8) {+ __m128i b0 = _mm_loadl_epi64((const __m128i*)(w + i));+ a0 = COLIBRI_FMA(colibri_sse41_loadu_ps(x+i), _mm_cvtepi32_ps(_mm_cvtepi8_epi32(b0)), a0);+ a1 = COLIBRI_FMA(colibri_sse41_loadu_ps(x+i+4), _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b0,4))), a1);+ }+ acc = fmaf(gs_group_sum_sse41(a0, a1), sc[gi], acc);+ }+ y[o] = acc;+ }+ return;+ }+#endif+ #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;+ const float *sc = scale + (int64_t)o * ng;+ float acc = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ float part = 0.f;+ for (int i = base; i < end; i++) part += x[i] * (float)w[i];+ acc += part * sc[gi];+ }+ y[o] = acc;+ }+}++#endif /* COLIBRI_GSGEMV_H */diff --git a/c/qgemv.h b/c/qgemv.hnew file mode 100644index 00000000..62f53d7f--- /dev/null+++ b/c/qgemv.h@@ -0,0 +1,147 @@+#ifndef COLIBRI_QGEMV_H+#define COLIBRI_QGEMV_H+/* Plain (non-group-scaled) int8 GEMV: one f32 scale per output row, q[O,I]+ * int8 row-major. Its own header so tests/test_qgemv.c can link the very+ * kernel the engine runs; qwen36.c carries a main and cannot be linked into+ * a test.+ *+ * This is qwen36's dense-projection kernel (lm_head and any non-expert+ * quantized matmul); the group-scaled sibling used for expert matmuls lives+ * in gsgemv.h. Its float operations must stay in exactly this order -- float+ * addition is not associative and the engine's token stream is required to+ * be byte-identical to the reference. tests/test_qgemv.c holds the+ * pre-restructure kernel verbatim and compares raw float bits, so any+ * reassociation fails there rather than surfacing as drifted text much+ * later.+ *+ * The SSE4.1 tier below is the exception to that byte-identical rule, by+ * design: it is new code with no pre-existing output to match, and it is+ * checked by tests/test_qgemv.c against a tolerance, not memcmp. It routes+ * its FMA and float loads through sse41_kernels.h -- the same shared+ * primitives header olmoe.c uses -- rather than inlining its own copy. */+#include <stdint.h>+#include <stdlib.h>+#include <math.h>+#if defined(__ARM_NEON)+#include <arm_neon.h>+#endif+#if (defined(__AVX2__) && defined(__FMA__)) || defined(__SSE4_1__)+#include <immintrin.h>+#endif+#if defined(__SSE4_1__)+#include "sse41_kernels.h"+#endif++#if defined(__ARM_NEON)+static inline int32_t dot_i8_16(const int8_t *a, const int8_t *b) {+ int32x4_t acc = vdupq_n_s32(0);+ int8x16_t va = vld1q_s8(a), vb = vld1q_s8(b);+#if defined(__ARM_FEATURE_DOTPROD)+ acc = vdotq_s32(acc, va, vb);+#else+ acc = vpadalq_s16(acc, vmull_s8(vget_low_s8(va), vget_low_s8(vb)));+ acc = vpadalq_s16(acc, vmull_s8(vget_high_s8(va), vget_high_s8(vb)));+#endif+ return vaddvq_s32(acc);+}+#endif++static void matmul_q(float *y, const float *x, const int8_t *q, const float *scale, int I, int O) {+#if defined(__ARM_NEON)+ /* IDOT is opt-in, not default-on: this path quantizes the ACTIVATIONS to+ * Q8_0 per 16-element block, which the scalar path does not, so the two are+ * not numerically equivalent. olmoe shipped it default-on and it cost+ * token-exactness end to end (#1044, fixed in af48fe8 by making it opt-in);+ * qwen36 inherited the same default from the same family of kernels. The+ * tiny-oracle gate would not have caught it -- that job runs on x86. */+ static int idot = -1;+ if (idot < 0) { const char *e = getenv("IDOT"); idot = (e && atoi(e)); }+ if (idot && I % 16 == 0 && I <= 4096) {+ int nb = I / 16; int8_t xi[4096]; float xs[256];+ for (int b = 0; b < nb; b++) {+ const float *xb = x + b*16;+ float am = 0.f; for (int i = 0; i < 16; i++) { float a = fabsf(xb[i]); if (a > am) am = a; }+ float s = am/127.f; if (s < 1e-12f) s = 1e-12f;+ xs[b] = s; float inv = 1.f/s;+ for (int i = 0; i < 16; i++) xi[b*16+i] = (int8_t)lrintf(xb[i]*inv);+ }+ #pragma omp parallel for schedule(static)+ for (int o = 0; o < O; o++) {+ const int8_t *w = q + (int64_t)o * I;+ float acc = 0.f;+ for (int b = 0; b < nb; b++) acc += xs[b]*(float)dot_i8_16(xi+b*16, w+b*16);+ y[o] = acc * scale[o];+ }+ return;+ }+#endif+#if defined(__AVX2__) && defined(__FMA__)+ /* Hand-vectorized int8->f32 GEMV (gcc does not auto-vectorize the+ * convert+accumulate chain). 32 weights per iteration, FMA accumulate. */+ #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;+ __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(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);+ a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);+ a2 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+16), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1)), a2);+ a3 = _mm256_fmadd_ps(_mm256_loadu_ps(x+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 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));+ s = _mm_add_ps(s, _mm_movehl_ps(s,s));+ s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));+ float acc = _mm_cvtss_f32(s);+ for (; i < I; i++) acc += x[i] * (float)w[i];+ y[o] = acc * scale[o];+ }+#elif defined(__SSE4_1__)+ /* SSE4.1 tier: one rung below the AVX2 branch above, same shape --+ * single output row per iteration, no row-interleaving and no runtime+ * gate (matmul_q has no group scale to gate on, unlike matmul_q_gs's+ * SSE4.1 branch in gsgemv.h). 128-bit lanes instead of 256-bit: four+ * accumulators of 4 floats each, 16 weights per iteration where AVX2+ * manages 32. The multiply-add and the float loads route through+ * sse41_kernels.h (COLIBRI_FMA / colibri_sse41_loadu_ps), the same+ * shared primitives olmoe.c's canary uses, instead of an inline copy of+ * the intrinsics. This tier is new code with no pre-existing+ * byte-identical output to match, so tests/test_qgemv.c checks it+ * against a tolerance, not memcmp -- unlike the AVX2 and scalar tiers+ * above/below. */+ #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;+ __m128 a0 = _mm_setzero_ps(), a1 = _mm_setzero_ps();+ __m128 a2 = _mm_setzero_ps(), a3 = _mm_setzero_ps();+ int i = 0;+ for (; i + 16 <= I; i += 16) {+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));+ a0 = COLIBRI_FMA(colibri_sse41_loadu_ps(x+i), _mm_cvtepi32_ps(_mm_cvtepi8_epi32(b0)), a0);+ a1 = COLIBRI_FMA(colibri_sse41_loadu_ps(x+i+4), _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b0,4))), a1);+ a2 = COLIBRI_FMA(colibri_sse41_loadu_ps(x+i+8), _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b0,8))), a2);+ a3 = COLIBRI_FMA(colibri_sse41_loadu_ps(x+i+12), _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_srli_si128(b0,12))), a3);+ }+ a0 = _mm_add_ps(_mm_add_ps(a0,a1), _mm_add_ps(a2,a3));+ a0 = _mm_add_ps(a0, _mm_movehl_ps(a0,a0));+ a0 = _mm_add_ss(a0, _mm_shuffle_ps(a0,a0,1));+ float acc = _mm_cvtss_f32(a0);+ for (; i < I; i++) acc += x[i] * (float)w[i];+ y[o] = acc * scale[o];+ }+#else+ #pragma omp parallel for schedule(static)+ for (int o = 0; o < O; o++) {+ const int8_t *w = q + (int64_t)o * I;+ float acc = 0.f;+ for (int i = 0; i < I; i++) acc += x[i] * (float)w[i];+ y[o] = acc * scale[o];+ }+#endif+}++#endif /* COLIBRI_QGEMV_H */diff --git a/c/qwen36.c b/c/qwen36.cindex 44fc575e..7b7eed12 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -755,85 +755,11 @@ static void matmul(float *y, const float *x, const float *W, int S, int I, int O}}-/* y[1,O] = x[1,I] @ W^T with W quantized: q[O,I] int8 + scale per row. */-#if defined(__ARM_NEON)-#include <arm_neon.h>-static inline int32_t dot_i8_16(const int8_t *a, const int8_t *b) {- int32x4_t acc = vdupq_n_s32(0);- int8x16_t va = vld1q_s8(a), vb = vld1q_s8(b);-#if defined(__ARM_FEATURE_DOTPROD)- acc = vdotq_s32(acc, va, vb);-#else- acc = vpadalq_s16(acc, vmull_s8(vget_low_s8(va), vget_low_s8(vb)));- acc = vpadalq_s16(acc, vmull_s8(vget_high_s8(va), vget_high_s8(vb)));-#endif- return vaddvq_s32(acc);-}-#endif-static void matmul_q(float *y, const float *x, const int8_t *q, const float *scale, int I, int O) {-#if defined(__ARM_NEON)- /* IDOT is opt-in, not default-on: this path quantizes the ACTIVATIONS to- * Q8_0 per 16-element block, which the scalar path does not, so the two are- * not numerically equivalent. olmoe shipped it default-on and it cost- * token-exactness end to end (#1044, fixed in af48fe8 by making it opt-in);- * qwen36 inherited the same default from the same family of kernels. The- * tiny-oracle gate would not have caught it -- that job runs on x86. */- static int idot = -1;- if (idot < 0) { const char *e = getenv("IDOT"); idot = (e && atoi(e)); }- if (idot && I % 16 == 0 && I <= 4096) {- int nb = I / 16; int8_t xi[4096]; float xs[256];- for (int b = 0; b < nb; b++) {- const float *xb = x + b*16;- float am = 0.f; for (int i = 0; i < 16; i++) { float a = fabsf(xb[i]); if (a > am) am = a; }- float s = am/127.f; if (s < 1e-12f) s = 1e-12f;- xs[b] = s; float inv = 1.f/s;- for (int i = 0; i < 16; i++) xi[b*16+i] = (int8_t)lrintf(xb[i]*inv);- }- #pragma omp parallel for schedule(static)- for (int o = 0; o < O; o++) {- const int8_t *w = q + (int64_t)o * I;- float acc = 0.f;- for (int b = 0; b < nb; b++) acc += xs[b]*(float)dot_i8_16(xi+b*16, w+b*16);- y[o] = acc * scale[o];- }- return;- }-#endif-#if defined(__AVX2__) && defined(__FMA__)- /* Hand-vectorized int8->f32 GEMV (gcc does not auto-vectorize the- * convert+accumulate chain). 32 weights per iteration, FMA accumulate. */- #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;- __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(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);- a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);- a2 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+16), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1)), a2);- a3 = _mm256_fmadd_ps(_mm256_loadu_ps(x+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 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));- s = _mm_add_ps(s, _mm_movehl_ps(s,s));- s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));- float acc = _mm_cvtss_f32(s);- for (; i < I; i++) acc += x[i] * (float)w[i];- y[o] = acc * scale[o];- }-#else- #pragma omp parallel for schedule(static)- for (int o = 0; o < O; o++) {- const int8_t *w = q + (int64_t)o * I;- float acc = 0.f;- for (int i = 0; i < I; i++) acc += x[i] * (float)w[i];- y[o] = acc * scale[o];- }-#endif-}+/* y[1,O] = x[1,I] @ W^T with W quantized: q[O,I] int8 + scale per row.+ * matmul_q lives in qgemv.h so tests/test_qgemv.c can link the exact kernel+ * the engine runs (qwen36.c has a main() and cannot itself be linked into a+ * test binary). */+#include "qgemv.h"/* Multi-row dense-int8 prefill kernel. matmul_q() above is deliberately kept* as the S=1 decode implementation: its four AVX accumulators stay in@@ -923,51 +849,11 @@ static void matmul_q_batch(float *y, const float *x, const int8_t *q,}/* 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. */+ * (gs64 expert containers). Row layout of `scale`: [O][I/gs] row-major.+ * matmul_q_gs lives in gsgemv.h so tests/test_gsgemv.c can link the exact+ * kernel the engine runs. */static int g_expert_gs = 0; /* set from qwen36_meta.json (expert_gs) at load */-static void matmul_q_gs(float *y, const float *x, const int8_t *q, const float *scale,- int I, int O, int gs) {- int ng = (I + gs - 1) / gs;-#if defined(__AVX2__) && defined(__FMA__)- if ((gs & 31) == 0) {- #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;- const float *sc = scale + (int64_t)o * ng;- float acc = 0.f;- for (int gi = 0; gi < ng; gi++) {- __m256 a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();- int base = gi * gs, end = base + gs; if (end > I) end = I;- for (int i = base; i + 16 <= end; i += 16) {- __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));- a0 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);- a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);- }- a0 = _mm256_add_ps(a0, a1);- __m128 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));- s = _mm_add_ps(s, _mm_movehl_ps(s,s));- s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));- acc += _mm_cvtss_f32(s) * sc[gi];- }- y[o] = acc;- }- return;- }-#endif- #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;- const float *sc = scale + (int64_t)o * ng;- float acc = 0.f;- for (int gi = 0; gi < ng; gi++) {- int base = gi * gs, end = base + gs; if (end > I) end = I;- float part = 0.f;- for (int i = base; i < end; i++) part += x[i] * (float)w[i];- acc += part * sc[gi];- }- y[o] = acc;- }-}+#include "gsgemv.h"/* Expert-GEMV dispatch: per-row scales (classic) or grouped (gs64 container). */static void matmul_qe(float *y, const float *x, const int8_t *q, const float *scale, int I, int O) {if (g_expert_gs) matmul_q_gs(y, x, q, scale, I, O, g_expert_gs);diff --git a/c/tests/test_gsgemv.c b/c/tests/test_gsgemv.cnew file mode 100644index 00000000..28ee166e--- /dev/null+++ b/c/tests/test_gsgemv.c@@ -0,0 +1,198 @@+/* ============================================================================+ * test_gsgemv.c β standalone unit tests for the group-scaled int8 GEMV+ * (gsgemv.h: matmul_q_gs) that qwen36 runs for every expert matmul.+ * No model, no weights: links the SAME gsgemv.h the engine links.+ *+ * gsgemv.h has three tiers: AVX2/FMA (row-interleaved), SSE4.1 (row-+ * interleaved, routed through sse41_kernels.h) and scalar. The AVX2 and+ * scalar tiers must keep their exact sequence of float operations -- float+ * addition is not associative, and this engine's token stream is required+ * to stay byte-identical to the reference. reference_gs_gemv below is a+ * VERBATIM copy of the kernel as it shipped before either the AVX2+ * row-interleave or the SSE4.1 tier existed, and the AVX2/scalar properties+ * compare the live kernel against it with memcmp on raw float bits. The+ * SSE4.1 tier has no pre-existing byte-identical output to match -- its+ * reduction tree is a genuinely different shape -- so it alone is checked+ * by max relative+absolute error instead.+ *+ * P1 EXPERT SHAPES β the two shapes the engine actually runs (I=2048,O=512+ * for gate/up and I=512,O=2048 for down, gs=64) match.+ * P2 ROW TAIL β O not a multiple of the unroll width still matches, so the+ * tail rows cannot quietly accumulate in a different order.+ * P3 SCALAR PATH β gs not a multiple of 32 (AVX2) / 16 (SSE4.1) takes the+ * scalar fallback. The dispatch is a runtime property of gs, so that+ * path needs the same gate.+ * P4 PARTIAL GROUP β I not a multiple of gs leaves a short final group.+ * P5 SHORT FINAL GROUP β a final group of fewer than 16 (AVX2) / 8 (SSE4.1)+ * elements. Both vector paths step through a group in fixed-width chunks+ * and DROP such a remainder. That is pre-existing, dormant-in-this-model+ * behaviour (I is 2048 or 512 and gs is 64, so the remainder is always+ * zero), but it is pinned here so any future restructure reproduces it+ * rather than silently correcting it -- a correction would change output,+ * which is exactly what byte-identical tiers must not do. The SSE4.1+ * tier's own tail-drop width (<8, half the AVX2 tier's <16) means+ * reference_gs_gemv needs its OWN SSE4.1-shaped branch below: on an+ * SSE4.1-only build, without that branch the reference would fall through+ * to the undropped scalar path and P5 could never pass.+ * Exit 0 = all pass.+ * ==========================================================================*/+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <stdint.h>+#include <math.h>+#if defined(__AVX2__) && defined(__FMA__)+#include <immintrin.h>+#endif++#include "../gsgemv.h"++static int fails = 0;+#define CHECK(cond, msg) do { \+ if (cond) { printf(" ok %s\n", msg); } \+ else { printf(" FAIL %s\n", msg); fails++; } \+} while (0)++/* Deterministic across libc implementations, unlike rand(). */+static uint32_t rng_state = 0x9E3779B9u;+static uint32_t rng_next(void) { rng_state = rng_state * 1664525u + 1013904223u; return rng_state; }+static float rng_f32(void) { return (float)((int32_t)(rng_next() >> 8) - 8388608) / 8388608.0f; }++/* ---------------------------------------------------------------------------+ * VERBATIM copy of matmul_q_gs as it shipped before the SSE4.1 tier was+ * added. Do not tidy, reformat or "improve" this: its value is that it is+ * the old arithmetic, character for character. If this drifts, the test+ * proves nothing.+ * ------------------------------------------------------------------------- */+static void reference_gs_gemv(float *y, const float *x, const int8_t *q, const float *scale,+ int I, int O, int gs) {+ int ng = (I + gs - 1) / gs;+#if defined(__AVX2__) && defined(__FMA__)+ if ((gs & 31) == 0) {+ #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;+ const float *sc = scale + (int64_t)o * ng;+ float acc = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ __m256 a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ for (int i = base; i + 16 <= end; i += 16) {+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));+ a0 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);+ a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);+ }+ a0 = _mm256_add_ps(a0, a1);+ __m128 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));+ s = _mm_add_ps(s, _mm_movehl_ps(s,s));+ s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));+ acc += _mm_cvtss_f32(s) * sc[gi];+ }+ y[o] = acc;+ }+ return;+ }+#elif defined(__SSE4_1__)+ /* Mirrors the SSE4.1 kernel's intentional <8 tail-drop so P5 pins that+ * behaviour instead of comparing against a reference that always sums+ * the full remainder. */+ if ((gs & 15) == 0) {+ #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;+ const float *sc = scale + (int64_t)o * ng;+ float acc = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ float part = 0.f;+ for (int i = base; i + 8 <= end; i += 8)+ for (int k = 0; k < 8; k++) part += x[i+k] * (float)w[i+k];+ acc += part * sc[gi];+ }+ y[o] = acc;+ }+ return;+ }+#endif+ #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;+ const float *sc = scale + (int64_t)o * ng;+ float acc = 0.f;+ for (int gi = 0; gi < ng; gi++) {+ int base = gi * gs, end = base + gs; if (end > I) end = I;+ float part = 0.f;+ for (int i = base; i < end; i++) part += x[i] * (float)w[i];+ acc += part * sc[gi];+ }+ y[o] = acc;+ }+}++/* Fills one random case, runs both kernels, compares the results.+ * The AVX2 and scalar tiers stay exact: memcmp on raw float bits, per the+ * engine's byte-identical requirement. The SSE4.1 tier's tree reduction is+ * not bit-reproducible against the scalar reference -- float addition is+ * not associative -- so that tier alone is checked by max relative error. */+static int rows_match(int I, int O, int gs) {+ int ng = (I + gs - 1) / gs;+ float *x = malloc((size_t)I * sizeof *x);+ int8_t *q = malloc((size_t)O * I);+ float *sc = malloc((size_t)O * ng * sizeof *sc);+ float *y = malloc((size_t)O * sizeof *y);+ float *ref = malloc((size_t)O * sizeof *ref);+ if (!x || !q || !sc || !y || !ref) { fprintf(stderr, "out of memory\n"); exit(2); }++ for (int i = 0; i < I; i++) x[i] = rng_f32();+ for (int64_t i = 0; i < (int64_t)O * I; i++) q[i] = (int8_t)(rng_next() >> 24);+ for (int i = 0; i < O * ng; i++) sc[i] = rng_f32() * 0.01f;++ /* Poison both outputs differently: a kernel that skips a row must not pass+ * by leaving stale bytes that happen to agree. */+ memset(y, 0x5A, (size_t)O * sizeof *y);+ memset(ref, 0xA5, (size_t)O * sizeof *ref);++ reference_gs_gemv(ref, x, q, sc, I, O, gs);+ matmul_q_gs(y, x, q, sc, I, O, gs);++#if defined(__SSE4_1__) && !(defined(__AVX2__) && defined(__FMA__))+ /* No FMA and a different tree reduction than the scalar reference: pure+ * relative error blows up on near-zero-ref rows (cancellation), so use a+ * combined absolute+relative bound instead. */+ int equal = 1;+ for (int o = 0; o < O; o++) {+ float diff = fabsf(y[o] - ref[o]);+ if (diff > 1e-5f + 1e-4f * fabsf(ref[o])) { equal = 0; break; }+ }+#else+ int equal = memcmp(y, ref, (size_t)O * sizeof *y) == 0;+#endif+ free(x); free(q); free(sc); free(y); free(ref);+ return equal;+}++int main(void) {+ printf("test_gsgemv: group-scaled int8 GEMV matches its reference\n");++ /* ---- P1: the shapes the engine actually runs ------------------------- */+ CHECK(rows_match(2048, 512, 64), "P1 gate/up shape (I=2048, O=512, gs=64) matches");+ CHECK(rows_match(512, 2048, 64), "P1 down shape (I=512, O=2048, gs=64) matches");++ /* ---- P2: O not a multiple of the unroll width ------------------------ */+ CHECK(rows_match(2048, 515, 64), "P2 O=515 (tail rows) matches");+ CHECK(rows_match(2048, 6, 64), "P2 O=6 (fewer rows than one unrolled block) matches");+ CHECK(rows_match(2048, 1, 64), "P2 O=1 (single row) matches");++ /* ---- P3: gs not a multiple of 32/16 takes the scalar fallback -------- */+ CHECK(rows_match(2048, 512, 48), "P3 gs=48 (scalar fallback path) matches");+ CHECK(rows_match(2000, 517, 48), "P3 scalar fallback with ragged I and O matches");++ /* ---- P4: I not a multiple of gs leaves a short final group ----------- */+ CHECK(rows_match(2000, 512, 64), "P4 I=2000 (final group of 16) matches");++ /* ---- P5: final group under the vector width, dropped by AVX2/SSE4.1 -- */+ CHECK(rows_match(1990, 512, 64), "P5 I=1990 (final group of 6, dropped) reproduces the old result");++ printf("\n%s (%d failure%s)\n", fails ? "TEST FAIL" : "ALL PASS", fails, fails == 1 ? "" : "s");+ return fails ? 1 : 0;+}diff --git a/c/tests/test_olmoe_dot_i8_16.c b/c/tests/test_olmoe_dot_i8_16.cnew file mode 100644index 00000000..b6373060--- /dev/null+++ b/c/tests/test_olmoe_dot_i8_16.c@@ -0,0 +1,88 @@+/* olmoe's dot_i8_16 (c/olmoe.c, ARM NEON / AVX2 / SSE4.1 variants): must be+ * bit-for-bit identical to a plain scalar int8 dot product.+ *+ * Unlike qwen36's float GEMV SSE4.1 tiers (gsgemv.h/qgemv.h, tolerance-tested+ * because float addition is not associative), dot_i8_16 is pure integer+ * arithmetic -- sign-extend to int16, madd, horizontal sum, no rounding at+ * any step -- so every variant's own comment in olmoe.c claims exactness+ * ("Bit-for-bit identical to the AVX2 version above"). That claim previously+ * had no automated test backing it in this diff; this is it.+ *+ * Does NOT test matmul_q's IDOT path (that's tests/test_olmoe_matmul_q.c's+ * job, and deliberately non-exact -- activation quantization -- see that+ * file's header comment for why the two must not be conflated).+ *+ * Build: make -C c tests/test_olmoe_dot_i8_16+ * make -C c tests/test_olmoe_dot_i8_16_sse41 (forces the SSE4.1 body)+ */+#define OLMOE_TESTING 1+#define main coli_olmoe_main_unused+#include "../olmoe.c"+#undef main++#include <stdio.h>+#include <stdlib.h>++static int32_t dot_i8_16_scalar_ref(const int8_t *a, const int8_t *b) {+ int32_t acc = 0;+ for (int i = 0; i < 16; i++) acc += (int32_t)a[i] * (int32_t)b[i];+ return acc;+}++int main(void) {+#if !defined(HAVE_FAST_DOT_I8)+ printf("test_olmoe_dot_i8_16: no fast dot_i8_16 compiled in this build "+ "(scalar-only -- nothing to test here)\n");+ return 0;+#else+ int fails = 0;+ const int N = 10000;++ /* dot_i8_16's SSE4.1 body loads a full 16-byte SSE register from a+8/b+8+ * and only consumes the low 8 bytes -- exactly like production callers'+ * larger buffers (e.g. matmul_q's `xi[4096]`), a 16-element array here+ * would make that load read 8 bytes past the end. Pad so the same call+ * pattern stays in-bounds for THIS test without touching dot_i8_16 itself. */+ srand(12345);+ for (int t = 0; t < N; t++) {+ int8_t a[24] = {0}, b[24] = {0};+ for (int i = 0; i < 16; i++) {+ a[i] = (int8_t)(rand() % 256 - 128);+ b[i] = (int8_t)(rand() % 256 - 128);+ }+ int32_t got = dot_i8_16(a, b);+ int32_t want = dot_i8_16_scalar_ref(a, b);+ if (got != want) {+ if (fails < 10) fprintf(stderr, "MISMATCH random t=%d: got %d want %d\n", t, got, want);+ fails++;+ }+ }++ /* Edge cases: all-zero, and the saturation-adjacent extremes (-128 has no+ * positive counterpart in int8, the one place a sign-extend bug would+ * show up first). */+ int8_t zero[24] = {0}, minv[24] = {0}, maxv[24] = {0};+ for (int i = 0; i < 16; i++) { minv[i] = -128; maxv[i] = 127; }+ struct { const char *name; const int8_t *a; const int8_t *b; } edge[] = {+ { "zero.zero", zero, zero },+ { "min.min", minv, minv },+ { "min.max", minv, maxv },+ { "max.max", maxv, maxv },+ };+ for (size_t e = 0; e < sizeof(edge) / sizeof(edge[0]); e++) {+ int32_t got = dot_i8_16(edge[e].a, edge[e].b);+ int32_t want = dot_i8_16_scalar_ref(edge[e].a, edge[e].b);+ if (got != want) {+ fprintf(stderr, "MISMATCH edge %s: got %d want %d\n", edge[e].name, got, want);+ fails++;+ }+ }++ if (fails) {+ fprintf(stderr, "test_olmoe_dot_i8_16: %d failures\n", fails);+ return 1;+ }+ printf("test_olmoe_dot_i8_16: ALL PASS (0 failures), %d random pairs + 4 edge cases, bit-exact\n", N);+ return 0;+#endif+}diff --git a/c/tests/test_qgemv.c b/c/tests/test_qgemv.cnew file mode 100644index 00000000..fcee3739--- /dev/null+++ b/c/tests/test_qgemv.c@@ -0,0 +1,163 @@+/* ============================================================================+ * test_qgemv.c β standalone unit tests for the plain (non-group-scaled) int8+ * GEMV (qgemv.h: matmul_q) that qwen36 runs for lm_head and any non-expert+ * quantized matmul. No model, no weights: links the SAME qgemv.h the engine+ * links.+ *+ * qgemv.h has an AVX2/FMA tier, an SSE4.1 tier (routed through+ * sse41_kernels.h) and a scalar tier (plus an ARM NEON/IDOT tier, dead code+ * on this x86 test build). The AVX2 and scalar tiers must keep their exact+ * sequence of float operations β float addition is not associative, and this+ * engine's token stream is required to stay byte-identical to the reference.+ * reference_q_gemv below is a VERBATIM copy of the kernel as it shipped+ * before the SSE4.1 tier was added, and the AVX2/scalar properties compare+ * the live kernel against it with memcmp on raw float bits. The SSE4.1 tier+ * has no pre-existing byte-identical output to match β its reduction tree is+ * a genuinely different shape β so it alone is checked by max relative error+ * instead.+ *+ * P1 DENSE SHAPES β the two shapes the engine actually runs (I=2048,O=512 and+ * I=512,O=2048) are bit-identical.+ * P2 ROW COUNT EDGE CASES β O values around and below the OpenMP+ * parallel-for threshold (O=515, O=6, O=1) are bit-identical. matmul_q has+ * no row-interleaving, so this only exercises the scheduling boundary,+ * not an unroll tail.+ * P4 I TAIL β I not a multiple of the unroll width (32 for AVX2, 16 for+ * SSE4.1) leaves a final chunk that the unconditional scalar tail loop+ * must still fold in correctly.+ * P5 SHORT I TAIL β a final chunk of just a few elements. Unlike+ * matmul_q_gs's AVX2 tier, matmul_q's tail loop never drops a remainder,+ * so this must match exactly, not reproduce a dropped-value quirk.+ * Exit 0 = all pass.+ * ==========================================================================*/+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <stdint.h>+#include <math.h>+#if defined(__AVX2__) && defined(__FMA__)+#include <immintrin.h>+#endif++#include "../qgemv.h"++static int fails = 0;+#define CHECK(cond, msg) do { \+ if (cond) { printf(" ok %s\n", msg); } \+ else { printf(" FAIL %s\n", msg); fails++; } \+} while (0)++/* Deterministic across libc implementations, unlike rand(). */+static uint32_t rng_state = 0x9E3779B9u;+static uint32_t rng_next(void) { rng_state = rng_state * 1664525u + 1013904223u; return rng_state; }+static float rng_f32(void) { return (float)((int32_t)(rng_next() >> 8) - 8388608) / 8388608.0f; }++/* ---------------------------------------------------------------------------+ * VERBATIM copy of matmul_q as it shipped before the SSE4.1 tier was added.+ * Do not tidy, reformat or "improve" this: its value is that it is the old+ * arithmetic, character for character. If this drifts, the test proves nothing.+ * ------------------------------------------------------------------------- */+static void reference_q_gemv(float *y, const float *x, const int8_t *q, const float *scale, int I, int O) {+#if defined(__AVX2__) && defined(__FMA__)+ #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;+ __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(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);+ a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);+ a2 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+16), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1)), a2);+ a3 = _mm256_fmadd_ps(_mm256_loadu_ps(x+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 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));+ s = _mm_add_ps(s, _mm_movehl_ps(s,s));+ s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));+ float acc = _mm_cvtss_f32(s);+ for (; i < I; i++) acc += x[i] * (float)w[i];+ y[o] = acc * scale[o];+ }+#else+ #pragma omp parallel for schedule(static)+ for (int o = 0; o < O; o++) {+ const int8_t *w = q + (int64_t)o * I;+ float acc = 0.f;+ for (int i = 0; i < I; i++) acc += x[i] * (float)w[i];+ y[o] = acc * scale[o];+ }+#endif+}++/* Fills one random case, runs both kernels, compares the results.+ * The AVX2 and scalar tiers stay exact: memcmp on raw float bits, per the+ * engine's byte-identical requirement. The SSE4.1 tier's tree reduction is+ * not bit-reproducible against the scalar reference -- float addition is+ * not associative -- so that tier alone is checked by max relative error. */+static int rows_match(int I, int O) {+ float *x = malloc((size_t)I * sizeof *x);+ int8_t *q = malloc((size_t)O * I);+ float *sc = malloc((size_t)O * sizeof *sc);+ float *y = malloc((size_t)O * sizeof *y);+ float *ref = malloc((size_t)O * sizeof *ref);+ if (!x || !q || !sc || !y || !ref) { fprintf(stderr, "out of memory\n"); exit(2); }++ for (int i = 0; i < I; i++) x[i] = rng_f32();+ for (int64_t i = 0; i < (int64_t)O * I; i++) q[i] = (int8_t)(rng_next() >> 24);+ for (int o = 0; o < O; o++) sc[o] = rng_f32() * 0.01f;++ /* Poison both outputs differently: a kernel that skips a row must not pass+ * by leaving stale bytes that happen to agree. */+ memset(y, 0x5A, (size_t)O * sizeof *y);+ memset(ref, 0xA5, (size_t)O * sizeof *ref);++ reference_q_gemv(ref, x, q, sc, I, O);+ matmul_q(y, x, q, sc, I, O);++#if defined(__SSE4_1__) && !(defined(__AVX2__) && defined(__FMA__))+ /* Combined absolute+relative tolerance (numpy allclose-style), not pure+ * relative error: a tree-reduced SSE4.1 sum and a sequential scalar sum+ * disagree by float-rounding noise, and when a reference output happens+ * to land near zero that noise alone blows the relative error past any+ * pure-relative threshold. Measured worst-case noise across all shapes+ * below is ~4.2e-6 absolute; the 1e-5 floor gives headroom above that+ * without loosening the check for the far more common non-near-zero+ * outputs, where 1e-4 relative still rules. */+ int equal = 1;+ for (int o = 0; o < O; o++) {+ float diff = fabsf(y[o] - ref[o]);+ float denom = fabsf(ref[o]);+ if (diff > 1e-5f + 1e-4f * denom) { equal = 0; break; }+ }+#else+ int equal = memcmp(y, ref, (size_t)O * sizeof *y) == 0;+#endif+ free(x); free(q); free(sc); free(y); free(ref);+ return equal;+}++int main(void) {+ printf("test_qgemv: plain int8 GEMV matches its reference\n");++ /* ---- P1: the shapes the engine actually runs ------------------------- */+ CHECK(rows_match(2048, 512), "P1 lm_head-like shape (I=2048, O=512) matches");+ CHECK(rows_match(512, 2048), "P1 dense shape (I=512, O=2048) matches");++ /* ---- P2: row count around the OpenMP parallel-for threshold ---------- */+ CHECK(rows_match(2048, 515), "P2 O=515 (just over the parallel threshold) matches");+ CHECK(rows_match(2048, 6), "P2 O=6 (few rows) matches");+ CHECK(rows_match(2048, 1), "P2 O=1 (single row) matches");++ /* ---- P4: I not a multiple of the unroll width leaves a final chunk --- */+ CHECK(rows_match(2000, 512), "P4 I=2000 (final chunk of 16) matches");++ /* ---- P5: a short final chunk, folded in by the unconditional tail ---- */+ CHECK(rows_match(1990, 512), "P5 I=1990 (final chunk of 6) matches");+ CHECK(rows_match(1, 4), "P5 I=1 (no full unrolled chunk at all) matches");++ printf("\n%s (%d failure%s)\n", fails ? "TEST FAIL" : "ALL PASS", fails, fails == 1 ? "" : "s");+ return fails ? 1 : 0;+}