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

expert_ffn.h: one routed-expert kernel for the MoE engines, qwen36 first

JustVugg275a1ee05839
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5a779f41..782af024 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -472,6 +472,35 @@ jobs:
echo "FAIL: sanitizer diagnostic under PILOT"; cat san.log; exit 1
fi
echo "sanitizers clean:"; grep -E "Matching tokens" san.log || true
+ - name: Expert kernel A/B on an int4 gs64 fixture (old path vs expert_ffn.h, byte-identical ids)
+ run: |
+ cd c
+ make clean >/dev/null 2>&1 || true
+ make qwen36
+ # The int8 gate above never enters the shared kernel (it needs an int4
+ # gs=64 container with widths that are multiples of 64: the default
+ # tiny has inter=32). This fixture does. The reference is the same
+ # torch model, but what this step asserts is not oracle agreement
+ # (int4 experts drift from f32 by design): it is that the kernel and
+ # the unpack-to-int8 path it replaces emit the SAME ids at every cap,
+ # including cap=1 (one expert resident: the per-pair cut) and cap=16
+ # (the whole prompt in one run).
+ python3 tools/make_qwen36_tiny.py --out qwen36_tiny64 --ref-mode full --inter 64 \
+ --emit-ref qwen36_tiny64/ref_full.json
+ python3 tools/convert_qwen36.py --model qwen36_tiny64 --out qwen36_tiny64_c --ebits 4 --gs 64
+ for cap in 1 2 8 16; do
+ for k in 0 1; do
+ QWEN_EXPERT_KERNEL=$k COLI_DENSE_I8=0 SNAP=qwen36_tiny64_c \
+ ./qwen36 "$cap" 4 qwen36_tiny64/ref_full.json > ab_${cap}_$k.log 2>&1 || true
+ grep -E "^C engine" ab_${cap}_$k.log > ids_${cap}_$k.txt
+ done
+ grep -q "expert kernel: planar int4" ab_${cap}_1.log || { echo "FAIL: kernel did not engage at cap=$cap"; cat ab_${cap}_1.log; exit 1; }
+ grep -q "expert kernel: planar int4" ab_${cap}_0.log && { echo "FAIL: QWEN_EXPERT_KERNEL=0 still engaged the kernel"; exit 1; }
+ test -s ids_${cap}_1.txt || { echo "FAIL: no ids at cap=$cap"; cat ab_${cap}_1.log; exit 1; }
+ cmp ids_${cap}_0.txt ids_${cap}_1.txt || { echo "FAIL: ids differ at cap=$cap"; cat ids_${cap}_0.txt ids_${cap}_1.txt; exit 1; }
+ echo "cap=$cap: identical ($(cat ids_${cap}_1.txt))"
+ done
+ make tests/test_expert_ffn && ./tests/test_expert_ffn
- name: A malformed container is refused, not read
run: |
cd c
diff --git a/README.md b/README.md
index f204abcc..e1033644 100644
--- a/README.md
+++ b/README.md
@@ -617,6 +617,7 @@ c/
β”‚
β”œβ”€β”€ st.h safetensors index and range reads
β”œβ”€β”€ quant.h canonical container decoders
+β”œβ”€β”€ expert_ffn.h routed-expert FFN kernel shared by the MoE engines (planar int4, layer runner)
β”œβ”€β”€ tok.h, json.h tokenizer and JSON parser
β”œβ”€β”€ compat.h Windows/macOS shims (POSIX names, one place)
β”œβ”€β”€ expert_store.h streaming expert cache
diff --git a/c/Makefile b/c/Makefile
index d12c661a..a2233128 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1043,7 +1043,7 @@ QWEN36_TIER_SRC =
QWEN36_CFLAGS = $(NOCUDA_CFLAGS)
QWEN36_LDFLAGS = $(NOCUDA_LDFLAGS)
endif
-qwen36$(EXE): qwen36.c serve_poll.h cli_args.h qwen36_tier.h st.h json.h compat.h edge_adapter_internal.h edge_adapters.h edge_runtime.h segment_adapter_internal.h segment_adapters.h segment_runtime.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+qwen36$(EXE): qwen36.c serve_poll.h cli_args.h qwen36_tier.h expert_ffn.h st.h json.h compat.h edge_adapter_internal.h edge_adapters.h edge_runtime.h segment_adapter_internal.h segment_adapters.h segment_runtime.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
$(CC) $(QWEN36_CFLAGS) qwen36.c $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o qwen36$(EXE) $(QWEN36_LDFLAGS)
# Qwen3.8-Flash-Next text-only sibling. This target is intentionally CPU-only;
@@ -1089,18 +1089,18 @@ qwen38-tiny-check: qwen38-tiny-generate qwen38$(EXE)
# Same tier sources as the engine: the test includes qwen36.c, so with CUDA=1
# it needs qwen36_tier.c and the backend object too (without CUDA, the header's
# inline stubs cover it and both are empty).
-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)
+tests/test_qwen36_ctx$(EXE): tests/test_qwen36_ctx.c qwen36.c expert_ffn.h 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)
+tests/test_qwen36_dense_batch$(EXE): tests/test_qwen36_dense_batch.c qwen36.c expert_ffn.h 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)
-tests/test_qwen36_json_escape$(EXE): tests/test_qwen36_json_escape.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+tests/test_qwen36_json_escape$(EXE): tests/test_qwen36_json_escape.c qwen36.c expert_ffn.h 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)
# Both tokenizer.json merge spellings ("a b" strings and ["a","b"] pairs)
# must index the same merge table; the pair form is what Qwen3.6 ships.
-tests/test_qwen36_tok_merges$(EXE): tests/test_qwen36_tok_merges.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+tests/test_qwen36_tok_merges$(EXE): tests/test_qwen36_tok_merges.c qwen36.c expert_ffn.h 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.
@@ -1315,7 +1315,7 @@ tests/test_olmoe_serve_framing$(EXE): tests/test_olmoe_serve_framing.c olmoe.c s
tests/test_olmoe_cache_index$(EXE): tests/test_olmoe_cache_index.c olmoe.c 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)
-tests/test_qwen36_cache_index$(EXE): tests/test_qwen36_cache_index.c qwen36.c 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 qwen36_tier.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+tests/test_qwen36_cache_index$(EXE): tests/test_qwen36_cache_index.c qwen36.c expert_ffn.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 qwen36_tier.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
$(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)
tests/test_idot$(EXE): tests/test_idot.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 route_trace.h
@@ -1367,6 +1367,9 @@ tests/test_e4m3_vector$(EXE): tests/test_e4m3_vector.c quant.h
tests/test_sparse_attn$(EXE): tests/test_sparse_attn.c sparse_attn.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+tests/test_expert_ffn$(EXE): tests/test_expert_ffn.c expert_ffn.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
tests/test_rans$(EXE): tests/test_rans.c rans.h compat.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
@@ -1735,11 +1738,11 @@ tests/test_qwen36_tier_autoplace$(EXE): tests/test_qwen36_tier_autoplace.c tests
tests/test_qwen36_tier_fp8$(EXE): tests/test_qwen36_tier_fp8.c tests/qwen36_fake_cuda.h qwen36_tier.c qwen36_tier.h backend_cuda.h compat.h
$(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)
-tests/test_qwen36_tier_int8_engine$(EXE): tests/test_qwen36_tier_int8_engine.c tests/qwen36_fake_cuda.h qwen36.c qwen36_tier.c qwen36_tier.h backend_cuda.h cli_args.h st.h json.h compat.h
+tests/test_qwen36_tier_int8_engine$(EXE): tests/test_qwen36_tier_int8_engine.c tests/qwen36_fake_cuda.h qwen36.c expert_ffn.h qwen36_tier.c qwen36_tier.h backend_cuda.h cli_args.h st.h json.h compat.h
$(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)
# #1391: il decode path deve offrire gli esperti int8 al tier, non solo il warmstart
-tests/test_qwen36_tier_int8_decode$(EXE): tests/test_qwen36_tier_int8_decode.c tests/qwen36_fake_cuda.h qwen36.c qwen36_tier.c qwen36_tier.h backend_cuda.h cli_args.h st.h json.h compat.h
+tests/test_qwen36_tier_int8_decode$(EXE): tests/test_qwen36_tier_int8_decode.c tests/qwen36_fake_cuda.h qwen36.c expert_ffn.h qwen36_tier.c qwen36_tier.h backend_cuda.h cli_args.h st.h json.h compat.h
$(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)
tests/test_serve_poll$(EXE): tests/test_serve_poll.c serve_poll.h
diff --git a/c/expert_ffn.h b/c/expert_ffn.h
new file mode 100644
index 00000000..c1939f38
--- /dev/null
+++ b/c/expert_ffn.h
@@ -0,0 +1,414 @@
+/* expert_ffn.h β€” the routed-expert FFN kernel shared by the MoE engines.
+ *
+ * One weight layout, one activation contract, one way of running a layer:
+ *
+ * layout "planar unsigned int4, gs=64": a row of I weights (I % 64 == 0) is
+ * I/64 blocks of 32 bytes; byte k of a block holds element k in its
+ * low nibble and element k+32 in its high nibble, both stored as
+ * v+8 (0..15). One f32 scale per (row, block), row-major [O][I/64].
+ * The same layout quant.h calls "fmt 4 planar" (K1b): `and 0x0F`
+ * yields elements 0..31 already in order, `srli 4` the other 32,
+ * so no unpack instruction is ever paid, and the unsigned nibbles
+ * feed vpdpbusd natively through dot(v,x) = dot(u,x) - 8*sum(x).
+ * f32 activations stay f32 (default): the weight is exact in f32, one
+ * fma per element, one fma per block for the scale. The only
+ * difference from a pair-layout f32 kernel is accumulation order.
+ * i8 activations quantized once per token to int8 with one scale per
+ * row plus the per-block sums (opt-in, `mode` 1): integer dots,
+ * 2 dpbusd per block. Not bit-identical to f32: same policy as
+ * IDOT elsewhere in the tree (opt-in until an ablation blesses it).
+ * layer xf_moe_run() runs a whole MoE layer: gate+up fused over the
+ * experts the routing touched, silu, down, then the K contributions
+ * of each token summed in rank order. Threads split (expert, row
+ * chunk) items, so a layer costs two OpenMP regions instead of
+ * 3*K, and a prompt row never re-reads a weight another row of the
+ * same expert just used.
+ *
+ * Why it exists: measured on the real Qwen3.6 container at full residency the
+ * MoE cost 34 ms/token in steady state against a DRAM floor of 17 ms for the
+ * int8-unpacked experts it was reading and 9 ms for the int4 bytes actually
+ * on disk. Unpacking int4 to int8 at load doubled both the bytes per token
+ * and the resident set; per-GEMV OpenMP regions (24 per layer) and one
+ * reduction per 64-block did the rest. The same shape (int4 experts, f32
+ * hidden state, top-k routing) is every engine here, which is why this is a
+ * header and not a function in one of them.
+ *
+ * Header-only, all static, pure compute: no Model, no I/O, no allocation
+ * beyond what the caller hands in. AVX2/FMA, AVX-VNNI or AVX512-VNNI where built,
+ * with a scalar fallback that defines the numerics every SIMD path must
+ * reproduce (f32 paths: same per-lane accumulation order; i8 paths: exact
+ * integer sums, so identical by construction). */
+#ifndef COLI_EXPERT_FFN_H
+#define COLI_EXPERT_FFN_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <string.h>
+#include <math.h>
+
+#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__)
+#include <immintrin.h>
+#endif
+#ifdef _OPENMP
+#include <omp.h>
+#endif
+
+#define XF_BLOCK 64 /* elements per planar block and per scale group */
+#define XF_BLOCK_BYTES 32
+
+/* ---- layout helpers ------------------------------------------------------- */
+
+static inline size_t xf_row_bytes(int I) { return (size_t)I / 2; }
+static inline int xf_groups(int I) { return I / XF_BLOCK; }
+static inline int xf_layout_ok(int I) { return I > 0 && (I % XF_BLOCK) == 0; }
+
+/* Repack one row from the "signed pairs" container layout (byte j = element
+ * 2j in the low nibble, 2j+1 in the high nibble, two's-complement 4-bit β€” the
+ * qwen36 converter's pack_int4) into planar unsigned. src and dst may not
+ * overlap. I % 64 == 0. */
+static inline void xf_repack_row_pairs_signed(uint8_t *dst, const uint8_t *src, int I) {
+ int b = 0;
+#if defined(__AVX2__)
+ /* 16 pair bytes hold elements 0..31: the low nibbles are the even ones,
+ * the high nibbles the odd ones, so interleaving the two nibble vectors
+ * byte-wise puts elements 0..31 in order. Same for 32..63 from the next 16
+ * bytes; xor 8 turns the signed nibble into v+8; the block is lo | hi<<4. */
+ const __m128i m4 = _mm_set1_epi8(0x0F);
+ const __m256i e8 = _mm256_set1_epi8(8);
+ for (; b < I / XF_BLOCK; b++) {
+ const uint8_t *s = src + (size_t)b * XF_BLOCK_BYTES;
+ __m128i a = _mm_loadu_si128((const __m128i *)s), c = _mm_loadu_si128((const __m128i *)(s + 16));
+ __m128i al = _mm_and_si128(a, m4), ah = _mm_and_si128(_mm_srli_epi16(a, 4), m4);
+ __m128i cl = _mm_and_si128(c, m4), ch = _mm_and_si128(_mm_srli_epi16(c, 4), m4);
+ __m256i e0 = _mm256_set_m128i(_mm_unpackhi_epi8(al, ah), _mm_unpacklo_epi8(al, ah)); /* elements 0..31 */
+ __m256i e1 = _mm256_set_m128i(_mm_unpackhi_epi8(cl, ch), _mm_unpacklo_epi8(cl, ch)); /* elements 32..63 */
+ e0 = _mm256_xor_si256(e0, e8); e1 = _mm256_xor_si256(e1, e8);
+ _mm256_storeu_si256((__m256i *)(dst + (size_t)b * XF_BLOCK_BYTES), _mm256_or_si256(e0, _mm256_slli_epi16(e1, 4)));
+ }
+#endif
+ for (; b < I / XF_BLOCK; b++) {
+ const uint8_t *s = src + (size_t)b * XF_BLOCK_BYTES;
+ uint8_t *d = dst + (size_t)b * XF_BLOCK_BYTES;
+ for (int k = 0; k < 32; k++) {
+ /* element k of the block: byte k/2, nibble k&1; element k+32: byte 16 + k/2 */
+ unsigned lo = (unsigned)(s[k >> 1] >> ((k & 1) * 4)) & 0xF;
+ unsigned hi = (unsigned)(s[16 + (k >> 1)] >> ((k & 1) * 4)) & 0xF;
+ /* signed 4-bit -> v+8 is the nibble xor 8 */
+ d[k] = (uint8_t)((lo ^ 8u) | ((hi ^ 8u) << 4));
+ }
+ }
+}
+static inline void xf_repack_pairs_signed(uint8_t *dst, const uint8_t *src, int O, int I) {
+ for (int o = 0; o < O; o++)
+ xf_repack_row_pairs_signed(dst + (size_t)o * xf_row_bytes(I), src + (size_t)o * xf_row_bytes(I), I);
+}
+/* Decode one element from a planar row (tests and scalar paths). */
+static inline int xf_get(const uint8_t *row, int i) {
+ const uint8_t *blk = row + (size_t)(i / XF_BLOCK) * XF_BLOCK_BYTES;
+ int k = i % XF_BLOCK;
+ unsigned u = k < 32 ? (blk[k] & 0xF) : (blk[k - 32] >> 4);
+ return (int)u - 8;
+}
+
+/* ---- activation contract for the i8 mode ---------------------------------- */
+
+/* Quantize x[I] to int8 with one scale (amax/127), and the per-block sums as
+ * f32 (exact: |sum| <= 64*127). Returns the scale. */
+static inline float xf_act_i8(const float *x, int I, int8_t *xq, float *xsum) {
+ float am = 0.f;
+ for (int i = 0; i < I; i++) { float a = fabsf(x[i]); if (a > am) am = a; }
+ float s = am > 0.f ? am / 127.f : 1.f, inv = 1.f / s;
+ for (int i = 0; i < I; i++) xq[i] = (int8_t)lrintf(x[i] * inv);
+ for (int g = 0; g < I / XF_BLOCK; g++) {
+ int32_t t = 0;
+ for (int i = 0; i < XF_BLOCK; i++) t += xq[g * XF_BLOCK + i];
+ xsum[g] = (float)t;
+ }
+ return s;
+}
+
+/* ---- scalar reference kernels (the numerics contract) --------------------- */
+
+/* f32: per block, 8 lanes l=0..7 accumulate elements l, l+8, ..., l+56 in
+ * order with fma; the 8 lane sums are scaled by the block scale into 8 lane
+ * accumulators; the row ends with the fixed 8->1 tree of xf_hsum8. The SIMD
+ * paths reproduce exactly this. */
+static inline float xf_hsum8_scalar(const float *l) {
+ float a0 = l[0] + l[4], a1 = l[1] + l[5], a2 = l[2] + l[6], a3 = l[3] + l[7];
+ float b0 = a0 + a2, b1 = a1 + a3;
+ return b0 + b1;
+}
+static inline float xf_dot_f32_ref(const uint8_t *w, const float *sc, const float *x, int I) {
+ float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+ for (int g = 0; g < I / XF_BLOCK; g++) {
+ const uint8_t *blk = w + (size_t)g * XF_BLOCK_BYTES;
+ const float *xb = x + g * XF_BLOCK;
+ float lane[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+ for (int i = 0; i < XF_BLOCK; i++) {
+ int v = (i < 32 ? (blk[i] & 0xF) : (blk[i - 32] >> 4)) - 8;
+ lane[i & 7] = fmaf((float)v, xb[i], lane[i & 7]);
+ }
+ for (int l = 0; l < 8; l++) acc[l] = fmaf(lane[l], sc[g], acc[l]);
+ }
+ return xf_hsum8_scalar(acc);
+}
+/* i8: y = sx * sum_g sc[g] * (dot_u(g) - 8*xsum[g]); the per-block integer
+ * dot is exact, then one f32 fma per block per lane exactly as the f32 path
+ * (the 8 lanes hold the 8 int32 partial sums vpdpbusd produces: lane l sums
+ * elements 4l..4l+3 and 32+4l..32+4l+3 of the block). */
+static inline float xf_dot_i8_ref(const uint8_t *w, const float *sc, const int8_t *xq, const float *xsum, float sx, int I) {
+ float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+ float corr = 0.f;
+ for (int g = 0; g < I / XF_BLOCK; g++) {
+ const uint8_t *blk = w + (size_t)g * XF_BLOCK_BYTES;
+ const int8_t *xb = xq + g * XF_BLOCK;
+ int32_t lane[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+ for (int k = 0; k < 32; k++) {
+ lane[k >> 2] += (int32_t)(blk[k] & 0xF) * xb[k];
+ lane[k >> 2] += (int32_t)(blk[k] >> 4) * xb[k + 32];
+ }
+ for (int l = 0; l < 8; l++) acc[l] = fmaf((float)lane[l], sc[g], acc[l]);
+ corr = fmaf(sc[g], xsum[g], corr);
+ }
+ return (xf_hsum8_scalar(acc) - 8.f * corr) * sx;
+}
+
+/* ---- SIMD kernels ---------------------------------------------------------- */
+
+#if defined(__AVX2__) && defined(__FMA__)
+#define XF_HAVE_AVX2 1
+static inline float xf_hsum8(__m256 v) {
+ __m128 lo = _mm256_castps256_ps128(v), hi = _mm256_extractf128_ps(v, 1);
+ __m128 a = _mm_add_ps(lo, hi); /* l+l+4 */
+ __m128 b = _mm_add_ps(a, _mm_movehl_ps(a, a)); /* (0+4)+(2+6), (1+5)+(3+7) */
+ __m128 c = _mm_add_ss(b, _mm_shuffle_ps(b, b, 1));
+ return _mm_cvtss_f32(c);
+}
+/* nibbles of one 32-byte block as two 32-lane signed int8 vectors (v = u-8) */
+static inline void xf_nib_s8(__m256i bb, __m256i *lo, __m256i *hi) {
+ const __m256i m4 = _mm256_set1_epi8(0x0F), e8 = _mm256_set1_epi8(8);
+ *lo = _mm256_sub_epi8(_mm256_and_si256(bb, m4), e8);
+ *hi = _mm256_sub_epi8(_mm256_and_si256(_mm256_srli_epi16(bb, 4), m4), e8);
+}
+/* No 512-bit f32 path on purpose: element i must land in lane i&7 in the
+ * reference's order, and folding 16 lanes onto 8 changes the fma order. The
+ * i8 path is exact integers and could widen; it is DRAM-bound already. */
+
+/* f32 row dot, AVX2: 8 lanes per element octet, lane = i&7 */
+static inline float xf_dot_f32_avx2(const uint8_t *w, const float *sc, const float *x, int I) {
+ __m256 acc = _mm256_setzero_ps();
+ for (int g = 0; g < I / XF_BLOCK; g++) {
+ __m256i bb = _mm256_loadu_si256((const __m256i *)(w + (size_t)g * XF_BLOCK_BYTES));
+ __m256i lo, hi; xf_nib_s8(bb, &lo, &hi);
+ const float *xb = x + g * XF_BLOCK;
+ __m128i lo0 = _mm256_castsi256_si128(lo), lo1 = _mm256_extracti128_si256(lo, 1);
+ __m128i hi0 = _mm256_castsi256_si128(hi), hi1 = _mm256_extracti128_si256(hi, 1);
+ __m256 lane = _mm256_setzero_ps();
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo0)), _mm256_loadu_ps(xb), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(lo0, 8))), _mm256_loadu_ps(xb + 8), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo1)), _mm256_loadu_ps(xb + 16), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(lo1, 8))), _mm256_loadu_ps(xb + 24), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi0)), _mm256_loadu_ps(xb + 32), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(hi0, 8))), _mm256_loadu_ps(xb + 40), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi1)), _mm256_loadu_ps(xb + 48), lane);
+ lane = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(hi1, 8))), _mm256_loadu_ps(xb + 56), lane);
+ acc = _mm256_fmadd_ps(lane, _mm256_set1_ps(sc[g]), acc);
+ }
+ return xf_hsum8(acc);
+}
+
+/* i8 row dot: unsigned nibbles x int8 activations, 8 int32 lanes per block */
+#if defined(__AVXVNNI__) || (defined(__AVX512VNNI__) && defined(__AVX512VL__))
+#define XF_HAVE_VNNI 1
+#if defined(__AVXVNNI__) && !defined(__AVX512VNNI__)
+#define xf_dpbusd(acc, u, x) _mm256_dpbusd_avx_epi32(acc, u, x)
+#else
+#define xf_dpbusd(acc, u, x) _mm256_dpbusd_epi32(acc, u, x)
+#endif
+#else
+static inline __m256i xf_dpbusd(__m256i acc, __m256i u, __m256i x) {
+ /* u <= 15, |x| <= 127: a pair sum fits int16 (<= 3810) */
+ return _mm256_add_epi32(acc, _mm256_madd_epi16(_mm256_maddubs_epi16(u, x), _mm256_set1_epi16(1)));
+}
+#endif
+static inline float xf_dot_i8_avx2(const uint8_t *w, const float *sc, const int8_t *xq, const float *xsum, float sx, int I) {
+ const __m256i m4 = _mm256_set1_epi8(0x0F), z = _mm256_setzero_si256();
+ __m256 acc = _mm256_setzero_ps();
+ int ng = I / XF_BLOCK, g = 0;
+ for (; g < ng; g++) {
+ __m256i bb = _mm256_loadu_si256((const __m256i *)(w + (size_t)g * XF_BLOCK_BYTES));
+ const int8_t *xb = xq + g * XF_BLOCK;
+ __m256i d = xf_dpbusd(z, _mm256_and_si256(bb, m4), _mm256_loadu_si256((const __m256i *)xb));
+ d = xf_dpbusd(d, _mm256_and_si256(_mm256_srli_epi16(bb, 4), m4), _mm256_loadu_si256((const __m256i *)(xb + 32)));
+ acc = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), _mm256_set1_ps(sc[g]), acc);
+ }
+ /* corr = sum_g sc[g]*xsum[g] in the scalar reference's order (sequential fma) */
+ float c = 0.f;
+ for (g = 0; g < ng; g++) c = fmaf(sc[g], xsum[g], c);
+ return (xf_hsum8(acc) - 8.f * c) * sx;
+}
+#endif /* AVX2 */
+
+/* ---- dispatch -------------------------------------------------------------- */
+
+static inline float xf_dot_f32(const uint8_t *w, const float *sc, const float *x, int I) {
+#ifdef XF_HAVE_AVX2
+ return xf_dot_f32_avx2(w, sc, x, I);
+#else
+ return xf_dot_f32_ref(w, sc, x, I);
+#endif
+}
+static inline float xf_dot_i8(const uint8_t *w, const float *sc, const int8_t *xq, const float *xsum, float sx, int I) {
+#ifdef XF_HAVE_AVX2
+ return xf_dot_i8_avx2(w, sc, xq, xsum, sx, I);
+#else
+ return xf_dot_i8_ref(w, sc, xq, xsum, sx, I);
+#endif
+}
+
+/* ---- one expert ------------------------------------------------------------- */
+
+typedef struct {
+ const uint8_t *g4, *u4, *d4; /* planar rows: gate/up [F][H], down [H][F] */
+ const float *gs, *us, *ds; /* block scales: [F][H/64], [F][H/64], [H][F/64] */
+} XfExpert;
+
+/* Activations of one token, prepared once per layer (both modes carry x). */
+typedef struct {
+ const float *x; /* [H] f32 */
+ const int8_t *xq; /* [H] int8, i8 mode */
+ const float *xsum; /* [H/64] block sums, i8 mode */
+ float sx; /* activation scale, i8 mode */
+} XfAct;
+
+/* gate+up rows [r0,r1) of one expert for one token: g[r], u[r]. Both matrices
+ * share the activation, so their rows are interleaved in the same pass. */
+static inline void xf_gate_up_rows(float *g, float *u, const XfExpert *e, const XfAct *a, int H, int r0, int r1, int mode) {
+ size_t rb = xf_row_bytes(H); int ng = xf_groups(H);
+ for (int r = r0; r < r1; r++) {
+ const uint8_t *wg = e->g4 + (size_t)r * rb, *wu = e->u4 + (size_t)r * rb;
+ const float *sg = e->gs + (size_t)r * ng, *su = e->us + (size_t)r * ng;
+ if (mode) { g[r] = xf_dot_i8(wg, sg, a->xq, a->xsum, a->sx, H); u[r] = xf_dot_i8(wu, su, a->xq, a->xsum, a->sx, H); }
+ else { g[r] = xf_dot_f32(wg, sg, a->x, H); u[r] = xf_dot_f32(wu, su, a->x, H); }
+ }
+}
+/* silu(g)*u over [0,F): the hidden row, in the engines' historical form */
+static inline void xf_swiglu(float *h, const float *g, const float *u, int F) {
+ for (int i = 0; i < F; i++) { float gv = g[i]; h[i] = (gv / (1.f + expf(-gv))) * u[i]; }
+}
+/* down rows [r0,r1) of one expert for one hidden row */
+static inline void xf_down_rows(float *y, const XfExpert *e, const XfAct *h, int F, int r0, int r1, int mode) {
+ size_t rb = xf_row_bytes(F); int ng = xf_groups(F);
+ for (int r = r0; r < r1; r++) {
+ const uint8_t *wd = e->d4 + (size_t)r * rb; const float *sd = e->ds + (size_t)r * ng;
+ y[r] = mode ? xf_dot_i8(wd, sd, h->xq, h->xsum, h->sx, F) : xf_dot_f32(wd, sd, h->x, F);
+ }
+}
+
+/* ---- one layer ---------------------------------------------------------------
+ *
+ * S tokens, K routed experts each. idx[s*K+k] is the expert id (or -1), val the
+ * router weight, experts[s*K+k] the resident expert (NULL iff idx < 0).
+ * out[s][H] = sum_k val[s][k] * expert_k(x[s]) accumulated in k order, as the
+ * per-token loops it replaces did. Callers own `scratch` (xf_moe_scratch_bytes).
+ *
+ * Work is split into (expert, row chunk) items twice: gate+up over F rows, then
+ * down over H rows. A prompt of S rows routed to the same expert reads that
+ * expert's weights from DRAM once per chunk, the other rows hit cache. */
+static inline size_t xf_moe_scratch_bytes(int S, int K, int H, int F) {
+ size_t n = (size_t)S * K;
+ return n * (2 * (size_t)F + (size_t)H) * sizeof(float) /* g,u per (s,k); contrib per (s,k) */
+ + n * (size_t)F * sizeof(float) /* h per (s,k) */
+ + n * ((size_t)F + 64) + n * (size_t)(F / XF_BLOCK) * sizeof(float) /* hq, hsum (i8 mode) */
+ + (size_t)S * ((size_t)H + 64) + (size_t)S * (size_t)(H / XF_BLOCK) * sizeof(float) /* xq, xsum */
+ + n * sizeof(int) * 4 + 4096;
+}
+
+static inline void xf_moe_run(float *out, const float *x, int S, int K, int H, int F,
+ const int *idx, const float *val, const XfExpert *const *experts,
+ int mode, void *scratch) {
+ const size_t n = (size_t)S * K;
+ char *p = (char *)scratch;
+#define XF_TAKE(T, count) ((T *)p); p += (((size_t)(count) * sizeof(T)) + 63) & ~(size_t)63
+ float *g = XF_TAKE(float, n * F);
+ float *u = XF_TAKE(float, n * F);
+ float *h = XF_TAKE(float, n * F);
+ float *ctb = XF_TAKE(float, n * H);
+ int8_t *hq = XF_TAKE(int8_t, n * F);
+ float *hsum = XF_TAKE(float, n * (F / XF_BLOCK));
+ float *hsx = XF_TAKE(float, n);
+ int8_t *xq = XF_TAKE(int8_t, (size_t)S * H);
+ float *xsum = XF_TAKE(float, (size_t)S * (H / XF_BLOCK));
+ float *xsx = XF_TAKE(float, S);
+ int *uniq = XF_TAKE(int, n); /* distinct expert ids, in first-seen order */
+ int *head = XF_TAKE(int, n); /* first (s,k) pair index of each distinct expert */
+ int *next = XF_TAKE(int, n); /* chain of pairs sharing an expert */
+ int *cnt = XF_TAKE(int, n);
+#undef XF_TAKE
+
+ /* activations once per token */
+ if (mode) for (int s = 0; s < S; s++) xsx[s] = xf_act_i8(x + (size_t)s * H, H, xq + (size_t)s * H, xsum + (size_t)s * (H / XF_BLOCK));
+
+ /* group the (s,k) pairs by expert */
+ int nu = 0;
+ for (int s = 0; s < S; s++) for (int k = 0; k < K; k++) {
+ int i = s * K + k; next[i] = -1;
+ if (idx[i] < 0 || !experts[i]) continue;
+ int j = 0; for (; j < nu; j++) if (uniq[j] == idx[i]) break;
+ if (j == nu) { uniq[nu] = idx[i]; head[nu] = i; cnt[nu] = 1; nu++; }
+ else { int t = head[j]; while (next[t] >= 0) t = next[t]; next[t] = i; cnt[j]++; }
+ }
+ if (nu == 0) { memset(out, 0, (size_t)S * H * sizeof(float)); return; }
+
+ int T = 1;
+#ifdef _OPENMP
+ T = omp_get_max_threads();
+#endif
+ /* chunking: enough items to feed every thread, rows in multiples of 8 */
+ int cF = (4 * T + nu - 1) / nu; if (cF < 1) cF = 1; if (cF > F / 8) cF = F / 8 > 0 ? F / 8 : 1;
+ int cH = (4 * T + nu - 1) / nu; if (cH < 1) cH = 1; if (cH > H / 8) cH = H / 8 > 0 ? H / 8 : 1;
+ int rowsF = (F + cF - 1) / cF; rowsF = (rowsF + 7) & ~7; cF = (F + rowsF - 1) / rowsF;
+ int rowsH = (H + cH - 1) / cH; rowsH = (rowsH + 7) & ~7; cH = (H + rowsH - 1) / rowsH;
+
+ /* phase 1: gate+up for every (expert, chunk), all rows routed to that expert */
+ #pragma omp parallel for schedule(dynamic, 1)
+ for (int it = 0; it < nu * cF; it++) {
+ int e = it / cF, c = it % cF;
+ int r0 = c * rowsF, r1 = r0 + rowsF; if (r1 > F) r1 = F;
+ for (int i = head[e]; i >= 0; i = next[i]) {
+ int s = i / K;
+ XfAct a = { x + (size_t)s * H, xq + (size_t)s * H, xsum + (size_t)s * (H / XF_BLOCK), mode ? xsx[s] : 0.f };
+ xf_gate_up_rows(g + (size_t)i * F, u + (size_t)i * F, experts[i], &a, H, r0, r1, mode);
+ }
+ }
+ /* hidden rows (cheap, per pair) */
+ #pragma omp parallel for schedule(static)
+ for (int i = 0; i < (int)n; i++) {
+ if (idx[i] < 0 || !experts[i]) continue;
+ xf_swiglu(h + (size_t)i * F, g + (size_t)i * F, u + (size_t)i * F, F);
+ if (mode) hsx[i] = xf_act_i8(h + (size_t)i * F, F, hq + (size_t)i * F, hsum + (size_t)i * (F / XF_BLOCK));
+ }
+ /* phase 2: down for every (expert, chunk) */
+ #pragma omp parallel for schedule(dynamic, 1)
+ for (int it = 0; it < nu * cH; it++) {
+ int e = it / cH, c = it % cH;
+ int r0 = c * rowsH, r1 = r0 + rowsH; if (r1 > H) r1 = H;
+ for (int i = head[e]; i >= 0; i = next[i]) {
+ XfAct a = { h + (size_t)i * F, hq + (size_t)i * F, hsum + (size_t)i * (F / XF_BLOCK), mode ? hsx[i] : 0.f };
+ xf_down_rows(ctb + (size_t)i * H, experts[i], &a, F, r0, r1, mode);
+ }
+ }
+ /* rank-order sum per token: out[s] = sum_k val[s][k] * ctb[s][k] */
+ #pragma omp parallel for schedule(static)
+ for (int s = 0; s < S; s++) {
+ float *os = out + (size_t)s * H;
+ memset(os, 0, (size_t)H * sizeof(float));
+ for (int k = 0; k < K; k++) {
+ int i = s * K + k; if (idx[i] < 0 || !experts[i]) continue;
+ float w = val[i]; const float *c = ctb + (size_t)i * H;
+ for (int d = 0; d < H; d++) os[d] += w * c[d];
+ }
+ }
+}
+
+#endif /* COLI_EXPERT_FFN_H */
diff --git a/c/qwen36.c b/c/qwen36.c
index 68b0c2ba..ffdaf3e2 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -61,7 +61,8 @@ static int qwen36_max_ctx(void) {
#include "cli_args.h"
#include "st.h"
#include "json.h" /* tokenizer.json parsing (reuse minimal parser) */
-#include "qwen36_tier.h" /* optional transparent Vulkan compute backend for MoE experts */
+#include "qwen36_tier.h" /* optional CUDA VRAM expert tier */
+#include "expert_ffn.h" /* routed experts: planar int4 kernel + layer runner */
#ifdef COLI_SEGMENT_ADAPTER
#include "segment_runtime.h"
#include "segment_adapters.h"
@@ -615,7 +616,10 @@ typedef struct {
} Layer;
/* ---------- LRU expert cache (int8 weights + per-row float scales) ---------- */
-typedef struct { int eid; int pinned; int is_int4; int8_t *g, *u, *d; uint8_t *g4, *u4, *d4; float *gs, *us, *ds; uint64_t used; } Slot;
+/* pw: the expert as expert_ffn.h wants it (planar int4, gate|up|down), the
+ * only weight copy a slot holds when the shared kernel is active; g/u/d and
+ * g4/u4/d4 are then NULL. */
+typedef struct { int eid; int pinned; int is_int4; int8_t *g, *u, *d; uint8_t *g4, *u4, *d4; uint8_t *pw; float *gs, *us, *ds; uint64_t used; } Slot;
typedef struct {
Slot *slots;
int *slot_by_expert; /* expert id -> resident slot, -1 if absent */
@@ -734,6 +738,7 @@ static int tm_on(void){ if(g_timers<0){ const char *e=getenv("COLI_TIMERS"); g_t
double g_qt_iss=0, g_qt_cpu=0, g_qt_tak=0; /* QTIER-Phasen (Decode) */
double g_dn_sub[4]; /* DN: proj, conv+split, l2n+rec, norm+out */
double g_tm_step=0; /* step() total (decode) */
+static double g_xf_load=0, g_xf_run=0; /* expert_ffn path: expert fetch (misses) vs compute, decode */
static double g_tm_win_moe=0; static int g_tm_win_n=0;
static void tm_add(int S, int idx, double ms){
if(S==1){
@@ -763,6 +768,9 @@ static void tm_report(void){
if(g_dn_sub[0]+g_dn_sub[1]+g_dn_sub[2]+g_dn_sub[3]>0)
fprintf(stderr,"[timers] dn-sub: proj %.1f | conv %.1f | l2n+rec %.1f | norm+out %.1f ms/token\n",
g_dn_sub[0]/g_tm_dec_tokens,g_dn_sub[1]/g_tm_dec_tokens,g_dn_sub[2]/g_tm_dec_tokens,g_dn_sub[3]/g_tm_dec_tokens);
+ if(g_xf_load+g_xf_run>0)
+ fprintf(stderr,"[timers] expert kernel: fetch %.2f | compute %.2f ms/token\n",
+ g_xf_load/g_tm_dec_tokens, g_xf_run/g_tm_dec_tokens);
if(g_qt_iss+g_qt_cpu+g_qt_tak>0)
fprintf(stderr,"[timers] qtier: issue %.2f | cpu-miss %.2f | take %.2f ms/token\n",
g_qt_iss/g_tm_dec_tokens, g_qt_cpu/g_tm_dec_tokens, g_qt_tak/g_tm_dec_tokens);
@@ -960,6 +968,37 @@ static int g_expert_gs = 0; /* set from qwen36_meta.json (expert_gs) at load *
* needs it to offer int8 experts (#1391): on an int8 container e->g4 is NULL. */
static int g_expert_is_int4 = 1;
+/* Shared expert kernel (expert_ffn.h): routed experts stay planar int4 in
+ * RAM and a layer runs as (expert, row-chunk) items. On by default for an
+ * int4 gs=64 container whose widths are multiples of 64, off under the CUDA
+ * expert tier (it uploads the pair-layout int4 and computes misses from the
+ * int8 copy) and with QWEN_EXPERT_KERNEL=0, which keeps the historical
+ * unpack-to-int8 path for A/Bs. Decided once from the container itself. */
+static int container_layer_is_int4(Model *m, int layer);
+static int xf_mode(Model *m) {
+ static int v = -1;
+ if (v >= 0) return v;
+ const char *e = getenv("QWEN_EXPERT_KERNEL");
+ int on = !(e && *e == '0');
+#ifdef COLI_CUDA
+ { const char *cu = getenv("COLI_CUDA"); if (cu && *cu == '1') on = 0; }
+#endif
+ Cfg *c = &m->c;
+ if (c->expert_gs != XF_BLOCK || !xf_layout_ok(c->hidden) || !xf_layout_ok(c->inter)) on = 0;
+ if (on) {
+ int probe = -1;
+ for (int l = 0; l < c->n_layers && probe < 0; l++) {
+ char nm[256];
+ snprintf(nm, sizeof(nm), "model.layers.%d.mlp.experts.0.merged_weight", m->active_of[l]);
+ if (st_find(&m->S, nm)) probe = container_layer_is_int4(m, m->active_of[l]);
+ }
+ if (probe != 1) on = 0;
+ }
+ v = on;
+ if (v) fprintf(stderr, "[qwen36] expert kernel: planar int4 in RAM (expert_ffn.h), QWEN_EXPERT_KERNEL=0 restores int8 unpack\n");
+ return v;
+}
+
/* The single offer decision the decode path makes for a routed expert: offer
* whichever format the container actually packed, exactly what tier_warmstart
* does (int4 β†’ the packed g4/u4/d4, int8 β†’ the live RAM weights, tier fmt=1
@@ -1417,10 +1456,19 @@ static int64_t scale_count_gu(const Cfg *c){ return c->expert_gs ? (int64_t)c->i
static int64_t scale_count_d (const Cfg *c){ return c->expert_gs ? (int64_t)c->hidden * ((c->inter + c->expert_gs - 1) / c->expert_gs) : c->hidden; }
static void slot_ensure_allocated(Model *m, Slot *s) {
- if (s->g) return;
+ if (s->g || s->pw) return;
Cfg *c = &m->c;
int64_t ng = (int64_t)c->inter * c->hidden;
int64_t nd = (int64_t)c->hidden * c->inter;
+ if (xf_mode(m)) {
+ /* half the bytes of the int8 block: the int4 stays packed */
+ s->pw = malloc((size_t)(ng + ng + nd) / 2);
+ if (!s->pw) { fprintf(stderr, "Error: OOM allocating slot weights\n"); exit(1); }
+ float *s_block = falloc(2*scale_count_gu(c) + scale_count_d(c));
+ s->gs = s_block; s->us = s_block + scale_count_gu(c); s->ds = s_block + 2*scale_count_gu(c);
+ s->pinned = 0; s->is_int4 = 1; s->g = s->u = s->d = NULL; s->g4 = s->u4 = s->d4 = NULL;
+ return;
+ }
int8_t *w_block = malloc(ng + ng + nd);
if (!w_block) { fprintf(stderr, "Error: OOM allocating slot weights\n"); exit(1); }
s->g = w_block;
@@ -1517,10 +1565,21 @@ static void load_expert_merged(Model *m, int layer, int eid, Slot *s) {
each nibble is signed 4-bit (sign-extend if bit3 set). */
if (tw->nbytes == want_w / 2) {
static int noted = 0;
- if (!noted) { fprintf(stderr, "[qwen36] int4 packed weights detected β€” unpacking to int8 in slot\n"); noted = 1; }
+ if (!noted) { fprintf(stderr, "[qwen36] int4 packed weights detected β€” %s\n", s->pw ? "kept int4, repacked planar for expert_ffn.h" : "unpacking to int8 in slot"); noted = 1; }
uint8_t *raw = (uint8_t *)malloc((size_t)(want_w / 2));
if (!raw) { fprintf(stderr, "OOM reading int4 expert %s\n", nm); exit(1); }
st_read_raw(&m->S, nm, raw, 1);
+ if (s->pw) {
+ /* shared kernel: pairs -> planar, never int8 */
+ int64_t gp = ng / 2;
+ xf_repack_pairs_signed(s->pw, raw, cc->inter, cc->hidden);
+ xf_repack_pairs_signed(s->pw + gp, raw + gp, cc->inter, cc->hidden);
+ xf_repack_pairs_signed(s->pw + 2 * gp, raw + 2 * gp, cc->hidden, cc->inter);
+ s->is_int4 = 1;
+ free(raw);
+ st_read_f32(&m->S, qsnm, s->gs, 0);
+ return;
+ }
unpack_int4_to_int8(s->g, raw, want_w);
s->is_int4 = 1;
/* Free any previous occupant first (LRU slot reuse). */
@@ -1930,6 +1989,51 @@ static void qwen_shared_experts_cpu(Model *m, Layer *l, const float *x, int S,
/* 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. */
+/* One MoE layer through expert_ffn.h. The experts a run holds must all be
+ * resident at once, so the batch is cut to what the layer cache can hold:
+ * the whole prompt chunk when cap covers S*K slots, one token when it covers
+ * K, one (token, expert) pair otherwise (cap=1 in CI evicts on every routed
+ * expert). A pair run adds val*expert into out exactly as the per-token loop
+ * did: out starts at zero and the kernel's rank-order sum is one fma per
+ * element, so the three cuts produce the same bits. */
+static void moe_xf_run(Model *m, int layer, const float *x, int S, float *out, const int *idx, const float *val) {
+ Cfg *c = &m->c; int D = c->hidden, K = c->topk, F = c->inter;
+ int cap = m->cache[layer].cap;
+ int64_t gp = (int64_t)F * D / 2;
+ int per = cap >= S * K ? S : 1; /* tokens per run */
+ int kper = cap >= K ? K : 1; /* experts per run */
+ int n = per * kper;
+ XfExpert *ex = malloc(sizeof(XfExpert) * (size_t)n);
+ const XfExpert **exp = malloc(sizeof(XfExpert *) * (size_t)n);
+ int *ridx = malloc(sizeof(int) * (size_t)n); float *rval = falloc(n);
+ float *tmp = kper < K ? falloc(D) : NULL;
+ void *scratch = malloc(xf_moe_scratch_bytes(per, kper, D, F));
+ if (!ex || !exp || !ridx || !scratch) { fprintf(stderr, "OOM moe_xf_run\n"); exit(1); }
+ int timed = tm_on() && S == 1;
+ for (int s0 = 0; s0 < S; s0 += per) {
+ for (int k0 = 0; k0 < K; k0 += kper) {
+ double t0 = timed ? tm_now() : 0;
+ for (int s = 0; s < per; s++) for (int k = 0; k < kper; k++) {
+ int src = (s0 + s) * K + (k0 + k), dst = s * kper + k;
+ ridx[dst] = idx[src]; rval[dst] = val[src]; exp[dst] = NULL;
+ if (idx[src] < 0) continue;
+ Slot *e; expert_get(m, layer, idx[src], &e);
+ ex[dst].g4 = e->pw; ex[dst].u4 = e->pw + gp; ex[dst].d4 = e->pw + 2 * gp;
+ ex[dst].gs = e->gs; ex[dst].us = e->us; ex[dst].ds = e->ds;
+ exp[dst] = &ex[dst];
+ }
+ double t1 = timed ? tm_now() : 0;
+ if (kper == K) xf_moe_run(out + (int64_t)s0 * D, x + (int64_t)s0 * D, per, K, D, F, ridx, rval, exp, 0, scratch);
+ else {
+ xf_moe_run(tmp, x + (int64_t)s0 * D, 1, 1, D, F, ridx, rval, exp, 0, scratch);
+ float *os = out + (int64_t)s0 * D; for (int d = 0; d < D; d++) os[d] += tmp[d];
+ }
+ if (timed) { double t2 = tm_now(); g_xf_load += t1 - t0; g_xf_run += t2 - t1; }
+ }
+ }
+ free(ex); free(exp); free(ridx); free(rval); free(tmp); free(scratch);
+}
+
static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
Cfg *c = &m->c; int D = c->hidden, E = c->n_experts, K = c->topk, I = c->inter;
float *logits = falloc((int64_t)S*E);
@@ -1943,6 +2047,9 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
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();
+ int use_xf = !use_qt && xf_mode(m);
+ int *xidx = use_xf ? malloc(sizeof(int) * (size_t)S * K) : NULL;
+ float *xval = use_xf ? falloc((int64_t)S * K) : NULL;
for (int s = 0; s < S; s++) {
float *pr = logits + (int64_t)s*E;
if (m->momentum_logits && m->pilot_smooth > 0.f) {
@@ -1993,7 +2100,9 @@ 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;
- if (use_qt) {
+ if (use_xf) {
+ for (int kk = 0; kk < K; kk++) { xidx[s*K+kk] = idx[kk]; xval[s*K+kk] = val[kk]; }
+ } else 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. */
@@ -2059,6 +2168,7 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
}
}
}
+ if (use_xf) { moe_xf_run(m, layer, x, S, out, xidx, xval); free(xidx); free(xval); }
/* 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. */
@@ -3187,6 +3297,7 @@ static void qwen36_segment_model_destroy(Qwen36SegmentEngine *engine) {
LCache *cache = &model->cache[layer];
for (int slot = 0; slot < cache->n; slot++) {
free(cache->slots[slot].g);
+ free(cache->slots[slot].pw);
free(cache->slots[slot].gs);
free(cache->slots[slot].g4);
free(cache->slots[slot].u4);
diff --git a/c/tests/test_expert_ffn.c b/c/tests/test_expert_ffn.c
new file mode 100644
index 00000000..9c9f1d4b
--- /dev/null
+++ b/c/tests/test_expert_ffn.c
@@ -0,0 +1,141 @@
+/* expert_ffn.h: the SIMD kernels must reproduce the scalar reference bit for
+ * bit (f32: same lane order; i8: exact integers), the reference must agree with
+ * a double-precision dot, the pair->planar repack must round-trip, and a whole
+ * layer through xf_moe_run must equal the per-token loop it replaces. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "../expert_ffn.h"
+
+static unsigned g_seed = 12345;
+static unsigned rnd(void) { g_seed = g_seed * 1103515245u + 12345u; return g_seed >> 8; }
+static float frand(void) { return ((int)(rnd() & 0xFFFF) - 32768) / 8192.f; }
+
+/* signed-pairs container row (the converter's layout) with random int4 */
+static void make_pairs(uint8_t *dst, int O, int I, int8_t *vals) {
+ for (int o = 0; o < O; o++) for (int i = 0; i < I; i += 2) {
+ int a = (int)(rnd() & 15) - 8, b = (int)(rnd() & 15) - 8;
+ vals[(size_t)o * I + i] = (int8_t)a; vals[(size_t)o * I + i + 1] = (int8_t)b;
+ dst[(size_t)o * I / 2 + i / 2] = (uint8_t)((a & 0xF) | ((b & 0xF) << 4));
+ }
+}
+static void make_scales(float *sc, size_t n) { for (size_t i = 0; i < n; i++) sc[i] = 0.002f + (rnd() & 1023) / 65536.f; }
+
+/* double-precision dot, and the magnitude of its terms: random rows cancel
+ * almost completely, so an error is judged against what was summed, not
+ * against the (near-zero) result */
+static double dot_ref_d(const int8_t *v, const float *sc, const float *x, int I, double *mag) {
+ double a = 0, m = 0;
+ for (int g = 0; g < I / 64; g++) { double d = 0; for (int i = 0; i < 64; i++) { double t = (double)v[g * 64 + i] * x[g * 64 + i]; d += t; m += fabs(t) * sc[g]; } a += d * sc[g]; }
+ *mag = m; return a;
+}
+
+static int fails = 0;
+#define CHECK(cond, ...) do { if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } } while (0)
+
+static void test_row(int I, int O) {
+ size_t rb = (size_t)I / 2; int ng = I / 64;
+ uint8_t *pairs = malloc(rb * O), *planar = malloc(rb * O); int8_t *vals = malloc((size_t)I * O);
+ float *sc = malloc(sizeof(float) * ng * O); float *x = malloc(sizeof(float) * I);
+ make_pairs(pairs, O, I, vals); make_scales(sc, (size_t)ng * O); for (int i = 0; i < I; i++) x[i] = frand();
+ xf_repack_pairs_signed(planar, pairs, O, I);
+ for (int o = 0; o < O; o++) for (int i = 0; i < I; i++)
+ if (xf_get(planar + o * rb, i) != vals[(size_t)o * I + i]) { CHECK(0, "repack I=%d O=%d row %d elem %d: %d != %d", I, O, o, i, xf_get(planar + o * rb, i), vals[(size_t)o * I + i]); return; }
+ int8_t *xq = malloc(I); float *xsum = malloc(sizeof(float) * ng); float sx = xf_act_i8(x, I, xq, xsum);
+ float *xdq = malloc(sizeof(float) * I); for (int i = 0; i < I; i++) xdq[i] = xq[i] * sx;
+ double worst_f = 0, worst_i = 0;
+ for (int o = 0; o < O; o++) {
+ const uint8_t *w = planar + o * rb; const float *s = sc + (size_t)o * ng;
+ float rf = xf_dot_f32_ref(w, s, x, I), kf = xf_dot_f32(w, s, x, I);
+ CHECK(rf == kf, "f32 kernel != reference at I=%d O=%d row %d: %.9g vs %.9g", I, O, o, kf, rf);
+ double mg, d = dot_ref_d(vals + (size_t)o * I, s, x, I, &mg), e = fabs(d - rf) / mg; if (e > worst_f) worst_f = e;
+ float ri = xf_dot_i8_ref(w, s, xq, xsum, sx, I), ki = xf_dot_i8(w, s, xq, xsum, sx, I);
+ CHECK(ri == ki, "i8 kernel != reference at I=%d O=%d row %d: %.9g vs %.9g", I, O, o, ki, ri);
+ double mi, di = dot_ref_d(vals + (size_t)o * I, s, xdq, I, &mi), ei = fabs(di - ri) / mi; if (ei > worst_i) worst_i = ei;
+ }
+ CHECK(worst_f < 1e-6, "f32 vs double: err %.3g of the summed magnitude at I=%d", worst_f, I);
+ CHECK(worst_i < 1e-6, "i8 vs double (on quantized x): err %.3g of the summed magnitude at I=%d", worst_i, I);
+ printf("rows I=%5d O=%5d: f32 bit-exact, i8 bit-exact, worst err/magnitude f32 %.2e i8 %.2e\n", I, O, worst_f, worst_i);
+ free(pairs); free(planar); free(vals); free(sc); free(x); free(xq); free(xsum); free(xdq);
+}
+
+/* the per-token loop xf_moe_run replaces, on the same planar weights */
+static void naive_moe(float *out, const float *x, int S, int K, int H, int F, const int *idx, const float *val, const XfExpert *const *ex, int mode) {
+ float *g = malloc(sizeof(float) * F), *u = malloc(sizeof(float) * F), *h = malloc(sizeof(float) * F), *y = malloc(sizeof(float) * H);
+ int8_t *xq = malloc(H), *hq = malloc(F); float *xs = malloc(sizeof(float) * (H / 64)), *hs = malloc(sizeof(float) * (F / 64));
+ for (int s = 0; s < S; s++) {
+ float *os = out + (size_t)s * H; memset(os, 0, sizeof(float) * H);
+ const float *xs_ = x + (size_t)s * H; float sx = mode ? xf_act_i8(xs_, H, xq, xs) : 0.f;
+ for (int k = 0; k < K; k++) {
+ int i = s * K + k; if (idx[i] < 0) continue; const XfExpert *e = ex[i];
+ for (int r = 0; r < F; r++) {
+ if (mode) { g[r] = xf_dot_i8_ref(e->g4 + (size_t)r * H / 2, e->gs + (size_t)r * (H / 64), xq, xs, sx, H); u[r] = xf_dot_i8_ref(e->u4 + (size_t)r * H / 2, e->us + (size_t)r * (H / 64), xq, xs, sx, H); }
+ else { g[r] = xf_dot_f32_ref(e->g4 + (size_t)r * H / 2, e->gs + (size_t)r * (H / 64), xs_, H); u[r] = xf_dot_f32_ref(e->u4 + (size_t)r * H / 2, e->us + (size_t)r * (H / 64), xs_, H); }
+ }
+ xf_swiglu(h, g, u, F);
+ float shx = mode ? xf_act_i8(h, F, hq, hs) : 0.f;
+ for (int r = 0; r < H; r++)
+ y[r] = mode ? xf_dot_i8_ref(e->d4 + (size_t)r * F / 2, e->ds + (size_t)r * (F / 64), hq, hs, shx, F)
+ : xf_dot_f32_ref(e->d4 + (size_t)r * F / 2, e->ds + (size_t)r * (F / 64), h, F);
+ float w = val[i]; for (int d = 0; d < H; d++) os[d] += w * y[d];
+ }
+ }
+ free(g); free(u); free(h); free(y); free(xq); free(hq); free(xs); free(hs);
+}
+
+static void test_layer(int S, int K, int H, int F, int NE, int mode) {
+ size_t gb = (size_t)F * H / 2, db = (size_t)H * F / 2;
+ XfExpert *E = malloc(sizeof(XfExpert) * NE); uint8_t *tmp = malloc(gb); int8_t *vals = malloc((size_t)F * H);
+ for (int e = 0; e < NE; e++) {
+ uint8_t *g4 = malloc(gb), *u4 = malloc(gb), *d4 = malloc(db);
+ float *gs = malloc(sizeof(float) * F * (H / 64)), *us = malloc(sizeof(float) * F * (H / 64)), *ds = malloc(sizeof(float) * H * (F / 64));
+ make_pairs(tmp, F, H, vals); xf_repack_pairs_signed(g4, tmp, F, H);
+ make_pairs(tmp, F, H, vals); xf_repack_pairs_signed(u4, tmp, F, H);
+ make_pairs(tmp, H, F, vals); xf_repack_pairs_signed(d4, tmp, H, F);
+ make_scales(gs, (size_t)F * (H / 64)); make_scales(us, (size_t)F * (H / 64)); make_scales(ds, (size_t)H * (F / 64));
+ XfExpert x = { g4, u4, d4, gs, us, ds }; E[e] = x;
+ }
+ float *x = malloc(sizeof(float) * S * H); for (int i = 0; i < S * H; i++) x[i] = frand();
+ int *idx = malloc(sizeof(int) * S * K); float *val = malloc(sizeof(float) * S * K); const XfExpert **ex = malloc(sizeof(void *) * S * K);
+ for (int s = 0; s < S; s++) for (int k = 0; k < K; k++) {
+ int i = s * K + k;
+ idx[i] = (k == K - 1 && (s & 1)) ? -1 : (int)(rnd() % NE); /* a hole in the routing now and then */
+ for (int j = 0; j < k; j++) if (idx[i] >= 0 && idx[s * K + j] == idx[i]) idx[i] = (idx[i] + 1) % NE;
+ val[i] = idx[i] < 0 ? 0.f : 0.05f + (rnd() & 255) / 512.f; ex[i] = idx[i] < 0 ? NULL : &E[idx[i]];
+ }
+ float *o1 = malloc(sizeof(float) * S * H), *o2 = malloc(sizeof(float) * S * H);
+ void *scratch = malloc(xf_moe_scratch_bytes(S, K, H, F));
+ naive_moe(o1, x, S, K, H, F, idx, val, ex, mode);
+ xf_moe_run(o2, x, S, K, H, F, idx, val, ex, mode, scratch);
+ int bad = 0; for (int i = 0; i < S * H; i++) if (o1[i] != o2[i]) { if (!bad) printf(" first diff at %d: %.9g vs %.9g\n", i, o2[i], o1[i]); bad++; }
+ CHECK(bad == 0, "layer S=%d K=%d H=%d F=%d mode=%d: %d of %d outputs differ from the per-token loop", S, K, H, F, mode, bad, S * H);
+ printf("layer S=%2d K=%d H=%4d F=%4d mode=%d: bit-identical to the per-token loop\n", S, K, H, F, mode);
+ for (int e = 0; e < NE; e++) { free((void *)E[e].g4); free((void *)E[e].u4); free((void *)E[e].d4); free((void *)E[e].gs); free((void *)E[e].us); free((void *)E[e].ds); }
+ free(E); free(tmp); free(vals); free(x); free(idx); free(val); free(ex); free(o1); free(o2); free(scratch);
+}
+
+int main(void) {
+#ifdef XF_HAVE_AVX2
+ printf("path: AVX2%s\n",
+#ifdef XF_HAVE_VNNI
+ " + VNNI");
+#else
+ " (maddubs)");
+#endif
+#else
+ printf("path: scalar\n");
+#endif
+ test_row(64, 8); test_row(128, 3); test_row(512, 2048); test_row(2048, 512); test_row(4096, 16);
+ /* an unreachable routing (all -1) must zero the output */
+ { int idx[4] = {-1, -1, -1, -1}; float val[4] = {0}; const XfExpert *ex[4] = {0}; float x[128], out[128]; void *sc = malloc(xf_moe_scratch_bytes(1, 4, 128, 64));
+ for (int i = 0; i < 128; i++) { x[i] = 1.f; out[i] = 7.f; }
+ xf_moe_run(out, x, 1, 4, 128, 64, idx, val, ex, 0, sc); int nz = 0; for (int i = 0; i < 128; i++) nz += out[i] != 0.f;
+ CHECK(nz == 0, "unrouted token left %d non-zero outputs", nz); free(sc); }
+ test_layer(1, 8, 2048, 512, 16, 0);
+ test_layer(1, 8, 2048, 512, 16, 1);
+ test_layer(7, 8, 2048, 512, 12, 0); /* prompt rows sharing experts */
+ test_layer(7, 8, 2048, 512, 12, 1);
+ test_layer(5, 4, 128, 192, 6, 0);
+ test_layer(3, 2, 64, 64, 2, 1);
+ if (fails) { printf("%d failure(s)\n", fails); return 1; }
+ printf("all passed\n"); return 0;
+}
diff --git a/c/tools/make_qwen36_tiny.py b/c/tools/make_qwen36_tiny.py
index d9009e4e..54240ee7 100644
--- a/c/tools/make_qwen36_tiny.py
+++ b/c/tools/make_qwen36_tiny.py
@@ -166,6 +166,11 @@ def main():
help="full keeps both layer kinds (Phase-2 engine); "
"attention_only replaces DeltaNet with identity (Phase 1)")
ap.add_argument("--max-new", type=int, default=16)
+ ap.add_argument("--hidden", type=int, default=64, help="hidden size (default 64)")
+ ap.add_argument("--inter", type=int, default=32,
+ help="routed/shared expert width (default 32). The shared "
+ "expert kernel (expert_ffn.h) needs hidden and inter "
+ "multiples of 64: --inter 64 exercises it.")
ap.add_argument("--prompt-ids", default=None,
help="Comma-separated token ids for the prompt (default 1,2,3,4,5)")
args = ap.parse_args()
@@ -175,7 +180,7 @@ def main():
prompt_ids = [int(x) for x in args.prompt_ids.split(",") if x.strip() != ""]
emit = args.emit_ref if args.emit_ref else None
- build(Path(args.out), max_new=args.max_new, prompt_ids=prompt_ids, emit_ref=emit,
+ build(Path(args.out), hidden=args.hidden, inter=args.inter, max_new=args.max_new, prompt_ids=prompt_ids, emit_ref=emit,
ref_mode=args.ref_mode, seed=args.seed)
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index a2369741..e5cb6147 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -385,6 +385,7 @@ 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_EXPERT_KERNEL` | `1` (on) | Routed experts run through the shared `expert_ffn.h` kernel: the int4 stays packed in RAM (planar layout, half the expert-cache RSS of the int8 unpack), gate+up are one pass, and a layer is two OpenMP regions over (expert, row-chunk) items instead of 3 x top-k GEMV regions. Takes effect on an int4 gs=64 container whose hidden and expert widths are multiples of 64, and not under the CUDA expert tier. `=0` restores the unpack-to-int8 path; the two produce the same tokens (1024-token decode on the real container byte-identical; pinned on the tiny int4 fixture in CI), only the f32 accumulation order inside a dot differs. Measured at cap 256 on the real container: 12.8 -> 15.7 tok/s, peak RSS 29 -> 17 GB. |
| `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. |
diff --git a/docs/qwen36.md b/docs/qwen36.md
index 6e860da3..977e56fd 100644
--- a/docs/qwen36.md
+++ b/docs/qwen36.md
@@ -68,6 +68,38 @@ 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).
+## The expert kernel
+
+Routed experts run through `c/expert_ffn.h`, a header shared with the other
+MoE engines rather than a set of GEMVs of this engine's own. Three things
+changed with it, measured on the real gs64 container at full residency on an
+8-core AVX-512 box (61 GB, DDR5-5600, 58 GB/s DRAM read):
+
+- **The int4 stays int4.** The engine used to unpack every expert to int8 at
+ load; the kernel keeps the container's nibbles, repacked once into a planar
+ layout where `and 0x0F` yields 32 elements in order and `srli 4` the other
+ 32, so a block costs no unpack instruction. Half the bytes per token and half
+ the expert-cache RSS: peak RSS at cap 256 went from 25 GB to 15 GB.
+- **A layer is a unit of work.** gate+up share one pass over the activation,
+ and threads split (expert, row-chunk) items: two OpenMP regions per layer
+ instead of 3 x top-k. A prompt row routed to an expert another row already
+ used reads that expert from cache, not DRAM.
+- **Same tokens.** Activations stay f32 (the kernel also has an int8
+ activation mode, `mode 1`, not wired in here: same policy as `IDOT`). The
+ only difference from the old path is the accumulation order inside a dot;
+ a 1024-token greedy decode on the real container is byte-identical, and CI
+ pins old vs new on a tiny int4 fixture at caps 1, 2, 8 and 16.
+
+Over a 1024-token greedy decode at cap 256 (same prompt, byte-identical
+text): 12.8 -> 15.7 tok/s, MoE per token 34 -> 20 ms on average and 30 -> 17
+ms in the last windows, peak RSS 29 -> 17 GB. Of the 20 ms, 11 are the kernel
+(the DRAM floor for the int4 bytes is 9) and 6 are the residual misses of a
+97.6% hit rate, fetched one at a time; that fetch is the next thing to
+overlap, not this kernel. `tests/test_expert_ffn` holds the numerics.
+`QWEN_EXPERT_KERNEL=0` restores the int8 path for A/Bs. The CUDA expert tier
+keeps its own path: it uploads the pair-layout int4 and computes misses from
+the int8 copy.
+
## Which container?
The gs64 container carries one scale per 64-weight group instead of one per