Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

qwen38: CUDA VRAM expert tier (fp8 streaming mode), engine test, FP8 fixture shards

kreuzzelga5d177bd25d5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 782af024..938e43c3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -702,6 +702,8 @@ jobs:
run: pip install -r c/tools/requirements-qwen38-tiny.txt
- name: Generate the upstream text fixture and run the token-and-logit oracle
run: make -C c qwen38-tiny-check
+ - name: Routed experts as the release ships them (FP8 shards), then the engine on the fake CUDA tier
+ run: make -C c qwen38-tiny-fp8-check qwen38-tier-engine-check
- name: Repeat the eviction path under ASan and UBSan
run: |
cd c
diff --git a/c/Makefile b/c/Makefile
index a2233128..c0131883 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -472,9 +472,12 @@ TEST_RULES := $(shell sed -n 's|^tests/\(test_[a-z0-9_]*\)\$$(EXE):.*|\1|p' $(f
# test_uring is Linux-only. V4 engine tests are appended below only on supported
# x86-64 Linux/Windows and aarch64 Linux hosts; the V4 infrastructure tests have
# unconditional rules and therefore remain portable gates.
+# test_qwen38_tier_engine drives qwen38.c over the generated FP8 fixture
+# (qwen38_tiny_fp8, gitignored); it runs from qwen38-tier-engine-check.
TEST_EXCLUDE = test_uring test_deepseek_v4 test_v4_ownership test_v4_serve_framing \
test_segment_adapters_registration test_segment_adapters_real \
- test_edge_adapters_registration test_edge_adapters_real
+ test_edge_adapters_registration test_edge_adapters_real \
+ test_qwen38_tier_engine
TEST_BINS = $(addprefix tests/,$(addsuffix $(EXE),$(filter-out $(TEST_EXCLUDE),$(TEST_RULES))))
ifneq (,$(LINUX))
TEST_BINS += tests/test_uring$(EXE)
@@ -1046,9 +1049,6 @@ endif
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;
-# qwen38.c owns the direct checkpoint loader and SERVE=1 protocol, with no
-# CUDA/Metal tier advertised by the control plane.
# DeepSeek V4.1 Flash: one file, like every other portable engine. The fp4 experts
# stream from the official checkpoint and quant.h's mxfp4 kernel reads them as they
# are, so there is no conversion target here to go with it.
@@ -1056,8 +1056,12 @@ deepseek_v41$(EXE): deepseek_v41.c cli_args.h st.h json.h tok.h tok_unicode.h co
sparse_attn.h hyper_connections.h serve_codec.h serve_poll.h .build-config
$(CC) $(CFLAGS) deepseek_v41.c -o deepseek_v41$(EXE) $(LDFLAGS)
-qwen38$(EXE): qwen38.c cli_args.h qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h route_trace.h tok.h tok_unicode.h tok_unicode_o200k.h serve_codec.h edge_adapter_internal.h edge_adapters.h edge_runtime.h qwen38_vision.h segment_adapter_internal.h segment_adapters.h segment_runtime.h
- $(CC) $(NOCUDA_CFLAGS) qwen38.c -o qwen38$(EXE) $(NOCUDA_LDFLAGS)
+# Qwen3.8-Flash-Next text-only sibling. qwen38.c owns the direct checkpoint
+# loader and SERVE=1 protocol. With CUDA=1 it links the same expert tier as
+# qwen36 (fp8 streaming mode: hot experts get VRAM copies, the RAM LRU stays);
+# without it the tier header's inline stubs keep the build toolkit-free.
+qwen38$(EXE): qwen38.c cli_args.h qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h route_trace.h tok.h tok_unicode.h tok_unicode_o200k.h serve_codec.h edge_adapter_internal.h edge_adapters.h edge_runtime.h qwen38_vision.h segment_adapter_internal.h segment_adapters.h segment_runtime.h qwen36_tier.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+ $(CC) $(QWEN36_CFLAGS) qwen38.c $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o qwen38$(EXE) $(QWEN36_LDFLAGS)
.PHONY: qwen38-tiny-generate qwen38-tiny-check
qwen38-tiny-generate:
@@ -1084,6 +1088,23 @@ qwen38-tiny-check: qwen38-tiny-generate qwen38$(EXE)
done; \
done
+# Same oracle with the routed experts as the release ships them: e4m3 bytes
+# plus BF16 128x128 block scales, gate/up and down in separate shards. The
+# native slab path and the expanded path must both reproduce the reference;
+# then the engine runs on the fake CUDA tier (no toolkit, no GPU).
+.PHONY: qwen38-tiny-fp8-generate qwen38-tiny-fp8-check qwen38-tier-engine-check
+qwen38-tiny-fp8-generate:
+ $(PYTHON) tools/make_qwen38_tiny.py --out ./qwen38_tiny_fp8 --fp8-experts
+
+qwen38-tiny-fp8-check: qwen38-tiny-fp8-generate qwen38$(EXE)
+ @for native in 1 0; do for cap in 1 2; do \
+ Q38_NATIVE_FP8=$$native OMP_NUM_THREADS=2 SNAP=./qwen38_tiny_fp8 ./qwen38$(EXE) $$cap 8 ./qwen38_tiny_fp8/ref.json || exit $$?; \
+ done; \
+ done
+
+qwen38-tier-engine-check: qwen38-tiny-fp8-generate tests/test_qwen38_tier_engine$(EXE)
+ ./tests/test_qwen38_tier_engine$(EXE)
+
# Context-size gates: KV layout, growth across requests, and the attention
# capacity. Includes qwen36.c directly, so no model file is needed.
# Same tier sources as the engine: the test includes qwen36.c, so with CUDA=1
@@ -1745,6 +1766,12 @@ tests/test_qwen36_tier_int8_engine$(EXE): tests/test_qwen36_tier_int8_engine.c t
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)
+# The qwen38 engine through its own main() on the fake backend: tier start
+# from the FP8 fixture, reduced CPU list, qt_note on recycled slots, oracle
+# tokens unchanged. Needs the fixture (qwen38-tiny-fp8-generate).
+tests/test_qwen38_tier_engine$(EXE): tests/test_qwen38_tier_engine.c tests/qwen36_fake_cuda.h qwen38.c qwen38_core.h qwen36_tier.c qwen36_tier.h backend_cuda.h cli_args.h st.h json.h compat.h quant.h route_trace.h
+ $(CC) $(CFLAGS) -DCOLI_CUDA $< -o $@ $(LDFLAGS)
+
tests/test_serve_poll$(EXE): tests/test_serve_poll.c serve_poll.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
diff --git a/c/qwen36_tier.c b/c/qwen36_tier.c
index c0997353..301ae73b 100644
--- a/c/qwen36_tier.c
+++ b/c/qwen36_tier.c
@@ -457,6 +457,7 @@ static void auto_place(int nl, int ne, int topk, const size_t *capacity, const u
* expert, now in hand, hotter than the coldest resident on its device? */
static int G_fp8_stream;
static const float *G_fp8_lut;
+static int G_upload_sync; /* QT_UPLOAD_SYNC=1: qt_issue waits for in-flight uploads first (tests) */
int qt_init_fp8(int nl, int ne, int D, int Ih, int cap, int topk, const float *e4m3_lut){
G_fp8_stream = 1; G_fp8_lut = e4m3_lut;
@@ -493,6 +494,7 @@ int qt_init(int nl, int ne, int D, int Ih, int cap, int topk, int expert_gs,
}
if(topk>QT_MAX_ROWS){ fprintf(stderr,"[qtier] topk>%d unsupported\n",QT_MAX_ROWS); return 0; }
memset(&G,0,sizeof G);
+ { const char *e=getenv("QT_UPLOAD_SYNC"); G_upload_sync=e&&*e&&*e!='0'; }
G.nl=nl; G.ne=ne; G.D=D; G.Ih=Ih; G.topk=topk;
/* Placement state is re-derived per init: the device fold-in below reads
* COLI_PLACE before the automatic placement has decided anything, and a
@@ -1006,6 +1008,14 @@ uint32_t qt_issue(int layer,const int *eids,int K,const float *x){
for(int i=0;i<G.ndev;i++) G.is_cnt[i]=0;
pthread_mutex_lock(&G.mx);
+ /* QT_UPLOAD_SYNC=1: everything enqueued so far is resident before this
+ * group is formed. Costs the upload/compute overlap, so it is for tests
+ * and diagnostics: the fake-backend engine test asserts on residency and
+ * hits after eight tokens, and on a two-vCPU runner the uploader thread
+ * did not get scheduled once before the run was over (0 uploads, 0 hits,
+ * six entries still queued). No group is open here, so the wait cannot
+ * meet a swap parked on issue_open. */
+ if(G_upload_sync) while(G.inflight>0 && !G.th_stop) pthread_cond_wait(&G.cv_take,&G.mx);
if(layer==0) qt_lfru_tick_locked();
G.issue_open=1;
for(int k=0;k<K;k++){
diff --git a/c/qwen38.c b/c/qwen38.c
index 468726ed..e632f326 100644
--- a/c/qwen38.c
+++ b/c/qwen38.c
@@ -1769,6 +1769,7 @@ int main(int argc, char **argv) {
}
Model m; model_init(&m, snap, cap, bits);
+ q38_tier_start(&m, cap); /* COLI_CUDA=1: hot experts stream to VRAM (qwen36_tier.c) */
if(is_ref)ref_logits=read_reference_logits(ref_root,m.c.vocab);
g_capture_last_logit=ref_logits!=NULL||getenv("DUMP")!=NULL;
q38_telemetry_init(snap, &m);
@@ -1793,6 +1794,7 @@ int main(int argc, char **argv) {
double dt = now_s() - t;
double tot = m.hits + m.miss;
printf("TF-NLL: %.4f nats/token over %d tokens | ppl = %.2f\n", nll, scored, exp(nll));
+ qt_stats(); /* VRAM tier hits/misses/swaps, if on */
printf("Expert cache hit rate: %.1f%% (hit=%llu miss=%llu)\n", tot?100.0*m.hits/tot:0.0,
(unsigned long long)m.hits, (unsigned long long)m.miss);
printf("Speed: %.2f tok/s (%.1fs for %d tokens) | PEAK RSS: %.2f GB\n", scored/dt, dt, scored, rss_gb());
@@ -1868,6 +1870,7 @@ int main(int argc, char **argv) {
if (g_ttft >= 0) fprintf(stderr, "TTFT: %.2f s (time to first token)\n", g_ttft);
tm_report(&m);
fprintf(stderr, "\nPEAK RSS: %.2f GB\n", rss_gb());
+ qt_stats(); /* VRAM tier hits/misses/swaps, if on */
fprintf(stderr, "Expert cache hit rate: %.1f%% (hit=%llu miss=%llu)\n", tot?100.0*m.hits/tot:0.0,
(unsigned long long)m.hits, (unsigned long long)m.miss);
fprintf(stderr, "Speed: %.2f tok/s (%.1fs for %d tokens)\n", n_new/dt, dt, n_new);
diff --git a/c/qwen38_core.h b/c/qwen38_core.h
index 4b2bf891..9d9fde34 100644
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@ -1,3 +1,4 @@
+#include "qwen36_tier.h" /* CUDA VRAM expert tier, shared with qwen36; CPU-only builds get the inline no-op stubs */
/* Native Qwen3.8-Flash-Next text core.
*
* This header is included once by qwen38.c after its tokenizer and protocol
@@ -1679,6 +1680,43 @@ static void q38_attention(Model *m,Layer *l,int layer,const float *x,int S,int p
/* The single-row path is intentionally kept separate from prefill. Decode is
* the latency-sensitive steady state and should not pay for route tables or a
* prompt-sized workspace. */
+/* ---- CUDA VRAM expert tier (qwen36_tier.c, fp8 streaming mode) ------------
+ * The tier keeps its own copies of hot experts in VRAM; the RAM LRU below is
+ * untouched by it. qt_issue() takes the resident experts of a token's route
+ * off the CPU, qt_take() adds their outputs back, and every expert the CPU
+ * did compute is reported with qt_note() so the tier can promote it. The
+ * tier copies what it needs during qt_note; the slot may be recycled by the
+ * next token. Only native FP8 slots are reported: gate.data at the slab start
+ * is what q38_bind_fp8_slot() produces, an expanded slot points elsewhere. */
+static void q38_tier_note(int layer,int eid,const Slot *ex) {
+ if(!qt_ready()||!ex->fp8_slab||ex->gate.data!=ex->fp8_slab)return;
+ qt_note(layer,eid,(const uint8_t*)ex->gate.data,(const uint8_t*)ex->up.data,
+ (const uint8_t*)ex->down.data,ex->gate.scales,ex->up.scales,ex->down.scales);
+}
+
+/* Start the tier after the model is loaded. COLI_CUDA=1 turns it on (the
+ * tier reads that itself); it needs every layer's experts in native FP8 with
+ * the block-scale bank resident, because the GPU kernels consume exactly the
+ * checkpoint layout (e4m3 bytes + [ceil(O/128), ceil(I/128)] scales). */
+static void q38_tier_start(Model *m,int cap) {
+ const char *on=getenv("COLI_CUDA");
+ if(!on||on[0]!='1'||on[1])return;
+ Cfg *c=&m->c;
+ if(!m->native_fp8){
+ fprintf(stderr,"[qtier] qwen38: expert tier needs native FP8 experts (Q38_NATIVE_FP8=1); staying on the CPU\n");
+ return;
+ }
+ for(int layer=0;layer<c->layers;layer++)
+ if(!q38_prepare_expert_scale_bank(m,layer)){
+ fprintf(stderr,"[qtier] qwen38: layer %d experts are not native FP8; staying on the CPU\n",layer);
+ return;
+ }
+ if(qt_init_fp8(c->layers,c->experts,c->hidden,c->inter,cap,c->topk,E4M3_LUT)){
+ atexit(qt_shutdown);
+ fprintf(stderr,"[qtier] qwen38: fp8 expert tier on (RAM LRU %d/layer stays; experts stream to VRAM as they get hot)\n",cap);
+ }
+}
+
static void q38_moe_decode(Model *m,Layer *l,int layer,const float *x,int S,float *out) {
Cfg *c=&m->c;int H=c->hidden,E=c->experts,K=c->topk,I=c->inter,SI=c->shared_inter;
float *logits=falloc(E),*sg=falloc(SI),*su=falloc(SI),*sh=falloc(SI),*shared=falloc(H);
@@ -1693,21 +1731,31 @@ static void q38_moe_decode(Model *m,Layer *l,int layer,const float *x,int S,floa
float route_gates[Q38_MAX_TOPK];
for(int z=0;z<K;z++) route_gates[z]=(float)(val[z]/den);
rt_route(layer,s,idx,route_gates,K); /* shared counts + post-normalization trace */
- q38_prefetch_native_fp8_experts(m,layer,idx,K);
+ /* Resident experts run on the GPU from here on (asynchronously); the
+ * CPU only loads and computes the rest, in route order. */
+ uint32_t qmask=qt_issue(layer,idx,K,xs);
+ int cpu_idx[Q38_MAX_TOPK],cpu_rank[Q38_MAX_TOPK],cpu_n=0;
+ for(int z=0;z<K;z++)if(!((qmask>>z)&1u)){cpu_idx[cpu_n]=idx[z];cpu_rank[cpu_n]=z;cpu_n++;}
+ q38_prefetch_native_fp8_experts(m,layer,cpu_idx,cpu_n);
double phase_started=now_s();
q38_weight_matmul(sg,xs,&l->sh_g,1,H,SI);q38_weight_matmul(su,xs,&l->sh_u,1,H,SI);
for(int j=0;j<SI;j++)sh[j]=q38_silu(sg[j])*su[j];q38_weight_matmul(shared,sh,&l->sh_d,1,SI,H);
float gate=0.f;for(int d=0;d<H;d++)gate+=xs[d]*l->sh_gate[d];gate=q38_sigmoid(gate);
q38_tm_add(m,Q38_TM_SHARED_EXPERT,phase_started);
Slot *selected[Q38_MAX_TOPK];
- int loaded_batch=q38_expert_get_batch(m,layer,idx,K,selected);
- for(int z=0;z<K;z++){
- Slot *ex=loaded_batch?selected[z]:q38_expert_get(m,layer,idx[z]);phase_started=now_s();
+ int loaded_batch=q38_expert_get_batch(m,layer,cpu_idx,cpu_n,selected);
+ for(int i=0;i<cpu_n;i++){
+ int z=cpu_rank[i];
+ Slot *ex=loaded_batch?selected[i]:q38_expert_get(m,layer,cpu_idx[i]);phase_started=now_s();
q38_weight_matmul(eg,xs,&ex->gate,1,H,I);q38_weight_matmul(eu,xs,&ex->up,1,H,I);
for(int j=0;j<I;j++)eh[j]=q38_silu(eg[j])*eu[j];q38_weight_matmul(eo,eh,&ex->down,1,I,H);
for(int d=0;d<H;d++)ys[d]+=route_gates[z]*eo[d];
q38_tm_add(m,Q38_TM_ROUTED_EXPERT,phase_started);
+ q38_tier_note(layer,cpu_idx[i],ex);
}
+ /* GPU experts land after the CPU ones: same values, one more group in
+ * the float sum (that is the only ordering difference to a CPU run). */
+ qt_take(qmask,route_gates,K,ys);
for(int d=0;d<H;d++)ys[d]+=gate*shared[d];
}
rt_trace_end();
diff --git a/c/tests/test_qwen38_tier_engine.c b/c/tests/test_qwen38_tier_engine.c
new file mode 100644
index 00000000..81178f70
--- /dev/null
+++ b/c/tests/test_qwen38_tier_engine.c
@@ -0,0 +1,96 @@
+/* The qwen38 engine on the fake CUDA backend, driven through its own main().
+ *
+ * What the tier's unit test (test_qwen36_tier_fp8.c) cannot see is the
+ * engine side: that q38_tier_start() brings the tier up from a real FP8
+ * fixture (scale banks resident, LUT published, fmt 8), that the decode loop
+ * hands qt_note the slab bytes of native slots only, that the reduced CPU
+ * list (mask -> cpu_idx/cpu_rank -> batch load) leaves the arithmetic alone,
+ * and that recycling the RAM slot right after qt_note corrupts nothing. The
+ * fake backend refuses every issue, so the CPU computes all experts and the
+ * oracle tokens/logits must still match exactly; the hit/miss counters pin
+ * that residency was consulted anyway. Real-GPU parity is a hardware run.
+ *
+ * Needs ./qwen38_tiny_fp8 (make qwen38-tiny-fp8-generate). Include order as
+ * in test_qwen36_tier_int8_engine.c: engine first, then the fake backend,
+ * then the tier source, so the tier's statics (G, qs()) are readable here. */
+#define main qwen38_main_unused
+#include "../qwen38.c"
+#undef main
+
+#ifdef _WIN32
+#undef setenv
+#undef unsetenv
+#define unsetenv(name) _putenv_s(name, "")
+#endif
+
+#include "qwen36_fake_cuda.h"
+
+#include "../qwen36_tier.c"
+
+static int t_fails;
+static void tk(int ok, const char *what) {
+ if (ok) { printf(" ok %s\n", what); return; }
+ printf(" FAIL %s\n", what);
+ t_fails++;
+}
+
+int main(void) {
+ /* the fixture: 4 layers x 4 experts, hidden 32, inter 8, top-2, all
+ * routed experts native e4m3 with one 128x128 block scale per matrix */
+ setenv("SNAP", "./qwen38_tiny_fp8", 1);
+ setenv("OMP_NUM_THREADS", "2", 1);
+ setenv("NOSTREAM", "1", 1);
+ setenv("USAGE_SAVE", "0", 1); /* leave the fixture directory alone */
+ setenv("COLI_CUDA", "1", 1);
+ setenv("COLI_GPUS", "0", 1);
+ setenv("QT_NO_WARMSTART", "1", 1);
+ /* Deterministic residency: the uploader is a thread, and on a two-vCPU
+ * runner it did not run once during the eight tokens (queue of six,
+ * 0 uploads, 0 hits, then five FAILs). With QT_UPLOAD_SYNC every
+ * promotion is resident before the next group is issued. */
+ setenv("QT_UPLOAD_SYNC", "1", 1);
+ setenv("COLI_PLACE", "off", 1);
+ setenv("HEAT_FILE", "", 1);
+ /* room for six of the sixteen experts, so promotion has to swap */
+ size_t exp_bytes = 3ull * 32 * 8 + 3ull * 1 * sizeof(float) + 4096;
+ char gb[64]; snprintf(gb, sizeof gb, "%.15f", (double)(6 * exp_bytes + exp_bytes / 2) / 1073741824.0);
+ setenv("CUDA_EXPERT_GB", gb, 1);
+ fake_ndev = 1; fake_uploads = 0; fake_lut_published = 0;
+
+ /* cap 1 < top-2: every expert is reloaded into the single RAM slot each
+ * time -- the slot is recycled right after the tier looked at it */
+ char *argv[] = { (char *)"qwen38", (char *)"1", (char *)"8", (char *)"./qwen38_tiny_fp8/ref.json" };
+ int rc = qwen38_main_unused(4, argv);
+ tk(rc == 0, "engine on the fake tier reproduces the oracle tokens and logits (cap 1)");
+ qt_fill_wait(); /* the last token's promotions, before the counters are read */
+
+ tk(G.on, "tier started from q38_tier_start on the FP8 fixture");
+ tk(G.wfmt == 8, "streaming mode, weight format 8");
+ tk(G.exp_bytes == exp_bytes, "exp_bytes = 3 x D x Ih + 3 block scales + slack");
+ tk(fake_lut_published, "e4m3 LUT published before the first upload");
+ tk(fake_uploads > 0 && fake_uploads % 3 == 0, "uploads come in gate/up/down triples");
+ tk(last_fmt == 8 && last_bytes == (size_t)G.D * G.Ih, "fmt 8 uploads carry one byte per element");
+
+ pthread_mutex_lock(&G.mx);
+ unsigned long long hits = 0; for (int i = 0; i < G.ndev; i++) hits += G.hits[i];
+ unsigned long long miss = G.miss;
+ int residents = 0, stale = 0;
+ for (int l = 0; l < G.nl; l++) for (int e = 0; e < G.ne; e++) {
+ residents += qs(l, e)->resident;
+ stale += (qs(l, e)->g4 != NULL || qs(l, e)->gs != NULL);
+ }
+ size_t used = G.used[0];
+ pthread_mutex_unlock(&G.mx);
+ tk(hits + miss > 0, "qt_issue was consulted for routed experts");
+ tk(hits > 0, "resident experts were routed (hits counted even though the fake backend refuses to issue)");
+ tk(residents > 0 && residents <= 6, "residency stays within the six-expert budget");
+ tk(used == (size_t)residents * G.exp_bytes, "bytes accounted exactly per resident");
+ tk(stale == 0, "no slot keeps a pointer into the engine's recycled RAM slot");
+
+ qt_shutdown();
+ tk(!G_fp8_stream && !G.on, "shutdown leaves the mode");
+
+ if (t_fails) { printf("test_qwen38_tier_engine: %d failure(s)\n", t_fails); return 1; }
+ printf("test_qwen38_tier_engine: ok\n");
+ return 0;
+}
diff --git a/c/tools/make_qwen38_tiny.py b/c/tools/make_qwen38_tiny.py
index 9b61907c..6b34b9c5 100644
--- a/c/tools/make_qwen38_tiny.py
+++ b/c/tools/make_qwen38_tiny.py
@@ -192,7 +192,25 @@ def _rewrite_shard_fp8(out: Path, packed):
assert name in tensors, name
tensors[name] = q.contiguous()
tensors[name + "_scale_inv"] = scale_inv.to(torch.bfloat16).contiguous()
- save_file(tensors, str(path), metadata={"format": "pt"})
+ # The release keeps a layer's gate/up expert tensors and its down_proj
+ # tensors in different shards. Because the writer sorts BF16 before F8 and
+ # by name within a dtype, that is what makes every layer's gate/up
+ # weight_scale_inv sidecars one compact byte range and the down sidecars
+ # another -- the invariant behind the engine's resident scale bank
+ # (q38_prepare_expert_scale_bank). One file would interleave
+ # down/gate/up per expert and silently send the engine down the
+ # per-matrix fallback, so the fixture ships two shards plus the index.
+ down = {k: v for k, v in tensors.items() if ".mlp.experts." in k and ".down_proj." in k}
+ rest = {k: v for k, v in tensors.items() if k not in down}
+ shards = {"model-00001-of-00002.safetensors": rest, "model-00002-of-00002.safetensors": down}
+ weight_map = {}
+ for fname, group in shards.items():
+ save_file(group, str(out / fname), metadata={"format": "pt"})
+ for k in group: weight_map[k] = fname
+ path.unlink()
+ (out / "model.safetensors.index.json").write_text(json.dumps(
+ {"metadata": {"total_size": sum(v.numel() * v.element_size() for v in tensors.values())},
+ "weight_map": weight_map}, indent=1), encoding="utf-8")
cfg_path = out / "config.json"
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
cfg["quantization_config"] = {"quant_method": "fp8", "activation_scheme": "dynamic",