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

Merge pull request #1870 into integ/release-batch-5

JustVugg0e870f483064
diff --cc c/qwen38.c
index 6350deb2,895449d8..6600e24e
--- a/c/qwen38.c
+++ b/c/qwen38.c
@@@ -1506,7 -1446,8 +1507,8 @@@ static int q38_pin_state_copy(Model *m
memcpy(m->ple_history, st->ple_hist, sizeof(st->ple_hist));
}
}
- q38_mtp_state_copy(m, st->mtp_pend, &st->mtp_len, &st->mtp_pend_n, &st->mtp_pend_tok, to_state);
+ q38_mtp_state_copy(m, st->mtp_pend, &st->mtp_len, &st->mtp_pend_n, st->mtp_pend_tok, to_state);
+ if (!to_state) q38_dn_gpu_invalidate(m); /* restored on the host: the card's copy is from another prompt */
#ifdef COLI_VULKAN
if (!to_state) q38c_host_wrote(m, 0); /* up to the device before the next chain step */
#endif
diff --cc c/qwen38_core.h
index 43a13480,2d67b660..f938cdcb
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@@ -2244,6 -2234,29 +2270,29 @@@ static void q38_deltanet(Model *m,Laye
float *core=falloc(V);
float *rec=m->DN_rec[layer],*ring=m->DN_conv[layer];
+ /* Decode token with the layer on the card: the two gates on the CPU (b and
+ * a, 48 outputs each), everything else -- in_proj qkv and z, conv,
+ * recurrence, gated norm, out_proj -- in one device chain, host in, host
- * out. Not during an MTP verify (snap_after: the CPU path takes the
- * snapshot after its first row). */
- if(S==1&&m->dn_dev&&m->snap_after==0&&qt_dn_gpu_ready(layer)){
++ * out. Not during an MTP verify (snap_rows: the CPU path keeps a copy
++ * of the state after each of its rows). */
++ if(S==1&&m->dn_dev&&m->snap_rows==0&&qt_dn_gpu_ready(layer)){
+ q38_dense_matmul(m,bb,x,&l->dn_b,1,H,VH);
+ q38_dense_matmul(m,aa,x,&l->dn_a,1,H,VH);
+ float egh[64],beta[64];
+ for(int h=0;h<VH&&h<64;h++){
+ egh[h]=expf(-expf(l->dn_alog[h])*q38_softplus(aa[h]+l->dn_dtbias[h]));
+ beta[h]=q38_sigmoid(bb[h]);
+ }
+ q38_dn_gpu_push(m,layer);
+ if(m->dn_dev_fresh[layer]&&qt_dn_gpu_step(layer,x,out,egh,beta)){
+ m->dn_host_stale[layer]=1;
+ free(qkv);free(z);free(bb);free(aa);free(norm);free(conv);free(q);free(k);free(core);
+ q38_tm_add(m,Q38_TM_DELTANET,phase_started);
+ return;
+ }
+ q38_dn_gpu_pull(m,layer); /* the tier turned the layer off: continue on the CPU from the card's state */
+ } else if(m->dn_dev) q38_dn_gpu_pull(m,layer); /* prefill, verify or a CPU-only layer: the host must be current */
+
for(int base=0;base<S;) {
int rows=S-base<rows_capacity?S-base:rows_capacity;
const float *chunk=x+(int64_t)base*H;
@@@ -3508,87 -3421,33 +3578,88 @@@ static float *step(Model *m,const int *
*
* Every verify row is computed the way a decode step computes it (the CPU
* kernels give a row the same bits whatever S is; device matrices run row by
- * row, see q38_weight_matmul), so the logits the caller sees, and its pick,
- * are those of plain decoding, greedy or sampled: the draft never reaches
- * the sampler, and a sample that equals it is simply an accepted draft. The
- * one exception is the CUDA expert tier, whose float order already depends
- * on which experts are resident when, with drafts or without. */
+ * row, see q38_weight_matmul), so the logits the caller sees, and its picks,
+ * are those of plain decoding, greedy or sampled: no draft reaches the
+ * sampler, and a sample that equals one is simply an accepted draft. The one
+ * exception is the CUDA expert tier, whose float order already depends on
+ * which experts are resident when, with drafts or without.
+ *
+ * How many drafts: Q38_MTP_DRAFTS (1..3, default 2) fixes the head's; 0 lets
+ * the gate pick 0..3 from the measured acceptance per draft position and the
+ * measured cost of a verify by its rows (spec_draft.h). Lookup drafts are
+ * always gated (COLI_SPEC_GATE=0 drafts every proposal in full: tests). With
+ * both sources a verify carries the proposal whose expected tokens per unit of
+ * time is higher, the longer one on a tie. */
typedef struct {
- int on, force; /* drafting; Q38_MTP_FORCE's mode letter or 0 */
- int ahead, draft, ahead_pos; /* a verify whose second row (the draft at ahead_pos) awaits the caller's pick */
+ int on, force, force_row; /* MTP drafting; Q38_MTP_FORCE's mode letter (or 0) and its row */
+ int depth; /* Q38_MTP_DRAFTS: drafts per verify, 0 = the gate picks 1..3 */
+ int lookup, lookup_max; /* COLI_LOOKUP: prompt-lookup drafts, up to COLI_LOOKUP_DRAFTS */
+ int lk_force, lk_force_row; /* COLI_LOOKUP_FORCE (tests): the oracle's tokens as the proposal */
+ int *hist, hist_n, hist_cap; /* the tokens fed so far and the one about to be: what lookup searches */
+ SpecGate gate;
+ /* a verify whose rows past the first await the caller's picks: rows
+ * 0..ahead_n-1 at ahead_pos.., ids[] their tokens, ahead_i the next row to
+ * hand out (its draft ids[ahead_i] must be the caller's pick) */
+ int ahead_n, ahead_i, ahead_pos, ahead_src, head_ok;
+ int ids[Q38_SPEC_ROWS];
float *ahead_logit, *ahead_streams;
- uint64_t drafts, accepted, forwards, tokens;
+ uint64_t drafts, accepted, forwards, tokens; /* the MTP head's drafts (the report's counts) */
+ uint64_t verifies; /* the MTP head's verifies */
+ uint64_t lk_drafts, lk_accepted, lk_verifies; /* prompt lookup's */
+ uint64_t depth_prop[Q38_SPEC_ROWS], depth_hit[Q38_SPEC_ROWS]; /* MTP drafts by position */
+ int ended_ahead; /* the generation ended with a verify's rows unconsumed (undone) */
} Q38Spec;
-/* Back to the state after the verify's first row, `len` positions fed. */
-static void q38_spec_rollback(Model *m,int len) {
+/* Copy slots for a verify of up to rows+1 rows: allocated the first time they are
+ * needed, kept for the model's life. 0 = out of memory (the caller drafts less). */
+static int q38_spec_alloc(Model *m,int rows) {
Cfg *c=&m->c;
+ if(rows>Q38_SPEC_SNAPS)rows=Q38_SPEC_SNAPS;
+ for(int s=m->snap_slots;s<rows;s++){
+ m->snap_rec[s]=(float**)calloc((size_t)c->layers,sizeof(float*));
+ m->snap_conv[s]=(float**)calloc((size_t)c->layers,sizeof(float*));
+ if(!m->snap_rec[s]||!m->snap_conv[s])goto refused;
+ for(int i=0;i<c->layers;i++)if(!c->is_attn[i]){
+ m->snap_rec[s][i]=(float*)malloc((size_t)c->dn_vheads*c->dn_kdim*c->dn_vdim*sizeof(float));
+ m->snap_conv[s][i]=(float*)malloc((size_t)c->dn_conv_dim*(c->dn_convk-1)*sizeof(float));
+ if(!m->snap_rec[s][i]||!m->snap_conv[s][i])goto refused;
+ }
+ if(m->PLE_conv_state){
+ m->snap_ple[s]=(float*)malloc((size_t)c->hc_width*(c->ple_convk-1)*c->ngram_size*sizeof(float));
+ if(!m->snap_ple[s])goto refused;
+ }
+ m->snap_slots=s+1;
+ continue;
+refused:
+ /* The next token may try again. Keep complete slots, but release the
+ * unfinished one so retries neither lose its pointers nor consume
+ * the memory the plain decode step needs. */
+ for(int i=0;i<c->layers;i++){
+ free(m->snap_rec[s]?m->snap_rec[s][i]:NULL);
+ free(m->snap_conv[s]?m->snap_conv[s][i]:NULL);
+ }
+ free(m->snap_rec[s]);free(m->snap_conv[s]);free(m->snap_ple[s]);
+ m->snap_rec[s]=m->snap_conv[s]=NULL;m->snap_ple[s]=NULL;
+ return 0;
+ }
+ return 1;
+}
+
+/* Back to the state after the verify's first `keep` rows, `len` positions fed. */
+static void q38_spec_rollback(Model *m,int len,int keep) {
+ Cfg *c=&m->c; int slot=keep-1;
#ifdef COLI_VULKAN
- q38c_rollback(m); /* the dense chain's own copies: its device buffers swap too */
+ q38c_rollback(m,slot,len); /* the dense chain's own copies: its device buffers swap too */
#endif
for(int i=0;i<c->layers;i++)if(!c->is_attn[i]){
- float *t=m->DN_rec[i];m->DN_rec[i]=m->snap_rec[i];m->snap_rec[i]=t;
- t=m->DN_conv[i];m->DN_conv[i]=m->snap_conv[i];m->snap_conv[i]=t;
+ float *t=m->DN_rec[i];m->DN_rec[i]=m->snap_rec[slot][i];m->snap_rec[slot][i]=t;
+ t=m->DN_conv[i];m->DN_conv[i]=m->snap_conv[slot][i];m->snap_conv[slot][i]=t;
}
+ q38_dn_gpu_invalidate(m); /* the host swapped its state in: the card's copy is from the rejected draft */
- if(m->snap_ple){
- float *t=m->PLE_conv_state;m->PLE_conv_state=m->snap_ple;m->snap_ple=t;
- memcpy(m->ple_history,m->snap_ple_history,sizeof(m->snap_ple_history));
- m->ple_history_len=m->snap_ple_history_len;
+ if(m->snap_ple[slot]){
+ float *t=m->PLE_conv_state;m->PLE_conv_state=m->snap_ple[slot];m->snap_ple[slot]=t;
+ memcpy(m->ple_history,m->snap_ple_history[slot],sizeof(m->snap_ple_history[slot]));
+ m->ple_history_len=m->snap_ple_history_len[slot];
}
m->kv_len=len;
if(m->kvp.len>len)m->kvp.len=len;
diff --cc docs/ENVIRONMENT.md
index 7fb3a5f0,6c2661d2..03256d0c
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@@ -515,14 -482,13 +515,15 @@@ checkpoint layout and the text-only cap
| `Q38_NATIVE_FP8` | `1` (on) | Keep routed E4M3 expert bytes and their F32 128×128 block scales native in the LRU. `=0` restores expanded-FP32 slots for A/B validation. |
| `Q38_NATIVE_BF16` | `1` (on) | Keep resident and routed BF16 matrices in two-byte storage while retaining FP32 activations/accumulation. `=0` restores the expanded-FP32 reference. |
| `Q38_EXPERT_INT4` | auto | Routed experts from `<snap>/experts-int4g64/`, the int4-g64 sidecar `tools/convert_qwen38_experts_int4.py` writes next to the FP8 shards: 2.76 MB per expert instead of 4.92 MB, so the same RAM holds 1.78x the experts and a miss reads 56% of the bytes. Unset: used when its `index.json` says the conversion is complete (an incomplete one is skipped with a line on stderr; one that disagrees with the model is refused). `=0` keeps the snapshot's FP8 experts; `=1` refuses to start without a complete sidecar. The CUDA expert tier streams FP8 only and stays off with int4 experts; `coli plan` / `--auto-tier` size the cap with the sidecar's records. See [qwen38.md](qwen38.md#routed-experts-as-int4-g64). |
-| `Q38_MTP` | `0` (off) | `=1` loads the checkpoint's MTP head and decodes speculatively: the head drafts the next token and one forward over two rows verifies it; a rejected draft rolls the DeltaNet/PLE state back to a copy taken after the first row. The output is that of plain decoding, greedy or sampled. A checkpoint without an MTP head is refused. Acceptance and tokens/forward go to stderr at the end of a run and after every served turn. Measured on the release with the int4-g64 sidecar: 1.94 tokens/forward and 12-14% more tokens/s, the expert reads from disk being the same with and without it. See [qwen38.md](qwen38.md#speculative-decoding-with-the-mtp-head). |
+| `Q38_MTP` | on when the checkpoint has the head | Loads the checkpoint's MTP head and decodes speculatively (`0`: plain decoding, the head unread; `1`: required, a checkpoint without it is refused; unset, a checkpoint without it decodes plainly with a line): the head drafts the next token and one forward over two rows verifies it; a rejected draft rolls the DeltaNet/PLE state back to a copy taken after the first row. The output is that of plain decoding, greedy or sampled. A checkpoint without an MTP head is refused. Acceptance and tokens/forward go to stderr at the end of a run and after every served turn. Measured on the release with the int4-g64 sidecar: 1.94 tokens/forward and 12-14% more tokens/s, the expert reads from disk being the same with and without it. See [qwen38.md](qwen38.md#speculative-decoding-with-the-mtp-head). |
| `Q38_MTP_WIRING` | `b` | How the MTP head normalizes the model's four streams before `fc_hidden`, which the tensors leave open: `b` one norm per stream (the reading the trained weights agree with: 94-96% of drafts accepted on the release), `a` one norm over all four streams as one vector (85-92%; a diagnostic). Only the acceptance rate depends on it, never the output. |
| `Q38_MTP_CAP` | the cap | Expert cache of the MTP head's layer. Its experts are the snapshot's FP8 even beside the int4-g64 sidecar; the startup line prints what the cache costs full. |
-| `Q38_MTP_FORCE`, `Q38_MTP_DUMP` | unset | Tests only: `reject` rolls back every draft, `accept` / `mixed` draft the reference's next token (always, every other one) in `ref.json` mode; `Q38_MTP_DUMP=<file>` writes every draft's row, token and logits. |
+| `Q38_MTP_DRAFTS` | `2` | With the MTP head on: the MTP head's drafts per verify, `1` to `3` (the deeper ones read the head's own streams), or `0` / `auto` to let the gate pick 0 to 3 per verify from the measured acceptance and verify cost. A verify of `k` drafts copies the recurrent state after `k` rows (113 MiB each). The default 2 measured fastest on a Ryzen 7 PRO 8700GE, on the CPU and in the Vulkan dense chain; `1` is the one-draft verify that came before. See [speculative.md](speculative.md). |
+| `Q38_MTP_FORCE`, `Q38_MTP_DUMP` | unset | Tests only: `reject` rolls back every draft, `accept` / `mixed` draft the reference's next token (always, every other verify) in `ref.json` mode, `cycle` moves the wrong draft over the rows verify by verify, `row1`..`row3` makes that draft wrong; `Q38_MTP_DUMP=<file>` writes every first draft's row, token and logits. |
+| `COLI_LOOKUP`, `COLI_LOOKUP_DRAFTS`, `COLI_SPEC_GATE`, `COLI_LOOKUP_FORCE` | `1`, `5`, `1`, unset | Prompt-lookup drafts, as for qwen36 below; on qwen38 combined with the MTP head (a verify carries the proposal worth more per unit of time). |
| `Q38_PREFILL_BATCH` | `1` (on) | Route prompt rows in bounded expert-major chunks and batch resident shared-expert/DeltaNet projections. `=0` restores row-at-a-time prompt execution for A/B diagnosis; decode is unchanged. |
| `Q38_TRUNK_CPU_INT8` | `1` (on) | The dense trunk (DeltaNet and attention projections, hyper-connection mixers, shared expert, router, lm_head; every matrix of at least `Q38_TRUNK_MIN_KB`) is kept on the CPU as int8 rows with one scale per row and the BF16 copy is released; `q38_weight_matmul` quantizes the activation to int8 and uses the integer kernels of `idot.h` for decode and prefill. `=0` keeps the BF16 rows and the f32 kernel (the numeric reference). See [qwen38.md](qwen38.md#the-trunk-on-the-cpu-int8-rows). |
+ | `Q38_DN_GPU` | `0` (off) | CUDA expert tier with the trunk in VRAM: a decode token runs every DeltaNet layer whose `dnqkv`, `dnz` and `dnout` sit on one card end to end on that card (conv, recurrence, gated norm; state resident in VRAM). See [qwen38.md](qwen38.md#the-deltanet-layer-on-the-card-q38_dn_gpu1). |
| `COLI_MAP_EXPERTS` | `0` | Point the native-FP8 routed-expert slots (or the int4-g64 sidecar's records) at a read-only mapping of their shard instead of copying 14 MB per miss into a slab. Same variable as in `glm53`. |
| `Q38_FP8_KERNEL` | vector | The routed experts' e4m3 blocks are decoded eight at a time in registers and multiplied with FMA (AVX2 builds); `scalar` restores `quant.h`'s table kernel, which differs only by float summation order inside a block. |
| `COLI_TIMERS` | `0` (off) | Set to `1` for the detailed Qwen3.8 phase breakdown on stderr. The shared per-request `PROF` frame is emitted regardless. |