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

feat(qwen36): routed experts from a qpack container through bounded slots

Léon Avic Simmonsed53f7d1c2e7
diff --git a/c/Makefile b/c/Makefile
index 5d33d901..d3fc2ae3 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1193,10 +1193,18 @@ ifneq ($(EXE),)
.PHONY: qwen36
qwen36: qwen36$(EXE)
endif
+# Apple METAL=1 engine builds also compile the qpack MLX-affine routed-
+# expert path (activated at runtime by QWEN36_QPACK=<container dir>); other
+# builds keep the inline stubs in qwen36_qpack.h and change nothing.
+QWEN36_QPACK_SRC =
+ifeq ($(METAL),1)
+QWEN36_QPACK_SRC = qwen36_qpack.c qpack.c
+QWEN36_CFLAGS += -DQWEN36_QPACK
+endif
# Rebuild when CUDA_DLL changes; otherwise an existing CPU-only executable can
# be reported as up to date despite selecting the Windows CUDA DLL tier.
-qwen36$(EXE): qwen36.c affine_quant.h qwen38_vision.h sse41_kernels.h decode_batch.h serve_poll.h cli_args.h qwen36_tier.h expert_ffn.h idot.h st.h json.h compat.h omp_tune.h kv_prefix.h pin_pool.h edge_adapter_internal.h edge_adapters.h edge_runtime.h segment_adapter_internal.h segment_adapters.h segment_runtime.h gsgemv.h qgemv.h $(QWEN36_TIER_SRC) $(CUDA_OBJ) .build-config
- $(CC) $(QWEN36_CFLAGS) qwen36.c $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o qwen36$(EXE) $(QWEN36_LDFLAGS)
+qwen36$(EXE): qwen36.c affine_quant.h qwen36_qpack.h qwen38_vision.h sse41_kernels.h decode_batch.h serve_poll.h cli_args.h qwen36_tier.h expert_ffn.h idot.h st.h json.h compat.h omp_tune.h kv_prefix.h pin_pool.h edge_adapter_internal.h edge_adapters.h edge_runtime.h segment_adapter_internal.h segment_adapters.h segment_runtime.h gsgemv.h qgemv.h $(QWEN36_TIER_SRC) $(QWEN36_QPACK_SRC) $(CUDA_OBJ) $(METAL_OBJ) .build-config
+ $(CC) $(QWEN36_CFLAGS) qwen36.c $(QWEN36_TIER_SRC) $(QWEN36_QPACK_SRC) $(CUDA_OBJ) $(METAL_OBJ) -o qwen36$(EXE) $(QWEN36_LDFLAGS)
# Qwen-Image-2.1 text-to-image (docs/qwen-image.md). It reads the diffusers
# checkpoint as it is: no conversion step. qi_gemm.h is its one matrix kernel.
@@ -1288,6 +1296,13 @@ tests/test_qwen36_cache_route$(EXE): tests/test_qwen36_cache_route.c gsgemv.h qg
tests/test_qwen36_dense_batch$(EXE): tests/test_qwen36_dense_batch.c gsgemv.h qgemv.h sse41_kernels.h qwen36.c qwen38_vision.h 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)
+# CPU gate: the qpack MLX-affine routed-expert glue (qwen36_qpack.c)
+# against the portable affine reference, on a synthesized container -- no
+# GPU, every platform. The Apple parity twin (Metal vs CPU reference on a
+# real Swiftlet-generated fixture) is the qwen36-metal-test target.
+tests/test_qwen36_qpack$(EXE): tests/test_qwen36_qpack.c qwen36.c gsgemv.h qgemv.h sse41_kernels.h qwen38_vision.h expert_ffn.h qwen36_qpack.c qwen36_qpack.h qpack.c qpack.h affine_quant.h qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ) $(METAL_OBJ)
+ $(CC) $(QWEN36_CFLAGS) -DQWEN36_QPACK $< qwen36_qpack.c qpack.c $(QWEN36_TIER_SRC) $(CUDA_OBJ) $(METAL_OBJ) -o $@ $(QWEN36_LDFLAGS)
+
tests/test_qwen36_json_escape$(EXE): tests/test_qwen36_json_escape.c gsgemv.h qgemv.h sse41_kernels.h qwen36.c qwen38_vision.h 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)
diff --git a/c/qwen36.c b/c/qwen36.c
index befaa0c0..481138c2 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -69,7 +69,11 @@ static int qwen36_max_ctx(void) {
#include "expert_ffn.h" /* routed experts: planar int4 kernel + layer runner */
#include "idot.h" /* integer dot kernels for the dense trunk (COLI_DENSE_IDOT, COLI_DENSE_BITS) */
#include "qwen38_vision.h" /* the ViT: the same tower in Qwen3.5/3.6/3.8 (#1757) */
+#include "qwen36_qpack.h" /* optional MLX-affine qpack routed-expert path */
#include "affine_quant.h" /* MLX affine dense triples in model.safetensors */
+#ifdef COLI_METAL
+#include "backend_metal.h" /* coli_metal_init: affine pipelines for the store */
+#endif
#ifdef COLI_SEGMENT_ADAPTER
#include "segment_runtime.h"
#include "segment_adapters.h"
@@ -2779,8 +2783,13 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
memset(out, 0, (int64_t)S*D*sizeof(float));
float *g = falloc(I), *u = falloc(I), *hh = falloc(D);
float *sh = falloc(I), *shu = falloc(I), *shd = falloc(D); /* shared expert scratch */
- int use_qt = qt_ready();
- int use_xf = !use_qt && xf_mode(m);
+ /* When a qpack container owns the routed experts, they run through
+ * the MLX-affine path (Metal on Apple, CPU reference elsewhere);
+ * neither the CUDA tier nor the expert_ffn kernel is consulted.
+ * Routing, shared expert, and the combine stay on the CPU below. */
+ int use_qq = qq_active();
+ int use_qt = !use_qq && qt_ready();
+ int use_xf = !use_qq && !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++) {
@@ -2842,7 +2851,20 @@ 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_xf) {
+ if (use_qq) {
+ /* A failed expert is fatal: once the container owns the routed
+ * experts there is no other weight source to fall back to, and a
+ * silently skipped expert would just be a wrong answer. */
+ for (int kk = 0; kk < K; kk++) {
+ if (idx[kk] < 0) continue;
+ if (!qq_expert_forward(layer, idx[kk], xs, val[kk],
+ out + (int64_t)s*D)) {
+ fprintf(stderr, "qpack expert layer %d expert %d failed"
+ " -- refusing\n", layer, idx[kk]);
+ exit(1);
+ }
+ }
+ } else 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
@@ -4365,9 +4387,56 @@ int main(int argc, char **argv) {
* (COLI_DENSE_I8=0 disables it) -- see load_tq/QW; model_init_range
* already logged the count and freed bytes. */
+ /* QWEN36_QPACK=<dir> hands the routed experts to a Swiftlet qpack
+ * container through the MLX-affine path (Metal on Apple builds, CPU
+ * reference elsewhere). A mismatched or unsupported container is a
+ * refusal, not a silent fallback to the snapshot experts. */
+ const char *qq_dir = getenv("QWEN36_QPACK");
+ if (qq_dir && *qq_dir) {
+ char qq_err[256];
+#ifdef COLI_METAL
+ /* Compile the Metal affine pipelines BEFORE the store opens. The
+ * store dispatches through coli_metal_matmul_affine_slot, which is
+ * gated on coli_metal_affine_available() -- i.e. on pipelines that
+ * only coli_metal_init() compiles. The parity gates call it in
+ * their own main; the ENGINE never did, so a METAL=1 build ran every
+ * real-model routed projection on the CPU affine reference while
+ * looking identical apart from qq_counts (measured: metal=0
+ * cpu=37440 on the first 35B smoke). Not a refusal when
+ * unavailable: the CPU reference is the documented oracle arm, but
+ * it must be CHOSEN (QWEN36_QPACK_SYNC / qq_force_cpu) or loudly
+ * reported, never a silent default. */
+ if (coli_metal_init())
+ fprintf(stderr, "[qpack] Metal affine pipelines ready\n");
+ else
+ fprintf(stderr, "[qpack] Metal unavailable -- routed experts"
+ " fall back to the CPU affine reference\n");
+#endif
+ /* QWEN36_QPACK_SLOTS=<n> bounds the refillable expert slot pool
+ * (0/unset = the default in qwen36_qpack.c, clamped to the container
+ * total either way). */
+ const char *qq_slots_env = getenv("QWEN36_QPACK_SLOTS");
+ if (qq_slots_env && *qq_slots_env)
+ qq_set_slot_count(atoi(qq_slots_env));
+ if (!qq_open(qq_dir, m.c.n_layers, m.c.n_experts, m.c.hidden,
+ m.c.inter, qq_err, sizeof(qq_err))) {
+ fprintf(stderr, "[qpack] %s: %s\n", qq_dir, qq_err);
+ return 1;
+ }
+ atexit(qq_close);
+ {
+ int qq_slots = 0;
+ qq_slot_stats(&qq_slots, NULL, NULL);
+ fprintf(stderr, "[qpack] routed experts <- MLX affine container"
+ " %s (%d bounded slots)\n", qq_dir, qq_slots);
+ }
+ }
+
/* Optional CUDA VRAM expert tier (COLI_CUDA=1): hot experts live in
* DEVICE_LOCAL memory across the configured GPUs, misses fall back to the
- * CPU int8 path. See qwen36_tier.h. */
+ * CPU int8 path. See qwen36_tier.h. Skipped when the qpack container owns
+ * the routed experts: the tier would warmstart-load the snapshot experts
+ * moe() no longer computes. */
/* Formato degli esperti dalla TAGLIA SU DISCO del primo, non da meta.ebits:
* esiste un container i8 il cui meta dichiara ebits=4 (stesso motivo per cui
* il loader piu' sopra guarda nbytes). Il tier ne ha bisogno prima di
@@ -4411,7 +4480,7 @@ int main(int argc, char **argv) {
}
if (expert_mixed && getenv("COLI_CUDA") && getenv("COLI_CUDA")[0] == '1')
fprintf(stderr, "[qwen36] COLI_CUDA=1 ignored: the VRAM expert tier does not take the mixed layout yet (one format per expert)\n");
- if (!expert_mixed && m.c.n_experts > 0 &&
+ if (!qq_active() && !expert_mixed && m.c.n_experts > 0 &&
qt_init(m.c.n_layers, m.c.n_experts, m.c.hidden, m.c.inter, cap, m.c.topk,
m.c.expert_gs, expert_is_int4)) {
fprintf(stderr, "[gpu] MoE experts -> CUDA VRAM tier\n");
diff --git a/c/qwen36_qpack.c b/c/qwen36_qpack.c
new file mode 100644
index 00000000..dff646ae
--- /dev/null
+++ b/c/qwen36_qpack.c
@@ -0,0 +1,341 @@
+/* qwen36_qpack.c -- MLX-affine routed experts for the qwen36 engine, read
+ * from a Swiftlet qpack v1 container: the routed projections match the CPU
+ * affine reference, from a bounded pool of expert slots.
+ *
+ * Reading each expert blob once and keeping it resident for the life of
+ * the store is the simplest correct design but unbounded, and naive
+ * eviction is unsafe: coli_metal_matmul_affine keys its persistent handle
+ * on stable host pointers, so evicting without invalidation would hand the
+ * GPU stale copied weights. The store is therefore a BOUNDED pool of
+ * refillable slots:
+ *
+ * - each slot owns one page-aligned expert_stride blob (the qpack layout
+ * guarantees expert_stride % 16384 == 0), registered with the Metal
+ * backend exactly ONCE as a whole-slot zero-copy buffer;
+ * - a miss refills the least-recently-used slot in place (one pread) under
+ * a NEW generation; every dispatch runs through a generation-checked
+ * QqExpertRef, so a ref held across an eviction is refused, never
+ * consumed;
+ * - Metal dispatch addresses the gate/up/down weight/scale/bias sections
+ * by byte offset inside the slot's registered buffer
+ * (coli_metal_matmul_affine_slot) -- nothing is cached by the refillable
+ * host pointers, and refills write through the one registration;
+ * - dispatch is synchronous: when a forward returns, the GPU is done
+ * reading the slot and the next miss may refill it. The async
+ * coli_metal_moe_block_begin/end overlap cannot carry this format
+ * without a shader redesign -- its bindless moe_gemv kernel binds one
+ * weight and one scale address per expert in the QT fmt namespace, with
+ * no bias section and no affine group reconstruction -- so this store
+ * ships the synchronous slot path; a begin/end arm for the affine
+ * format is a separate change.
+ *
+ * The affine format boundary holds: these blobs are unsigned uint32-packed
+ * MLX Q4/Q8 with scale AND bias, never Colibri's signed-int4 QT fmt=4, and
+ * they never enter the QT fmt namespace.
+ *
+ * Single-threaded by contract: only the engine's MoE loop touches the store
+ * (the PILOT prefetch worker services the QT slot cache, not this one). */
+#include "qwen36_qpack.h"
+
+#ifdef QWEN36_QPACK
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <malloc.h>
+#endif
+
+#include "qpack.h"
+#ifdef COLI_METAL
+#include "backend_metal.h"
+#else
+/* Keep one dispatch site below instead of two #ifdef bodies. */
+typedef struct ColiMetalSlotBuffer ColiMetalSlotBuffer;
+#endif
+
+/* Default pool: keeps the tiny test fixtures (<= 64 experts) fully resident
+ * with headroom while bounding real containers; qq_open always clamps the
+ * pool to the container's total expert count. */
+enum { QQ_DEFAULT_SLOT_COUNT = 96 };
+
+typedef struct {
+ unsigned char *blob; /* page-aligned, expert_stride bytes */
+ int layer, eid; /* -1 = empty */
+ uint32_t generation; /* bumped on every (re)fill */
+ uint64_t last_use; /* LRU clock; 0 = never used */
+ ColiAffineQuantizedView gate, up, down;
+ ColiMetalSlotBuffer *mbuf; /* whole-slot buffer, registered once */
+} QqSlot;
+
+static struct {
+ ColiQpackReader reader;
+ QqSlot *slots; /* [n_slots] bounded, refillable */
+ float *scratch_g, *scratch_u, *scratch_h; /* [inter],[inter],[hidden] */
+ size_t slot_len; /* expert_stride */
+ int n_slots;
+ int n_layers, n_experts, hidden, inter;
+ int active, force_cpu;
+ uint64_t tick; /* LRU clock source */
+ uint64_t evictions, fills;
+ uint64_t metal_projections, cpu_projections;
+} g_qq;
+
+/* Survives qq_close so tests and the engine configure the NEXT open. */
+static int g_qq_slot_request;
+
+static int qq_fail(char *error, size_t capacity, const char *message) {
+ if (error && capacity) snprintf(error, capacity, "%s", message);
+ return 0;
+}
+
+/* Slot blobs must satisfy the whole-slot registration contract in
+ * backend_metal.h: 16384-aligned base, length a multiple of 16384 (the
+ * qpack layout already guarantees the stride). */
+static unsigned char *qq_blob_alloc(size_t stride) {
+#ifdef _WIN32
+ return (unsigned char *)_aligned_malloc(stride, 16384);
+#else
+ void *p = NULL;
+ if (posix_memalign(&p, 16384, stride) != 0) return NULL;
+ return (unsigned char *)p;
+#endif
+}
+
+static void qq_blob_free(unsigned char *p) {
+#ifdef _WIN32
+ _aligned_free(p);
+#else
+ free(p);
+#endif
+}
+
+/* Build and geometry-check the three projection views for one slot fill.
+ * gate/up must be [inter, hidden], down [hidden, inter]. */
+static int qq_views(QqSlot *sl, char *error, size_t error_capacity) {
+ const size_t stride = g_qq.slot_len;
+ if (coli_qpack_affine_view(&g_qq.reader, sl->blob, stride, "gate_proj",
+ &sl->gate, error, error_capacity) ||
+ coli_qpack_affine_view(&g_qq.reader, sl->blob, stride, "up_proj",
+ &sl->up, error, error_capacity) ||
+ coli_qpack_affine_view(&g_qq.reader, sl->blob, stride, "down_proj",
+ &sl->down, error, error_capacity))
+ return 0;
+ if (sl->gate.input_dim != (size_t)g_qq.hidden ||
+ sl->gate.output_dim != (size_t)g_qq.inter ||
+ sl->up.input_dim != (size_t)g_qq.hidden ||
+ sl->up.output_dim != (size_t)g_qq.inter ||
+ sl->down.input_dim != (size_t)g_qq.inter ||
+ sl->down.output_dim != (size_t)g_qq.hidden)
+ return qq_fail(error, error_capacity,
+ "projection shape does not match hidden/inter");
+ return 1;
+}
+
+/* Hit: touch LRU state and return the slot. Miss: refill the least-
+ * recently-used slot in place. The victim is invalidated FIRST -- from that
+ * point every ref captured against the old fill is refused at dispatch,
+ * even if the read below fails halfway. */
+static QqSlot *qq_acquire_slot(int layer, int eid, char *error,
+ size_t error_capacity) {
+ if (layer < 0 || layer >= g_qq.n_layers ||
+ eid < 0 || eid >= g_qq.n_experts) {
+ qq_fail(error, error_capacity, "layer or expert out of range");
+ return NULL;
+ }
+ QqSlot *victim = &g_qq.slots[0];
+ for (int i = 0; i < g_qq.n_slots; i++) {
+ QqSlot *sl = &g_qq.slots[i];
+ if (sl->layer == layer && sl->eid == eid) {
+ sl->last_use = ++g_qq.tick;
+ return sl;
+ }
+ if (sl->last_use < victim->last_use) victim = sl;
+ }
+ if (victim->layer >= 0) g_qq.evictions++;
+ victim->generation++;
+ victim->layer = -1;
+ victim->eid = -1;
+ if (coli_qpack_read_expert(&g_qq.reader, (size_t)layer, (size_t)eid,
+ victim->blob, g_qq.slot_len,
+ error, error_capacity))
+ return NULL;
+ if (!qq_views(victim, error, error_capacity)) return NULL;
+ victim->layer = layer;
+ victim->eid = eid;
+ victim->last_use = ++g_qq.tick;
+ g_qq.fills++;
+ return victim;
+}
+
+/* y[view->output_dim] = x @ dequant(view)^T for one row. Metal first when
+ * the pipelines are ready and the oracle switch allows it -- through the
+ * slot's whole-buffer registration, addressed by section byte offsets, never
+ * through a handle cached on the refillable host pointers. CPU reference
+ * otherwise. Counted per projection so tests can prove which path ran. */
+static int qq_matmul(QqSlot *sl, const ColiAffineQuantizedView *view,
+ const float *x, float *y) {
+#ifdef COLI_METAL
+ if (!g_qq.force_cpu && coli_metal_affine_available() &&
+ coli_metal_affine_dispatch_supported(view, 1)) {
+ if (!sl->mbuf)
+ sl->mbuf = coli_metal_slot_register(sl->blob, g_qq.slot_len);
+ if (sl->mbuf) {
+ const unsigned char *blob = sl->blob;
+ size_t woff = (size_t)((const unsigned char *)view->weights - blob);
+ size_t soff = (size_t)((const unsigned char *)view->scales - blob);
+ size_t boff = (size_t)((const unsigned char *)view->biases - blob);
+ if (coli_metal_matmul_affine_slot(sl->mbuf, woff, soff, boff,
+ y, x, 1, view)) {
+ g_qq.metal_projections++;
+ return 1;
+ }
+ }
+ }
+#else
+ (void)sl;
+#endif
+ if (coli_affine_matmul_ref(y, x, 1, view) != COLI_AFFINE_OK) return 0;
+ g_qq.cpu_projections++;
+ return 1;
+}
+
+/* Full teardown, shared by qq_close and the qq_open failure path (safe on a
+ * partially built store: coli_qpack_close tolerates a zeroed reader). */
+static void qq_teardown(void) {
+ if (g_qq.slots) {
+ for (int i = 0; i < g_qq.n_slots; i++) {
+ QqSlot *sl = &g_qq.slots[i];
+#ifdef COLI_METAL
+ if (sl->mbuf) coli_metal_slot_unregister(sl->mbuf);
+#endif
+ qq_blob_free(sl->blob);
+ }
+ free(g_qq.slots);
+ }
+ free(g_qq.scratch_g); free(g_qq.scratch_u); free(g_qq.scratch_h);
+ coli_qpack_close(&g_qq.reader);
+ memset(&g_qq, 0, sizeof(g_qq));
+}
+
+int qq_open(const char *container_dir, int n_layers, int n_experts,
+ int hidden, int inter, char *error, size_t error_capacity) {
+ if (g_qq.active)
+ return qq_fail(error, error_capacity, "qpack store is already open");
+ if (!container_dir || n_layers <= 0 || n_experts <= 0 ||
+ hidden <= 0 || inter <= 0)
+ return qq_fail(error, error_capacity, "invalid qpack store geometry");
+ if (coli_qpack_open(&g_qq.reader, container_dir, error, error_capacity))
+ return 0;
+ g_qq.n_layers = n_layers; g_qq.n_experts = n_experts;
+ g_qq.hidden = hidden; g_qq.inter = inter;
+ if (g_qq.reader.layout.layer_count != (size_t)n_layers ||
+ g_qq.reader.layout.expert_count != (size_t)n_experts) {
+ qq_fail(error, error_capacity,
+ "container layer/expert count does not match the model");
+ goto fail;
+ }
+ g_qq.slot_len = g_qq.reader.layout.expert_stride;
+ {
+ size_t total = (size_t)n_layers * (size_t)n_experts;
+ int slots = g_qq_slot_request > 0 ? g_qq_slot_request
+ : QQ_DEFAULT_SLOT_COUNT;
+ if ((size_t)slots > total) slots = (int)total;
+ g_qq.n_slots = slots;
+ }
+ g_qq.slots = (QqSlot *)calloc((size_t)g_qq.n_slots, sizeof(QqSlot));
+ g_qq.scratch_g = (float *)malloc((size_t)inter * sizeof(float));
+ g_qq.scratch_u = (float *)malloc((size_t)inter * sizeof(float));
+ g_qq.scratch_h = (float *)malloc((size_t)hidden * sizeof(float));
+ if (!g_qq.slots || !g_qq.scratch_g || !g_qq.scratch_u ||
+ !g_qq.scratch_h) {
+ qq_fail(error, error_capacity, "out of memory for qpack store");
+ goto fail;
+ }
+ for (int i = 0; i < g_qq.n_slots; i++) {
+ g_qq.slots[i].layer = g_qq.slots[i].eid = -1;
+ g_qq.slots[i].blob = qq_blob_alloc(g_qq.slot_len);
+ if (!g_qq.slots[i].blob) {
+ qq_fail(error, error_capacity, "out of memory for expert slots");
+ goto fail;
+ }
+ }
+ /* Probe expert (0,0) now so a shape mismatch is an open-time refusal,
+ * not a mid-decode one. */
+ if (!qq_acquire_slot(0, 0, error, error_capacity)) goto fail;
+ g_qq.active = 1;
+ return 1;
+fail:
+ qq_teardown();
+ return 0;
+}
+
+int qq_active(void) { return g_qq.active; }
+
+void qq_set_slot_count(int n_slots) {
+ g_qq_slot_request = n_slots > 0 ? n_slots : 0;
+}
+
+void qq_slot_stats(int *n_slots, uint64_t *evictions, uint64_t *fills) {
+ if (n_slots) *n_slots = g_qq.n_slots;
+ if (evictions) *evictions = g_qq.evictions;
+ if (fills) *fills = g_qq.fills;
+}
+
+void qq_force_cpu(int force) { g_qq.force_cpu = force ? 1 : 0; }
+
+int qq_expert_acquire(int layer, int eid, QqExpertRef *ref) {
+ if (!g_qq.active || !ref) return 0;
+ char error[256];
+ QqSlot *sl = qq_acquire_slot(layer, eid, error, sizeof(error));
+ if (!sl) {
+ fprintf(stderr, "[qpack] expert layer %d expert %d: %s\n",
+ layer, eid, error);
+ return 0;
+ }
+ ref->slot = (int32_t)(sl - g_qq.slots);
+ ref->generation = sl->generation;
+ return 1;
+}
+
+int qq_ref_forward(QqExpertRef ref, const float *x, float weight,
+ float *out) {
+ if (!g_qq.active || !x || !out) return 0;
+ if (ref.slot < 0 || ref.slot >= g_qq.n_slots) return 0;
+ QqSlot *sl = &g_qq.slots[ref.slot];
+ /* The stale check IS the slot contract: an evicted slot must be impossible
+ * to consume. Checked here, at dispatch time, not at acquire. */
+ if (sl->generation != ref.generation || sl->layer < 0) {
+ fprintf(stderr, "[qpack] stale slot ref refused (slot %d generation"
+ " %u, ref %u)\n", (int)ref.slot, sl->generation,
+ ref.generation);
+ return 0;
+ }
+ float *g = g_qq.scratch_g, *u = g_qq.scratch_u, *h = g_qq.scratch_h;
+ if (!qq_matmul(sl, &sl->gate, x, g) || !qq_matmul(sl, &sl->up, x, u))
+ return 0;
+ for (int i = 0; i < g_qq.inter; i++) {
+ float gv = g[i];
+ g[i] = (gv / (1.f + expf(-gv))) * u[i];
+ }
+ if (!qq_matmul(sl, &sl->down, g, h)) return 0;
+ for (int d = 0; d < g_qq.hidden; d++) out[d] += weight * h[d];
+ return 1;
+}
+
+int qq_expert_forward(int layer, int eid, const float *x, float weight,
+ float *out) {
+ if (!g_qq.active || !x || !out) return 0;
+ QqExpertRef ref;
+ if (!qq_expert_acquire(layer, eid, &ref)) return 0;
+ return qq_ref_forward(ref, x, weight, out);
+}
+
+void qq_counts(uint64_t *metal_projections, uint64_t *cpu_projections) {
+ if (metal_projections) *metal_projections = g_qq.metal_projections;
+ if (cpu_projections) *cpu_projections = g_qq.cpu_projections;
+}
+
+void qq_close(void) { qq_teardown(); }
+
+#endif /* QWEN36_QPACK */
diff --git a/c/qwen36_qpack.h b/c/qwen36_qpack.h
new file mode 100644
index 00000000..f06868db
--- /dev/null
+++ b/c/qwen36_qpack.h
@@ -0,0 +1,118 @@
+/* qwen36_qpack.h -- optional MLX-affine routed-expert path for the qwen36
+ * engine, fed by a Swiftlet qpack v1 expert container: parity with the CPU
+ * affine reference from a bounded pool of expert slots.
+ *
+ * When a container is opened, moe() computes every routed expert through
+ * checked ColiAffineQuantizedView descriptors into a BOUNDED pool of
+ * refillable expert slots: each slot is one page-aligned expert_stride blob,
+ * registered with the Metal backend exactly once as a whole-slot buffer and
+ * addressed by byte offset at dispatch (coli_metal_matmul_affine_slot) on
+ * Apple builds, or run through the portable CPU reference everywhere else.
+ * A miss refills the least-recently-used slot in place and bumps its
+ * generation; dispatch re-checks the generation, so a stale reference is
+ * refused instead of consuming another expert's bytes. Router, SwiGLU
+ * combine, shared expert, attention, and DeltaNet stay on the CPU -- this is
+ * NOT a whole-GPU forward pass.
+ *
+ * Compiled only when the build sets -DQWEN36_QPACK (Apple METAL=1 engine
+ * builds and the qpack parity tests); otherwise the inline stubs below keep
+ * the engine on its QT int8/int4 expert path with zero overhead -- the same
+ * arrangement as the CUDA tier in qwen36_tier.h. */
+#ifndef QWEN36_QPACK_H
+#define QWEN36_QPACK_H
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+
+/* Handle to one slot fill: `slot` names the pool entry, `generation` the
+ * fill it was captured against. qq_ref_forward re-checks the generation on
+ * every dispatch, so a ref held across an eviction/refill is refused rather
+ * than silently reading the expert that replaced it. */
+typedef struct {
+ int32_t slot;
+ uint32_t generation;
+} QqExpertRef;
+
+#ifdef QWEN36_QPACK
+
+/* Open a qpack container for the loaded model's routed experts and validate
+ * its geometry: layerCount/expertCount against the config, and expert (0,0)'s
+ * gate/up/down projections against [inter,hidden]/[inter,hidden]/[hidden,inter].
+ * Returns 1 when the store is active, 0 with a message in `error` otherwise.
+ * Single-threaded by contract: only the engine's MoE loop may touch the store
+ * (the PILOT prefetch worker never does). */
+int qq_open(const char *container_dir, int n_layers, int n_experts,
+ int hidden, int inter, char *error, size_t error_capacity);
+int qq_active(void);
+
+/* Bound the slot pool for the NEXT qq_open; n <= 0 restores the default (96
+ * slots). The pool is always clamped to the container's total expert count,
+ * so the default keeps the tiny test fixtures fully resident with headroom
+ * while bounding memory on real containers. Engine builds expose this as
+ * QWEN36_QPACK_SLOTS=<n>. */
+void qq_set_slot_count(int n_slots);
+
+/* Pool observability: slot count, evictions (a live expert displaced), and
+ * fills (every expert read into a slot, first fills included). Tests use
+ * this to PROVE eviction/refill happened during a parity run instead of
+ * trusting that an undersized pool was exercised. */
+void qq_slot_stats(int *n_slots, uint64_t *evictions, uint64_t *fills);
+
+/* 1 = force every projection through the CPU affine reference even when the
+ * Metal affine pipelines are ready. This is the parity oracle switch: the
+ * one-layer and logit parity gates run the same engine code twice and compare
+ * the two dispatch modes. */
+void qq_force_cpu(int force);
+
+/* Split forward. qq_expert_acquire loads (layer,eid) into a slot -- a hit
+ * touches LRU state, a miss refills the least-recently-used slot in place
+ * (one pread) under a NEW generation -- and captures a generation-checked
+ * ref. qq_ref_forward computes out[hidden] += weight * expert(x) against
+ * that exact fill and refuses a stale ref (returns 0 without touching out).
+ * The split keeps the eviction contract testable and gives future async
+ * begin/end orchestration a checked handle to carry across the overlap;
+ * today's dispatch is synchronous, so a refused ref can only mean a caller
+ * held it across another acquire. */
+int qq_expert_acquire(int layer, int eid, QqExpertRef *ref);
+int qq_ref_forward(QqExpertRef ref, const float *x, float weight,
+ float *out);
+
+/* out[hidden] += weight * down(silu(gate(x)) * up(x)) for one routed expert:
+ * acquire + ref_forward in one call. Returns 1 on success, 0 on
+ * read/descriptor/compute failure (the caller must treat 0 as fatal -- there
+ * is no other expert source to fall back to once the container owns the
+ * routed experts). */
+int qq_expert_forward(int layer, int eid, const float *x, float weight,
+ float *out);
+
+/* Cumulative projection dispatch counts, so tests can PROVE which path ran
+ * instead of trusting a silent fallback: coli_metal_matmul_affine_slot
+ * returns 0 for CPU fallback by contract, and this is where that becomes
+ * visible. */
+void qq_counts(uint64_t *metal_projections, uint64_t *cpu_projections);
+void qq_close(void);
+
+#else /* !QWEN36_QPACK: inline stubs, engine keeps its QT expert path */
+
+static inline int qq_open(const char *a, int b, int c, int d, int e,
+ char *error, size_t error_capacity) {
+ (void)a;(void)b;(void)c;(void)d;(void)e;
+ /* Loud, not silent: QWEN36_QPACK=<dir> on a build without the path is a
+ * refusal, never an engine that quietly computes different experts. */
+ if (error && error_capacity)
+ snprintf(error, error_capacity,
+ "engine built without qpack affine support (QWEN36_QPACK)");
+ return 0;
+}
+static inline int qq_active(void){return 0;}
+static inline void qq_set_slot_count(int a){(void)a;}
+static inline void qq_slot_stats(int *a,uint64_t *b,uint64_t *c){if(a)*a=0;if(b)*b=0;if(c)*c=0;}
+static inline void qq_force_cpu(int a){(void)a;}
+static inline int qq_expert_acquire(int a,int b,QqExpertRef *c){(void)a;(void)b;(void)c;return 0;}
+static inline int qq_ref_forward(QqExpertRef a,const float*b,float c,float*d){(void)a;(void)b;(void)c;(void)d;return 0;}
+static inline int qq_expert_forward(int a,int b,const float*c,float d,float*e){(void)a;(void)b;(void)c;(void)d;(void)e;return 0;}
+static inline void qq_counts(uint64_t *a,uint64_t *b){if(a)*a=0;if(b)*b=0;}
+static inline void qq_close(void){}
+
+#endif /* QWEN36_QPACK */
+#endif /* QWEN36_QPACK_H */
diff --git a/c/tests/test_qwen36_qpack.c b/c/tests/test_qwen36_qpack.c
new file mode 100644
index 00000000..b3039704
--- /dev/null
+++ b/c/tests/test_qwen36_qpack.c
@@ -0,0 +1,488 @@
+/* CPU gate for the qwen36 qpack MLX-affine routed-expert path.
+ *
+ * Proves the engine-side glue with no GPU in the room:
+ * - qq_open refuses geometry that does not match the loaded model (layer
+ * count, expert count, hidden, inter) and accepts the matching container;
+ * - qq_expert_forward equals an independent composition of the affine CPU
+ * reference (gate/up/down + SwiGLU + weighted accumulate) per expert;
+ * - moe() with the store active produces exactly the router-weighted sum of
+ * reference expert outputs (shared expert zeroed), i.e. the wiring feeds
+ * the right activations to the right experts with the right weights.
+ *
+ * The container is synthesized here the same way tests/test_qpack.c does it;
+ * the Metal-vs-CPU parity gates on the REAL Swiftlet fixture live in
+ * tests/test_qwen36_qpack_metal.c and run on Apple hardware. */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#define main qwen36_main_unused
+#include "../qwen36.c"
+#undef main
+
+#include "../qpack.h"
+
+#include <sys/stat.h>
+
+#define CHECK(condition) do { \
+ if (!(condition)) { \
+ fprintf(stderr, "%s:%d: check failed: %s\n", \
+ __FILE__, __LINE__, #condition); \
+ exit(1); \
+ } \
+} while (0)
+
+/* Fixture geometry: Q4, per_word=8, group_size=8.
+ * gate/up: [INTER, HIDDEN]; down: [HIDDEN, INTER]. */
+enum { FX_LAYERS = 2, FX_EXPERTS = 2, FX_HIDDEN = 16, FX_INTER = 8,
+ FX_GS = 8, FX_STRIDE = 16384 };
+
+static const char fx_layout[] =
+ "{\"expertCount\":2,\"layerCount\":2,\"expertStride\":16384,"
+ "\"linearLayers\":[true,false],\"sections\":["
+ "{\"name\":\"gate_proj.weight\",\"dtype\":\"U32\","
+ "\"shape\":[8,2],\"offset\":0,\"size\":64},"
+ "{\"name\":\"gate_proj.scales\",\"dtype\":\"F32\","
+ "\"shape\":[8,2],\"offset\":64,\"size\":64},"
+ "{\"name\":\"gate_proj.biases\",\"dtype\":\"F32\","
+ "\"shape\":[8,2],\"offset\":128,\"size\":64},"
+ "{\"name\":\"up_proj.weight\",\"dtype\":\"U32\","
+ "\"shape\":[8,2],\"offset\":192,\"size\":64},"
+ "{\"name\":\"up_proj.scales\",\"dtype\":\"F32\","
+ "\"shape\":[8,2],\"offset\":256,\"size\":64},"
+ "{\"name\":\"up_proj.biases\",\"dtype\":\"F32\","
+ "\"shape\":[8,2],\"offset\":320,\"size\":64},"
+ "{\"name\":\"down_proj.weight\",\"dtype\":\"U32\","
+ "\"shape\":[16,1],\"offset\":384,\"size\":64},"
+ "{\"name\":\"down_proj.scales\",\"dtype\":\"F32\","
+ "\"shape\":[16,1],\"offset\":448,\"size\":64},"
+ "{\"name\":\"down_proj.biases\",\"dtype\":\"F32\","
+ "\"shape\":[16,1],\"offset\":512,\"size\":64}]}";
+
+static void fx_path(char *out, size_t cap, const char *root, const char *name) {
+ int n = snprintf(out, cap, "%s/%s", root, name);
+ CHECK(n > 0 && (size_t)n < cap);
+}
+
+static void fx_mkdir(const char *path) {
+#ifdef _WIN32
+ CHECK(_mkdir(path) == 0);
+#else
+ CHECK(mkdir(path, 0700) == 0);
+#endif
+}
+
+static void fx_write(const char *path, const void *data, size_t size) {
+ FILE *f = fopen(path, "wb");
+ CHECK(f != NULL);
+ CHECK(fwrite(data, 1, size, f) == size);
+ CHECK(fclose(f) == 0);
+}
+
+static void fx_store_f32(unsigned char *at, float value) {
+ uint32_t bits;
+ memcpy(&bits, &value, sizeof(bits));
+ at[0] = (unsigned char)bits;
+ at[1] = (unsigned char)(bits >> 8);
+ at[2] = (unsigned char)(bits >> 16);
+ at[3] = (unsigned char)(bits >> 24);
+}
+
+/* One expert blob: deterministic per (layer, expert) so every expert is a
+ * different matrix and a routing/index mix-up shows up as a numeric miss. */
+static void fx_fill_expert(unsigned char *blob, size_t layer, size_t expert) {
+ uint32_t state = 0x9e3779b9u ^ (uint32_t)(layer * 131u + expert * 17u + 5u);
+ /* weights: gate@0 up@192 down@384, 16 u32 words each */
+ static const size_t woff[3] = { 0, 192, 384 };
+ for (int p = 0; p < 3; p++)
+ for (int w = 0; w < 16; w++) {
+ state = state * 1664525u + 1013904223u;
+ blob[woff[p] + (size_t)w * 4 + 0] = (unsigned char)state;
+ blob[woff[p] + (size_t)w * 4 + 1] = (unsigned char)(state >> 8);
+ blob[woff[p] + (size_t)w * 4 + 2] = (unsigned char)(state >> 16);
+ blob[woff[p] + (size_t)w * 4 + 3] = (unsigned char)(state >> 24);
+ }
+ /* scales/biases: gate@64/128 up@256/320 down@448/512, 16 f32 each */
+ static const size_t soff[3] = { 64, 256, 448 };
+ for (int p = 0; p < 3; p++)
+ for (int i = 0; i < 16; i++) {
+ float scale = 0.03125f * (float)((int)((layer + expert + i + p) % 7) - 3);
+ float bias = 0.015625f * (float)((int)((layer * 3 + expert + i) % 5) - 2);
+ if (scale == 0.0f) scale = 0.046875f;
+ fx_store_f32(blob + soff[p] + (size_t)i * 4, scale);
+ fx_store_f32(blob + soff[p] + 64 + (size_t)i * 4, bias);
+ }
+}
+
+static void fx_build(const char *root) {
+ char path[1024];
+ fx_mkdir(root);
+ fx_path(path, sizeof(path), root, "packed_experts");
+ fx_mkdir(path);
+ fx_path(path, sizeof(path), root, "packed_experts/layout.json");
+ fx_write(path, fx_layout, sizeof(fx_layout) - 1);
+ for (size_t layer = 0; layer < FX_LAYERS; layer++) {
+ unsigned char *bytes = calloc((size_t)FX_EXPERTS * FX_STRIDE, 1);
+ CHECK(bytes != NULL);
+ for (size_t expert = 0; expert < FX_EXPERTS; expert++)
+ fx_fill_expert(bytes + expert * FX_STRIDE, layer, expert);
+ char name[64];
+ int n = snprintf(name, sizeof(name),
+ "packed_experts/layer_%02zu.bin", layer);
+ CHECK(n > 0 && (size_t)n < sizeof(name));
+ fx_path(path, sizeof(path), root, name);
+ fx_write(path, bytes, (size_t)FX_EXPERTS * FX_STRIDE);
+ free(bytes);
+ }
+ char manifest[1024];
+ int n = snprintf(
+ manifest, sizeof(manifest),
+ "{\"magic\":\"QPACK\",\"version\":1,\"modelName\":\"fixture\","
+ "\"sourceCheckpoint\":\"fixture\",\"quantBits\":4,"
+ "\"quantGroupSize\":%d,\"files\":{"
+ "\"packed_experts/layout.json\":%zu,"
+ "\"packed_experts/layer_00.bin\":%d,"
+ "\"packed_experts/layer_01.bin\":%d}}",
+ FX_GS, sizeof(fx_layout) - 1,
+ FX_EXPERTS * FX_STRIDE, FX_EXPERTS * FX_STRIDE);
+ CHECK(n > 0 && (size_t)n < sizeof(manifest));
+ fx_path(path, sizeof(path), root, "manifest.json");
+ fx_write(path, manifest, (size_t)n);
+}
+
+static void fx_cleanup(const char *root) {
+ char path[1024];
+ for (size_t layer = 0; layer < FX_LAYERS; layer++) {
+ char name[64];
+ snprintf(name, sizeof(name), "packed_experts/layer_%02zu.bin", layer);
+ fx_path(path, sizeof(path), root, name);
+ remove(path);
+ }
+ fx_path(path, sizeof(path), root, "packed_experts/layout.json");
+ remove(path);
+ fx_path(path, sizeof(path), root, "manifest.json");
+ remove(path);
+ fx_path(path, sizeof(path), root, "packed_experts");
+#ifdef _WIN32
+ _rmdir(path); _rmdir(root);
+#else
+ rmdir(path); rmdir(root);
+#endif
+}
+
+/* Independent oracle: read the blob with the raw qpack reader and compose the
+ * affine CPU reference by hand. out[FX_HIDDEN] += weight * expert(x). */
+static void oracle_expert(const ColiQpackReader *reader, int layer, int eid,
+ const float *x, float weight, float *out) {
+ unsigned char blob[FX_STRIDE];
+ char err[256];
+ CHECK(coli_qpack_read_expert(reader, (size_t)layer, (size_t)eid,
+ blob, sizeof(blob), err, sizeof(err)) == 0);
+ ColiAffineQuantizedView vg, vu, vd;
+ CHECK(coli_qpack_affine_view(reader, blob, sizeof(blob), "gate_proj",
+ &vg, err, sizeof(err)) == 0);
+ CHECK(coli_qpack_affine_view(reader, blob, sizeof(blob), "up_proj",
+ &vu, err, sizeof(err)) == 0);
+ CHECK(coli_qpack_affine_view(reader, blob, sizeof(blob), "down_proj",
+ &vd, err, sizeof(err)) == 0);
+ float g[FX_INTER], u[FX_INTER], h[FX_HIDDEN];
+ CHECK(coli_affine_matmul_ref(g, x, 1, &vg) == COLI_AFFINE_OK);
+ CHECK(coli_affine_matmul_ref(u, x, 1, &vu) == COLI_AFFINE_OK);
+ for (int i = 0; i < FX_INTER; i++)
+ g[i] = (g[i] / (1.f + expf(-g[i]))) * u[i];
+ CHECK(coli_affine_matmul_ref(h, g, 1, &vd) == COLI_AFFINE_OK);
+ for (int d = 0; d < FX_HIDDEN; d++) out[d] += weight * h[d];
+}
+
+static double rel_err(const float *got, const float *want, size_t n) {
+ double maxabs = 0.0, ymax = 0.0;
+ for (size_t i = 0; i < n; i++) {
+ if (!isfinite((double)got[i]) || !isfinite((double)want[i]))
+ return (double)INFINITY;
+ double d = fabs((double)got[i] - (double)want[i]);
+ if (d > maxabs) maxabs = d;
+ double m = fabs((double)want[i]);
+ if (m > ymax) ymax = m;
+ }
+ return maxabs / (ymax + 1e-9);
+}
+
+static int fails = 0;
+static void ck(int cond, const char *what) {
+ if (cond) { printf(" ok %s\n", what); return; }
+ printf(" FAIL %s\n", what);
+ fails++;
+}
+
+static void case_open_validation(const char *root) {
+ char err[256];
+ printf("qq_open geometry validation\n");
+ err[0] = 0;
+ ck(!qq_open(root, FX_LAYERS + 1, FX_EXPERTS, FX_HIDDEN, FX_INTER,
+ err, sizeof(err)) && err[0], "wrong layer count refused");
+ err[0] = 0;
+ ck(!qq_open(root, FX_LAYERS, FX_EXPERTS + 2, FX_HIDDEN, FX_INTER,
+ err, sizeof(err)) && err[0], "wrong expert count refused");
+ err[0] = 0;
+ ck(!qq_open(root, FX_LAYERS, FX_EXPERTS, FX_HIDDEN * 2, FX_INTER,
+ err, sizeof(err)) && err[0], "wrong hidden refused");
+ err[0] = 0;
+ ck(!qq_open(root, FX_LAYERS, FX_EXPERTS, FX_HIDDEN, FX_INTER + 8,
+ err, sizeof(err)) && err[0], "wrong inter refused");
+ ck(!qq_active(), "store stays inactive after refusals");
+ err[0] = 0;
+ ck(qq_open(root, FX_LAYERS, FX_EXPERTS, FX_HIDDEN, FX_INTER,
+ err, sizeof(err)), "matching geometry accepted");
+ ck(qq_active(), "store active after open");
+}
+
+static void case_expert_forward(const char *root) {
+ printf("qq_expert_forward vs independent affine reference\n");
+ ColiQpackReader reader;
+ char err[256];
+ CHECK(coli_qpack_open(&reader, root, err, sizeof(err)) == 0);
+
+ float x[FX_HIDDEN];
+ for (int i = 0; i < FX_HIDDEN; i++)
+ x[i] = 0.0625f * (float)((i * 7 + 3) % 13 - 6);
+
+ uint64_t metal0, cpu0;
+ qq_counts(&metal0, &cpu0);
+ int all_ok = 1;
+ double worst = 0.0;
+ for (int layer = 0; layer < FX_LAYERS; layer++)
+ for (int eid = 0; eid < FX_EXPERTS; eid++) {
+ float got[FX_HIDDEN], want[FX_HIDDEN];
+ for (int d = 0; d < FX_HIDDEN; d++) { got[d] = 0.25f; want[d] = 0.25f; }
+ float w = 0.5f + 0.125f * (float)(layer * FX_EXPERTS + eid);
+ if (!qq_expert_forward(layer, eid, x, w, got)) { all_ok = 0; continue; }
+ oracle_expert(&reader, layer, eid, x, w, want);
+ double e = rel_err(got, want, FX_HIDDEN);
+ if (e > worst) worst = e;
+ }
+ uint64_t metal1, cpu1;
+ qq_counts(&metal1, &cpu1);
+ printf(" expert forward worst nerr=%.2e\n", worst);
+ ck(all_ok, "every expert forward succeeded");
+ ck(worst < 1e-6, "expert forward matches the affine reference");
+ ck(cpu1 - cpu0 == (uint64_t)FX_LAYERS * FX_EXPERTS * 3,
+ "three CPU-reference projections per expert");
+ ck(metal1 == metal0, "no Metal dispatch on the CPU build");
+ /* A real out buffer, so these exercise the range check itself and not
+ * the null-argument refusal in front of it. */
+ float sink[FX_HIDDEN];
+ memset(sink, 0, sizeof(sink));
+ ck(!qq_expert_forward(FX_LAYERS, 0, x, 1.f, sink),
+ "out-of-range layer refused");
+ ck(!qq_expert_forward(0, FX_EXPERTS, x, 1.f, sink),
+ "out-of-range expert refused");
+ coli_qpack_close(&reader);
+}
+
+static void case_moe_wiring(const char *root) {
+ printf("moe() one-layer wiring through the qpack store\n");
+ ColiQpackReader reader;
+ char err[256];
+ CHECK(coli_qpack_open(&reader, root, err, sizeof(err)) == 0);
+
+ enum { S = 2, ISH = 4 };
+ Model m;
+ memset(&m, 0, sizeof(m));
+ m.c.hidden = FX_HIDDEN; m.c.inter = FX_INTER;
+ m.c.n_experts = FX_EXPERTS; m.c.topk = FX_EXPERTS; /* both experts run */
+ m.c.n_group = 1; m.c.shared_inter = ISH; m.c.eps = 1e-6f;
+ Layer l;
+ memset(&l, 0, sizeof(l));
+ float gate[FX_EXPERTS * FX_HIDDEN];
+ for (int i = 0; i < FX_EXPERTS * FX_HIDDEN; i++)
+ gate[i] = 0.05f * (float)((i * 5 + 1) % 9 - 4);
+ float sh_zero[ISH * FX_HIDDEN];
+ memset(sh_zero, 0, sizeof(sh_zero));
+ /* dev's dense matrices are QW (int8-during-load, #1674): f32-only here,
+ * q/q4 NULL, so matmul_d takes the plain float path. */
+ l.gate = (QW){ .w = gate, .I = FX_HIDDEN, .O = FX_EXPERTS };
+ l.sh_g = (QW){ .w = sh_zero, .I = FX_HIDDEN, .O = ISH }; /* shared adds 0 */
+ l.sh_u = (QW){ .w = sh_zero, .I = FX_HIDDEN, .O = ISH };
+ l.sh_d = (QW){ .w = sh_zero, .I = ISH, .O = FX_HIDDEN };
+
+ float x[S * FX_HIDDEN];
+ for (int i = 0; i < S * FX_HIDDEN; i++)
+ x[i] = 0.09375f * (float)((i * 11 + 5) % 15 - 7);
+
+ float out[S * FX_HIDDEN];
+ moe(&m, &l, 0, x, S, out);
+
+ /* Expected: per position, softmax the router logits, take both experts,
+ * renormalize (sum already 1), accumulate reference expert outputs. */
+ float want[S * FX_HIDDEN];
+ memset(want, 0, sizeof(want));
+ for (int s = 0; s < S; s++) {
+ const float *xs = x + s * FX_HIDDEN;
+ float logits[FX_EXPERTS];
+ for (int e = 0; e < FX_EXPERTS; e++) {
+ float acc = 0.f;
+ for (int i = 0; i < FX_HIDDEN; i++)
+ acc += xs[i] * gate[e * FX_HIDDEN + i];
+ logits[e] = acc;
+ }
+ softmax_row(logits, FX_EXPERTS);
+ float sum = 0.f;
+ for (int e = 0; e < FX_EXPERTS; e++) sum += logits[e];
+ for (int e = 0; e < FX_EXPERTS; e++)
+ oracle_expert(&reader, 0, e, xs, logits[e] / sum,
+ want + s * FX_HIDDEN);
+ }
+ double e = rel_err(out, want, (size_t)S * FX_HIDDEN);
+ printf(" moe one-layer nerr=%.2e\n", e);
+ ck(e < 1e-5, "moe() equals router-weighted reference experts");
+ coli_qpack_close(&reader);
+}
+
+/* With the pool covering every expert (default clamps to the container
+ * total), the run so far must have filled each expert exactly once and
+ * evicted nothing -- the resident-equivalent fast path. */
+static void case_default_pool_stats(void) {
+ printf("default pool bounds\n");
+ int n_slots = 0;
+ uint64_t ev = 0, fills = 0;
+ qq_slot_stats(&n_slots, &ev, &fills);
+ ck(n_slots == FX_LAYERS * FX_EXPERTS,
+ "default pool clamps to the container total");
+ ck(ev == 0, "no eviction while the pool covers every expert");
+ ck(fills == FX_LAYERS * FX_EXPERTS, "every expert filled exactly once");
+}
+
+/* A pool SMALLER than the expert population must still be exact.
+ * One slot serving four experts forces an evict/refill on every miss, and
+ * every forward must still equal the independent affine reference. */
+static void case_bounded_slots(const char *root) {
+ printf("bounded slot pool: evict/refill parity (1 slot, %d experts)\n",
+ FX_LAYERS * FX_EXPERTS);
+ ColiQpackReader reader;
+ char err[256];
+ CHECK(coli_qpack_open(&reader, root, err, sizeof(err)) == 0);
+ qq_set_slot_count(1);
+ CHECK(qq_open(root, FX_LAYERS, FX_EXPERTS, FX_HIDDEN, FX_INTER,
+ err, sizeof(err)));
+ int n_slots = 0;
+ uint64_t ev = 0, fills = 0;
+ qq_slot_stats(&n_slots, &ev, &fills);
+ ck(n_slots == 1, "pool bounded to one slot");
+
+ float x[FX_HIDDEN];
+ for (int i = 0; i < FX_HIDDEN; i++)
+ x[i] = 0.0625f * (float)((i * 5 + 2) % 13 - 6);
+ double worst = 0.0;
+ int all_ok = 1;
+ for (int pass = 0; pass < 2; pass++)
+ for (int layer = 0; layer < FX_LAYERS; layer++)
+ for (int eid = 0; eid < FX_EXPERTS; eid++) {
+ float got[FX_HIDDEN], want[FX_HIDDEN];
+ memset(got, 0, sizeof(got));
+ memset(want, 0, sizeof(want));
+ if (!qq_expert_forward(layer, eid, x, 1.f, got)) {
+ all_ok = 0;
+ continue;
+ }
+ oracle_expert(&reader, layer, eid, x, 1.f, want);
+ double e = rel_err(got, want, FX_HIDDEN);
+ if (e > worst) worst = e;
+ }
+ qq_slot_stats(&n_slots, &ev, &fills);
+ printf(" evict/refill worst nerr=%.2e evictions=%llu fills=%llu\n",
+ worst, (unsigned long long)ev, (unsigned long long)fills);
+ ck(all_ok, "every forward through the one-slot pool succeeded");
+ ck(worst < 1e-6, "evict/refill forwards match the affine reference");
+ /* The open probe fills (0,0); pass 1 hits it and misses the other 3;
+ * pass 2 misses all 4 -- every later miss displaces a live expert. */
+ ck(fills == 8, "eight fills through the one slot");
+ ck(ev == 7, "seven fills evicted a live expert");
+ coli_qpack_close(&reader);
+}
+
+/* The stale-read refusal the slot contract requires. Evict, refill the
+ * SAME slot with a different expert, then present the old handle: dispatch
+ * must refuse it without touching the accumulator, and the refilled slot
+ * must compute the NEW expert's numbers. */
+static void case_stale_refs(const char *root) {
+ printf("slot generations: stale ref refused after evict/refill\n");
+ ColiQpackReader reader;
+ char err[256];
+ CHECK(coli_qpack_open(&reader, root, err, sizeof(err)) == 0);
+ CHECK(qq_active()); /* one-slot store still open from the case above */
+
+ float x[FX_HIDDEN];
+ for (int i = 0; i < FX_HIDDEN; i++)
+ x[i] = 0.09375f * (float)((i * 3 + 1) % 11 - 5);
+
+ QqExpertRef ref;
+ CHECK(qq_expert_acquire(0, 0, &ref));
+ float out[FX_HIDDEN];
+ memset(out, 0, sizeof(out));
+ ck(qq_ref_forward(ref, x, 1.f, out), "fresh ref dispatches");
+
+ /* Evict (0,0): the only slot is refilled with (1,1). */
+ QqExpertRef other;
+ CHECK(qq_expert_acquire(1, 1, &other));
+ ck(other.slot == ref.slot, "refill reused the same slot");
+ ck(other.generation != ref.generation, "refill bumped the generation");
+
+ float sink[FX_HIDDEN];
+ for (int i = 0; i < FX_HIDDEN; i++) sink[i] = 42.f;
+ ck(!qq_ref_forward(ref, x, 1.f, sink), "stale ref refused at dispatch");
+ int untouched = 1;
+ for (int i = 0; i < FX_HIDDEN; i++)
+ if (sink[i] != 42.f) untouched = 0;
+ ck(untouched, "refused dispatch leaves the accumulator untouched");
+
+ /* The refilled slot computes the NEW expert, not stale bytes. */
+ float got[FX_HIDDEN], want[FX_HIDDEN];
+ memset(got, 0, sizeof(got));
+ memset(want, 0, sizeof(want));
+ ck(qq_ref_forward(other, x, 1.f, got), "refilled ref dispatches");
+ oracle_expert(&reader, 1, 1, x, 1.f, want);
+ double e = rel_err(got, want, FX_HIDDEN);
+ printf(" refilled expert nerr=%.2e\n", e);
+ ck(e < 1e-6, "refilled slot equals the reference for the NEW expert");
+
+ QqExpertRef bogus = { 12345, other.generation };
+ ck(!qq_ref_forward(bogus, x, 1.f, got), "out-of-range slot ref refused");
+
+ /* Re-acquire (0,0): valid again under a fresh generation. */
+ QqExpertRef again;
+ CHECK(qq_expert_acquire(0, 0, &again));
+ ck(again.generation != ref.generation,
+ "re-acquired expert carries a new generation");
+ memset(got, 0, sizeof(got));
+ memset(want, 0, sizeof(want));
+ ck(qq_ref_forward(again, x, 1.f, got), "re-acquired ref dispatches");
+ oracle_expert(&reader, 0, 0, x, 1.f, want);
+ ck(rel_err(got, want, FX_HIDDEN) < 1e-6,
+ "re-acquired expert matches the reference");
+
+ qq_close();
+ ck(!qq_active(), "store inactive after close");
+ qq_set_slot_count(0);
+ coli_qpack_close(&reader);
+}
+
+int main(void) {
+ const char *root = "qpack_qwen36_cpu_fixture.tmp";
+ fx_cleanup(root); /* stale dir from an aborted run */
+ fx_build(root);
+
+ case_open_validation(root);
+ case_expert_forward(root);
+ case_moe_wiring(root);
+ case_default_pool_stats();
+ qq_close();
+ ck(!qq_active(), "store inactive after close");
+
+ case_bounded_slots(root);
+ case_stale_refs(root);
+
+ fx_cleanup(root);
+ printf(fails ? "qwen36 qpack CPU gate: FAILED\n"
+ : "qwen36 qpack CPU gate: ok\n");
+ return fails ? 1 : 0;
+}