Skip to content

DeepSeek-V4.1-Flash runtime (jang_tools.dsv41): Engram, dSpark, vision, suffix pruning, fused decode - #29

Merged
jjang-ai merged 56 commits into
mainfrom
feat/dsv41-flash-jang-runtime
Oct 26, 2026
Merged

jjang-ai merged 56 commits into
mainfrom
feat/dsv41-flash-jang-runtime

Conversation

@jjang-ai

Copy link
Copy Markdown
Owner

DeepSeek-V4.1-Flash (model_type: deepseek_v41) runtime for vMLX Python: jang_tools/dsv41/ (backbone, caches, Engram, vision, dSpark) and the engine wrapper in jang_tools/dsv4_1/mlx_model.py.

Docs: jang_tools/dsv41/RUNTIME_SERVING.md (opens with a speed ledger: what was slow, the fix, where it lives, measured change) and DECODE_DSPARK_METHODS.md.

What's in it

  • Runtime: hyper-connections, compressed sparse attention with the shared indexer, 4-bit compressed-KV / index pools (905 MiB at 1M tokens), Engram tables read from SSD by row (16 concurrent gathers, per-layer lazy reads, next-chunk lookahead), in-bundle vision tower, fp32 LM-head input.
  • dSpark 3-stage speculative decode: one verify forward per step, in-place partial-accept commit, wall-clock governor (never below AR), prefix-cache boundary snapshots with the draft-window seed.
  • Prefill: group-major wo_a, fused DSA index scores (vMLX kernel, M5 matrix units with bf16 operands), block top-k for long rows, prompt-suffix pruning (layers 21-39 run only the rows the prompt end reads; exact at the prompt end).
  • Decode: per-layer async eval, bf16 router GEMV, 2-dispatch routed + shared MoE, fused hyper-connection stage (metal_decode.py, bit-exact).

Measured (M5 Ultra 256 GB, vmlx serve, dSpark on, cold unique text)

  • Cold prefill 845 / 1331 / 1554 pp/s at 1.6k / 6.5k / 26.5k; without the draft 1452 / 1641 / 1584 at 8k / 32k / 100k.
  • Decode code / code2 / structured / prose 90.2 / 62.3 / 111.9 / 38.7 tok/s; plain greedy 39.2 (2k) / 34.3 (100k); TTFT 0.21-0.46 s.
  • RAM prefix hit 3.38 -> 0.36 s, SSD hit after restart 0.34 s; per-tool-call persist 2-118 ms; multimodal + image reuse; footprint 206.9 GB.

Tests

tests/dsv41_*_test.py (decode fusion bit-equality, top-k, attention gather, cache state, governor) and jang_tools/dsv41/tests/ (suffix pruning == full prefill, commit_prefix, Engram I/O) pass; tests/serve_acceptance.py is the end-to-end serving check.

Add the validated jang_tools.dsv41 runtime and the jang_tools.dsv4_1 vMLX engine
wrapper for the DeepSeek-V4.1-Flash-1017 Q2Q3 affine bundle.

jang_tools/dsv41/ (standalone runtime, proven token-identical to reference):
- model.py: DSV41 (MLA + Engram taps + 128-expert MoE + vision tower), Session
  cache with checkpoint/restore, forward(ids, images, token_types).
- engram.py: disk-only FP8 n-gram tables (concurrent pread + memmap, OS page
  cache; never resident).
- vision.py: ViT + Aligner + prepare_vl_inputs (parity-verified vs torch ref).
- dspark.py: 3-stage DSpark MTP draft + DSparkRunner accept/reject loop; loads
  the prestacked draft from a bundle dspark/ subdir or quantizes from source.
- convert_dsv41_jang.py: source -> JANG mixed affine bundle (q2/q3 routed, q8
  attn/shared, engram on disk).
- convert_dspark_jang.py: emit a self-contained dspark/ subdir (4-bit draft).
- st_io.py, calib_*, generate.py, verify_source.py, tests/.

jang_tools/dsv4_1/ (engine-facing):
- mlx_model.py: Model wrapper exposing make_cache()/__call__(images,token_types)
  over the DSV41 runtime; load_deepseek_v41().
- mlx_register.py: registers deepseek_v41 into mlx_lm.models.

Live-proven in vmlx serve: text + reasoning + JSON tool calls + multimodal
(image across turns) + SSD/RAM caching; DSpark speculative 1.03-1.26x from the
self-contained bundle.
…scripts

DSparkRunner gains an adaptive mode: an acceptance EMA shrinks the draft width as
acceptance falls and falls back to pure-AR steps (no draft/verify overhead) under
sustained low acceptance, re-probing every N steps. Standalone vs plain AR (n=80):
code 1.42x, structured 1.36x, low_accept 1.50x; worst case (open-ended prose,
24% base accept) improves 0.87x (fixed) -> 0.97x (adaptive). Strict >=AR is not
achievable for speculative decoding on adversarial low-accept content (detection
needs probing that costs); adaptive keeps the worst case within ~3% of AR while
typical content gets 1.3-1.5x. Additive: adaptive defaults off.

- calib_metrics.py: teacher-forced quant metrics — top-1 next-token accuracy +
  top-1 prob / NLL / entropy percentiles (mean/median/p95/p99). IMATRIX bundle:
  top-1 58.8%, NLL mean 2.35 / median 0.48 / p95 10.98, PPL 10.44 (24 rows).
- eval_mtp_ar.py: speculative-vs-AR ratio across prompt types.
Replace the periodic-probe fallback with a latch: after `latch_after` (default 2)
consecutive zero-accept drafts, switch to BARE greedy (no draft, no verify, no
hidden extraction, no window upkeep) for the rest of the generation — byte-for-byte
AR cost. The short detection transient amortizes to ~0 on realistic generations.

Standalone vs plain AR (n=200): code 1.37x, structured 1.37x, low_accept 1.47x,
prose (22% base accept) 0.84x fixed -> 1.01x adaptive. MIN spec/AR ratio 1.01x
=> NEVER-BELOW-AR PASS (was FAIL at 0.84-0.97x with the probe approach).
kl_eval.py: two-pass KL so two ~211 GB models never co-reside. `--mode dump` saves
per-position full log-probs (fp16) + true token over seed-stable held-out rows;
`--mode kl` diffs two dumps -> KL(ref||cand) + top-1 agreement, mean/median/p95/p99.
Validated: self-KL = 0.0, top-1 agreement = 1.0; quant-side dump produced (2444
positions, cand top-1-vs-true 60.3%). The reference pass needs a >256 GB host for
the fp8 source (286 GB > this Studio's RAM) or a re-emitted complete RTN (routed
shards 201.6 GB > 131 GB free disk here) — then KL runs with one command.

prefill_probe.py: raw standalone prefill pp/s (no engine) — 741@512 -> 865@4096,
warm (engram OS-cached) = pure MoE compute. Enlarged attn/indexer chunks gave no
gain (empirically tested), so 1000 pp/s needs a Metal-kernel port, not config.
…n-place indexed, sink in combine)

Vendored glm5_mla_decode_attn as metal_decode_attn.py: 64 heads x rank512 shared
latent, bf16 rows read in place by index (no mx.take gather, no fp32 latent copy),
fp32 accumulation; V4.1 attn_sink folded into the combine pass as an extra
exp(sink-M) denominator term. Equivalent to _attn_core (cos 0.999999, rel 3e-3 bf16).

Wired into sparse_attention for the S==1 decode step behind VMLX_DSV41_DECODE_ATTN,
default OFF: validated correct but a wall-clock wash (31.08 vs 31.42 tok/s) because
decode is dispatch/occupancy-bound, not attention-compute-bound. Kept as the building
block for a full fused per-layer decode chain.
eval_mtp_ar.py built the adaptive runner as DSparkRunner(..., min_accept=0.4),
but the runner was refactored to EMA width-shrink + latch_after and has no
min_accept parameter (and no **kwargs), so constructing the adaptive runner
raised TypeError -- the smart MTP path never ran through the harness.

Use the live API (adaptive=True). Verified on IMATRIX, n=80: adaptive floors
never-below-AR (MIN 1.01x: code 1.37x, structured 1.35x, low_accept 1.47x,
prose 1.01x where fixed-width is 0.86x).
When the entire draft block is accepted (k==W), the verify forward has already
written exactly-correct causal KV for every accepted position (no rejected tail
to undo), so the restore+refeed commit forward is pure waste. Skip it: keep the
verify cache, defer truth[W] (the free bonus token) to the next step's p0 via
pending=vlog[W]. One backbone forward per step instead of two on high-accept
content. Partial-accept steps keep the exact restore+refeed path unchanged.

Measured (IMATRIX M5 Ultra, n=80, adaptive): code 1.37x->1.88x (55.7 t/s),
structured 1.35x->2.00x (57.1), low_accept 1.47x->1.93x (50.1), prose 1.01x->1.04x;
MIN 1.04x (never-below-AR PASS). Output token-identical to plain greedy on
code/structured (first-divergence=None), i.e. correctness unchanged.
…mlx-swift)

Canonical cross-machine reference for the validated V4.1 methods: DSpark loop
(token-identical, off-by-one seed, no-refeed fast path), adaptive never-below-AR
latch, the measured single-stream decode floor (MLX qmv ~50% bw at M=1, MTP is
the lever), and the MLA decode-attn kernel. Co-located with dspark.py so the
engine SBG wiring and vmlx-swift SpecDec can mirror it verbatim.
…ver)

Refactor generate() to delegate to a new stream() generator that yields committed
backbone-greedy tokens one at a time (so the vMLX engine's SBG spec-decode path can
stream + check stops between/within accepted blocks) and owns its own runtime Session,
independent of any engine cache. Loop logic unchanged incl. the no-refeed fast path.
Verified: eval ratios preserved (code 1.90x/structured 2.00x/low_accept 1.84x/prose 1.04x,
MIN 1.04x) and output token-identical to greedy (code 59/59, structured 29/29).
Engine V4.1 DSpark spec-decode is wired (vmlx bf1ce697): draft load + DSV41DSparkGenerator
over DSparkRunner.stream + scheduler selection, verified live ~65.9 tok/s vs AR ~31.
Root cause: the release reference stores the sparse-attention cache in low
precision (compress_kv FP4, index_k FP4, sliding window FP8), but this MLX port
stored all three in bf16 -> ~3.6x bloat (measured 3205 MB projected @ 1M).

Fix: new QuantGrowBuffer stores compress_kv / index_k rows 4-bit (affine, group
GROUP_SIZE); quantize-on-append, dequantize-on-view for the attention/indexer
read path (the reference dequantizes on read too). Session.checkpoint/restore use
each buffer snapshot()/load(). Window stays bf16 (constant ~5MB, negligible).

Measured: 1M projected RESIDENT cache = 905 MB (target ~890). Quality intact:
fib code correct, 17*23=391, primary colors correct. Moves toward reference (which
itself runs an FP4 cache), not away.
…x cache WORKS together)

The AR serving path uses DeepseekV41Cache (was bf16 ~3.2GB@1M). Make its compress_kv/
index_k 4-bit RESIDENT (QuantGrowBuffer) -> ~890MB@1M live cache. A first attempt that
serialized the pools as 3 arrays (wq/scales/biases) broke prefix_cache reconstruction of
the 4 kv-source layers (36/40 -> cache miss); fixed by keeping state() = the DEQUANTIZED
bf16 (one array per pool, UNCHANGED serialization format) and re-quantizing on restore via
QuantGrowBuffer.load_dense. Resident is 4-bit; stored prefix blocks stay bf16.

Verified live (vmlx serve --use-paged-cache, 657-tok prompt x2): turn2 cached=656 (paged
HIT, 40/40 layers reconstructed, no failure), coherent. So 890MB live cache + per-tool-call
prefix cache (SSD/RAM, eviction) work TOGETHER on the AR path. Multimodal mid-turn also
re-proven with an aligned image (image->Red, continuation->Strawberry).
…brid prefix-cache coexistence

- dspark.py: split stream() into prefill() (prefills to the clean prompt boundary; accepts an
  external session + start_offset, clamps to leave >=1 token, trims an over-restored cache) and
  decode_stream() (the greedy verify/accept/no-refeed loop). generate() unchanged behavior.
- mlx_model.py: _SeqState.checkpoint/restore (QuantGrowBuffer snapshot/load) for driving the engine
  cache through a DSpark verify rollback.
These enable DSpark to run on the engine cache; the hit-continuation off a restored composite
MLA+DSA+engram prefix still has an index_k restore mismatch, so the engine generator keeps DSpark on
its OWN session (fast, coherent) and delegates prefix HITS to the proven AR path (full 890MB + prefix
cache). Verified: DSpark cold coherent, no recovery errors.
…tart_offset slicing

The scheduler's prefix-hit contract passes only the UNCACHED TAIL as prompt_tokens with the cache
already restored, so prefill() now forwards prompt_ids AS GIVEN from the session's absolute position
(sess.pos) and returns the absolute frontier c = start+len-1 (no start_offset slicing/trimming, which
double-counted and trimmed the whole restored prefix). Behavior-preserving for the cold path (pos=0);
correct for a restored session. start_offset kept as an ignored back-compat arg.
…tch)

The adaptive runner no longer locks into bare greedy for the rest of a
generation after two zero-accept drafts. It enters a low-overhead AR mode
but keeps the draft windows current and probes once every probe_every
tokens, leaving the mode the instant a probe accepts -- so draft depth is
acceptance-governed and recovers on mixed reasoning->code content. Width
tracks the acceptance EMA within the draft head's physical size bs; no
fixed/hard MTP depth is enforced. Output stays token-identical to greedy
(verified) and recovery is proven on a low-accept->easy prompt.
export_engram_aux.py writes engram_aux.safetensors (token_map / multipliers /
primes / offsets + scalar layout) from the bundle, reusing the proven NgramHasher
setup so the Swift engram port skips HF-tokenizer normalization. The vmlx-swift
DeepSeek-V4.1 runtime loads this sidecar for its n-gram hashing.

tests/verify_dspark_adaptive.py asserts the recoverable adaptive DSpark is
token-identical to greedy and that drafting recovers after a low-accept stretch
(no permanent AR latch).
…fill 3-8x)

Cold prefill was bound by Engram row I/O, not compute: each position reads 24
random 256-byte rows per Engram layer from the ~98 GB on-disk tables, and the
prefill path gathered them through a memory map, one page fault at a time
(~8-11k rows/s, ~14 s for a 1024-token unique prompt). With warm pages the same
forward ran 748-830 pp/s.

- DiskEngramTable reads rows and scales with concurrent pread for every batch
  size (64 lanes, 256-row tasks, preallocated buffers): ~130k cold rows/s.
  read()/prefetch()/finish() split the host read from the MLX dequant.
- DSV41.forward runs text prefill longer than 256 tokens in sub-chunks
  (128, then 512) with every sub-chunk's rows requested up front, queuing
  each sub-chunk's forward with async_eval as its rows land.

Cold unique-text prefill (standalone runtime, M5 Ultra): 1024 tok 68 -> 527 pp/s,
4096 tok 459 -> 653 pp/s, 8192 tok 382 -> 677 pp/s. Pipelined output equals
chunked continuation with the same bounds bit for bit (max |dlogit| 0).
test_engram_io.py: pread == memmap gather, prefetch == lookup.
…unk lookahead

Replaces the token sub-chunk pipeline from ae82d16: every extra forward
re-streams the routed experts' weights (~0.14 s fixed cost), so splitting a
chunk into sub-chunks cost more than the reads it hid.

- One forward per chunk. Layer 1's rows are read up front; later Engram layers'
  rows arrive as a callable the forward resolves when it reaches them, after
  async_eval'ing the layers before, so their reads overlap GPU work. Layer
  reads are chained (first layer first) so it gets every I/O lane.
- forward(engram_lookahead=next_chunk): the next prefill chunk's hashes and
  reads start while this chunk computes; the record is consumed only when the
  next forward's start position and token ids match (else discarded).
  dsv4_1 Model.__call__ forwards the kwarg.
- Reader: 16 threads gathering memmap slices (GIL released in np.take) with
  MADV_RANDOM, ~110-146k cold rows/s; DSV41_ENGRAM_IO=pread keeps the 64-lane
  pread reader.

Cold unique-text prefill, 2048-token engine chunks (standalone, M5 Ultra):
1k 598, 2k 713, 4k 756, 8k 768, 16k 746 pp/s (warm 741-801).
Logits bit-identical to the eager path at every size.
…ct prefill parity claim

RUNTIME_SERVING.md: residency, Engram I/O and prefill design rules (one
forward per chunk, per-layer lazy rows, next-chunk lookahead), prefix-cache
and per-tool-call persistence contract, multimodal rules, measured serving
results and open items. tests/serve_acceptance.py drives a real vmlx serve
process and reports cold prefill, decode by content type, TTFT, prefix /
tool-turn reuse, multiturn, multimodal, reasoning leaks and phys_footprint.
DECODE_DSPARK_METHODS.md: the 865 pp/s prefill figure was page-cache warm.
…aft windows

Defects:
- DSparkRunner.prefill forwarded the whole prompt in one call and the engine
  snapshotted after it, so the prefix cache stored N tokens of state under the
  scheduler's prompt[:-1] key. Every hit re-fed the last prompt token at
  position N (duplicated <think>, shifted positions/compressor groups/engram).
- The one-shot prefill skipped chunking, per-chunk eval and clear_cache, so a
  long prompt was one lazy graph.
- DSparkAttention.window was a GrowBuffer holding every committed position
  (~3 KB/token, ~3 GB at 1M) although attend only reads the last 128 rows.
- seed_windows forced a blocking mx.eval every committed step.

Fix:
- prefill(prompt, on_boundary=..., chunk_size=...) forwards prompt[:-1] in
  chunks (eval + clear_cache per chunk), calls on_boundary(sess) at exactly
  N-1, then forwards the last token alone (same shape as the engine AR path).
- Draft windows are a BoundedWindow (last win rows, functional updates so ref
  checkpoints stay valid) and are seeded only from the last win positions.
- seed_windows submits with mx.async_eval instead of a host sync.
…refuse lossy trim

Defects (audit items 7, 11, 12):
- DeepseekV41Cache.state emitted the dequantized bf16 view of the 4-bit
  compressed/index pools and restore re-quantized it: not bit-exact, ~3.6x the
  bytes (~3.3 GB per 1M-token entry), and the numpy block store widened that
  bf16 to float32 (~6.4 KB/token on SSD -- the measured 7-10 KB/token with the
  fixed windows on top; the composite state is NOT duplicated per block).
- trim() was lossy (cannot rebuild the window, wrong pool math, cleared pend)
  while is_trimmable() said True; restored caches got ratio 0 because the
  engine reads a compress_ratio attribute that did not exist.
- Model.__call__ silently fell back to the runtime's shared session when
  handed a non-DSV4.1 cache list (e.g. a generic restore's empty KVCache).

Fix:
- Format v2 state: window, ck/ik wq+scales+biases (first n rows), pend,
  layer-0 history; bf16/f16 carried as uint16 bits, original dtypes in meta.
  Restore is bit-exact. A stored entry is ~0.9 KB/token (~0.9 GB per 1M
  tokens) + ~5.2 MB windows + 4 B/token history. Pre-v2 entries raise
  (rejected, never migrated: they were bf16 round-trips stored at the wrong
  prompt boundary).
- clone_cache_list(): compact bit-exact snapshot copy sharing one _SeqState
  (one history copy instead of one per layer).
- from_state() classmethod; compress_ratio / sliding_window properties
  (ratio-0 layers report None); meta carries the ratio.
- is_trimmable() False, trim() a no-op returning 0.
- Model.__call__ raises on a non-DeepseekV41Cache cache list.
- tests/dsv41_cache_state_test.py: bit-exact round trip (direct and via
  numpy), order-independent setters, stale-format rejection, clone
  exactness/compactness/independence, bytes per token at real geometry.
…oist markov cast

Defects (audit item 8):
- Adaptive mode entered AR only after consecutive zero-accept drafts; any
  k>=1 reset the streak, so low-but-nonzero acceptance kept speculating even
  when each rejecting step (draft + verify + restore/commit forward) cost
  more per token than plain AR.
- DSpark.draft re-cast the bf16 markov head (vocab x rank, ~130 MB) to f32
  on each of the bs steps and synced the host on every step's argmax.
- The docs claimed provable token identity with plain greedy; a multi-token
  verify forward is not bitwise identical to a one-token decode forward.

Fix:
- _Governor: EMA seconds per emitted token for spec and AR steps, measured
  step start to step start. Speculate only while faster than AR; in AR mode a
  speculative probe every probe_every AR tokens (replaces the stale
  estimate); in spec mode an AR re-measure every ar_probe_every steps. No
  terminal state. DSparkRunner takes an injectable clock.
- markov_chain(): f32 transposed head cached once per DSpark, chain kept on
  the device (one sync per block).
- Docstrings/DECODE_DSPARK_METHODS.md corrected.
- tests/dsv41_dspark_governor_test.py: synthetic timing model -- output ==
  greedy; zero / slow-partial acceptance within 6-8% of AR with probes still
  firing; full acceptance < 0.45x AR time; mid-stream recovery; governor has
  no terminal state; markov_chain == the reference loop.
A module-level mx.set_default_device(mx.cpu) leaked into the rest of a
pytest session. Use an autouse fixture that restores the previous device.
…ed on prefix hit

Defect (audit item 14): after a prefix hit DSparkRunner.prefill reset the
draft windows and seeded them only from the uncached tail, so drafting
after a hit started with a nearly empty 128-slot window (low acceptance for
the first ~128 tokens of every warm turn).

Fix:
- DSpark keeps the projected main hidden of its last win committed
  positions (main_tail(); seed_from_main_x() seeds from projected rows).
- _SeqState.dspark_tail is serialized on layer 0 (format v2 'dsp_x' +
  meta dsp_p0, bit-exact, ~1 MB per entry), carried by _relink and by
  clone_cache_list only when it ends exactly at the boundary.
- prefill() reseeds the windows from it when it ends at the restored
  position; otherwise unchanged (AR-produced entries have none).
- tests: tail round-trip/clone staleness; runner reseeds only on an exact
  boundary match.
…ol dequant per forward

Defect (audit item 5): every forward dequantized the WHOLE 4-bit compressed
pool view(T) in each consumer layer, concatenated it to the window and cast
it to fp32 inside sparse_attention -- ~0.5-1 GB per layer per decode token at
1M context -- although a decode query reads only index_topk rows. Shared
pools were re-dequantized by every consumer (layer 20's index pool by 5
indexers, each compressed pool by up to 6 attention layers).

Fix:
- QuantGrowBuffer.gather(idx): dequantize only the requested rows.
- append_compressed_rows(): for <= GATHER_MAX_QUERIES (8) queries per
  segment (decode, DSpark verify) dequantize only the S*topk selected rows
  and give each query its own slots in the same order -- bit-identical
  attention; prefill chunks keep the full-pool path.
- Shared.view(): per-forward memo, so a shared pool is dequantized once per
  forward (lives only as long as the forward's Shared, nothing extra stays
  resident).
- _compressed returns the visible row count; the caller reads the pool.

Verified: tests/dsv41_attention_gather_test.py (gather == full pool
sparse_attention, bit-exact, S in {1,3,6}; memo tracks appends) and the small
random-model forward (parity_reference bundle, chunk plan 37+1+1+1+1+50 incl.
four S=1 decode steps) produces bit-identical logits before/after on CPU.
Not changed: DSV41.forward / _engram_rows (owned by the engram I/O work).
Each prefill chunk forward now hands DSV41.forward the token ids of the next
forward (the next chunk, or the final prompt token after the last body
chunk), so its Engram rows are read from SSD while the current chunk
computes -- the pipelined text prefill the AR path got in ae82d16/623fd96.
Backbones whose forward lacks the kwarg (test fakes) are called as before.
Test: lookahead of every chunk == the next forward's ids, none on the last.
…t-resident 1024 chunks), merged serving results, open items
…Spark identity claim

The quantized head took bf16 input and produced bf16 logits, whose top-2
tied exactly every ~50-100 tokens; a batched verify forward broke those ties
differently from single-token decode. fp32 head input gives fp32 logits
(reference: F.linear(x.float(), weight)) with no measurable decode cost
(DSpark code/code2/structured/prose 44.7/39.3/76.9/28.6 tok/s vs
45.4/39.9/78.2/28.6 before). Remaining DSpark-vs-AR differences come from
batch-shape-dependent bf16 backbone numerics and sit at near-ties (AR top-2
margin 0.0045-0.040); the docs now say so instead of 'token-identical'.
A partial accept (0 < k < W) used to restore the checkpoint and run a second
forward over [p0, d1..dk, truth[k]]. The verify forward already computed the
exact causal cache inputs for its first k+1 tokens, so DSV41.commit_prefix
now restores the checkpoint and replays only those tokens' cheap cache
updates: window rows, compressor pooling on the captured projections
(pending tail, completed groups, compressed / index pool rows with the same
RoPE positions), Engram history and position. truth[k] becomes the next p0.
forward(capture_verify=True) stashes references to the per-token inputs.
k == 0 keeps the refeed (cheaper per token there). VMLX_DSV41_DSPARK_REFEED=1
restores the old path for A/B.

Standalone, 256 tokens, chat prompts (M5 Ultra): code 44.9 -> 57.5 tok/s,
code2 41.3 -> 48.7, Rust 50.9 -> 59.1, prose 28.8 -> 28.8, structured
81.6 -> 74.9 (acceptance 0.99 -> 0.96 with different step boundaries).
test_commit_prefix.py: commit_prefix(W+1) equals the capture forward's own
state bit for bit; partial keeps match a forward of only the kept tokens
(row counts exact, values within bf16 batch-shape tolerance).
…7); DSpark default-on and VL-tail gating (stale 'default OFF' / 'text-only')
…2 51.1 tok/s), verify-width cost curve, row-exact QMV status
…was first-request warm-up); block-disk namespaces per engine build
…en -> 0.88 GiB resident, 0.89 GiB stored at 1M)
…ll 708 -> 909 pp/s)

wo_a is block-diagonal over 8 groups. The forward reshaped the attention
output to [tokens, groups, 1, K], so a 2048-token prefill chunk ran one 1-row
quantized product per token per group: 18.6 ms per layer, a third of the
layer's time. For more than GATHER_MAX_QUERIES rows it now runs group-major
([groups, tokens, K] @ [groups, R, K]^T): 2.1 ms per layer. Decode and DSpark
verify (<= 8 rows) keep the per-row products, so each verify row stays
computed exactly like a 1-row decode. WO_GROUP_MAJOR = False restores it.

Draft resident, 1024-token chunks, 12k-token cold prompt (standalone engine
wrapper): 708 -> 909 pp/s. Numerics: prefill logits vs the old layout mean
cos 0.9954, top-1 agreement 98.4%, greedy continuation identical; moving the
chunk boundaries (1024 vs 512) with the old layout already differs more
(mean cos 0.9943, min 0.73).
serve_acceptance.py: --no-vision for text-only bundles (DSV4-0731).
…72 pp/s; resident-memory cliff data; harness samples memory only after timed checks
The indexer materialized [C, heads, T] bf16 scores and ran relu, the head
weighting and the head sum as separate passes, in query chunks shrinking
with context (20 queries per chunk at 100k keys: ~100 iterations per index
layer per forward, 8 index layers). Prefill now uses vMLX's fused
dsa_pool_index_scores Metal kernel (sum_h w * relu(q . k), fp32, one pass)
with query chunks sized to keep the [C, T] fp32 block near 1 GB:
164 -> 97 ms per index layer per 2048-token chunk at 100k keys. Optional
import; VMLX_DSV41_FUSED_INDEX=0 or no vMLX keeps the bf16 path. Decode and
DSpark verify (<= 8 rows) unchanged.

Cold prefill to 100k (2048 chunks, no draft): average 737 -> 821 pp/s;
40-50k window 809 -> 913; 88-100k 658 -> 775. Numerics vs the bf16 path:
prefill logits mean cos 0.9962, top-1 agreement 100%, greedy continuation
identical.
MLX's GPU argpartition sorts the whole row, so selecting the top-512 of
[queries, T] index scores dominated the indexer at long context. For rows of
65536+ keys, select the 512 blocks of 64 with the largest maxima (they hold
the top-512 values), then argpartition only their 32768 entries. Selected
values are identical to the direct path (only the pick among exactly tied
values can differ). Selection time: 32.7 -> 13.5 ms at 2048 x 100k,
51.9 -> 3.2 ms at 256 x 1M. dsv41_topk_test.py checks value equality.
…tored), long-context prefill windows to 1M, fused index scores + block top-k
…tition

At a 170k context, decode with the block top-k ran 23.9 vs 25.1 tok/s (one
row: the direct partition is cheaper) and, because decode index scores take
the bf16 path where exact ties are common, could pick a different member of
a tied set. Block top-k now needs more than GATHER_MAX_QUERIES rows.
Measured at 170k: decode tokens identical with and without the block path
(25.0 vs 25.1 tok/s), prefill 751 -> 791 pp/s.
…(fp16 fragments no faster); next lever M5 tensor ops
…has them

vMLX 391ea34f adds dsa_pool_index_scores(..., bf16_operands=True), which runs
the fused index-score kernel on the M5 matrix units (Metal 4 tensor ops):
~4.3x the fp32 simdgroup kernel at 2048 x 100k keys. The indexer passes its
bf16 q / index keys / weights as is (the reference scores in bf16) and falls
back to the fp32 fused kernel (older vMLX, unsupported GPU, or
VMLX_DSV41_INDEX_BF16=0), then the stock path.

Cold prefill to 100k (2048 chunks, no draft): average 831 -> 884 pp/s,
40-50k window 913 -> 963, 88-100k 818 -> 910. Numerics vs the fp32 kernel:
prefill logits mean cos 0.9964, top-1 agreement 100%, greedy continuation
identical.
…ows the prompt end reads)

Layers past the last KV-source / Engram / candidate-source layer own only a
128-token window, so for a prefill ending at prompt_end layer i needs just the
trailing 1 + (40 - i) * 127 rows (layer 39: 128, layer 21: 2414). The cache state
at prompt_end and the last-token logits match a full prefill.

Real model, cold prefill, 2048 chunks: 8k 1019 -> 1452, 32k 938 -> 1641,
100k 875 -> 1584 pp/s. 8k / 32k: logits cos 0.99996 / 0.99994, same top-5,
24/24 greedy tokens identical; window caches bit-identical through layer 27.
DSV41.forward(prompt_end=), engine wrapper kwarg, DSpark prefill body chunks.
VMLX_DSV41_SUFFIX_PRUNE=0 disables. CPU test: tests/test_suffix_prune.py.
…async_eval)

Decode and DSpark verify forwards (<= 16 rows) call mx.async_eval(h, pre_mix) after
every layer, so the GPU runs early layers while the host encodes later ones (ds4 #1261,
oMLX language.py). Bit-identical; VMLX_DSV41_LAYER_ASYNC=0 restores one eval per token.

Real-dimension synthetic stack (10 layers, ctx 1024, shared GPU): decode step
p10 9.29 -> 7.78 ms (1.19x), median 44.7 -> 16.8 ms under contention.

Adds tests/synth.py (random-weight DSV4.1 at tiny or bundle dims), tests/bench_decode.py
(in-process interleaved A/B) and tests/dsv41_decode_fusion_test.py (greedy + verify
logits bit-equal with the flag off and on).
…no per-call f32 copy

Block.moe cast the 384x5120 gate weight to f32 on every call. For <= 8 rows a Metal GEMV
(metal_decode.router_logits, MLX gemv BM4/SN32/TM4/TN4 order, the vMLX glm5_router_matvec
pattern generalized to any K % 128 / E % 16) reads the bf16 rows directly. Softplus, bias,
argpartition and normalization are unchanged.

Exactness: 1 row bit-identical to x.f32 @ w.f32.T (test + greedy logits bit-equal). 2-8 rows:
each row equals its own 1-row decode logits (stock switches to a GEMM, |diff| <= ~2e-6).
VMLX_DSV41_ROUTER_GEMV=0 restores the f32-cast matmul.

Router + routing per layer, 40 distinct gate weights chained in one graph (p10):
1 row 85.8 -> 67.8 us, 8 rows 123 -> 73 us (~0.7 ms/token decode, ~2 ms per 8-row verify).
…= 2048)

MLX's f32 GEMV switches to a split-K variant when K >= 16 * out rows, so the bf16-read
kernel was 1 ulp off for small expert counts (e.g. 16 x 1024). Measured: bit-equal on
60/60 inputs for (E, K) in {128..512} x {1024, 5120} inside the rule, mismatching outside.
The bundle (384 x 5120) is inside. Tiny synthetic model now has 128 experts so the
greedy tests exercise the kernel; tests sweep (E, K).
…serve MOE_GU/MOE_DN)

metal_decode.moe_decode replaces Block.moe's ~25 dispatches for <= 8 rows:
- moe_gu (F/8 x 7 slots x R): gate+up of the 6 routed experts (2/3-bit) and the shared
  expert w1/w3 (8-bit, slot 6) from one read of x; bf16 rounding where gather_qmm/qlinear
  round, clamped SwiGLU and route weight in f32 -> h [R, 7, F] bf16.
- moe_dn (D/4 x R, 7 simdgroups): down_proj / w2 per slot, bf16 round, f32 sum in slot order
  (MLX's sequential axis reduction) + shared -> y bf16.
Every projection is MLX's qmv_fast / qmv lane walk (transcribed), chosen by MLX's rule
(qmv_fast iff K % 512 == 0, 256 for 8-bit; measured on f32 outputs).

Exactness: 1 row bit-identical to stock Block.moe (tiny and bundle dims, 2/3-bit, inputs
into the SwiGLU clamp); greedy decode logits bit-equal flag off/on. 2-8 rows: each row equals
its own 1-row decode; vs the stock batch (qmm shared expert) <= 1% of max |y|.
VMLX_DSV41_FUSED_MOE=0 restores the stock path.

MoE+router per layer, 4 distinct bundle-dim layers chained (p10, shared GPU):
1 row 0.279 -> 0.226 ms, 2 rows 0.434 -> 0.407, 4 rows 0.460 -> 0.426, 8 rows 0.704 -> 0.676.
10-layer decode step 7.17 -> 6.85 ms (p10).

Also: synthetic norms are BF16 as in the bundle (f32 norms had made the earlier router test
fall back to the stock path); fusion tests now assert the kernel actually ran.
…rify (bit-exact)

Per sublayer ~14 dispatches (hc_mixes, hc_pre, RMSNorm, hc_post) become three
(metal_decode, mlx-serve HC_STAGE/HC_SPLIT, oMLX K1/K2):
- hc_stage: collapse with the previous pre + RMSNorm (MLX rms_looped / rms_single_row
  order), sum(x^2) (MLX row_reduce_looped order) and the 24 mixes (MLX gemv
  BM1 BN8 SM1 SN32 TM4 TN4, 6 threadgroups as MLX) in one dispatch;
- hc_split: mean, rsqrt, mixes * rs, then the _hc_split_metal Sinkhorn code;
- hc_post: post * h + comb^T . residual. Stock runs that einsum as an f32 GEMM on the M5
  matrix units in TF32 (MLX_ENABLE_TF32=1 default): comb truncated to TF32, products summed
  pairwise; reproduced exactly (full f32 when MLX_ENABLE_TF32=0).
A once-per-process self-check (_hc_fused_ok) compares against the stock ops on this
block's weights and keeps the stock path on any mismatch.

Exactness: stage/split/expand bit-equal to the stock ops at tiny and bundle dims; greedy
decode logits bit-equal flag off/on (tiny 6-layer and bundle-dim 6-layer models, with all
fusions on). Verify rows: each row = its 1-row decode (stock verify runs the mixes and the
einsum as TF32 GEMMs over rows); the fused verify is closer to sequential decode
(tiny model: max |logit diff| 1.61 -> 0.35). VMLX_DSV41_FUSED_HC=0 restores the stock ops.

hc stage per layer (stack with attention/MoE stubbed, p10, shared GPU):
1 row 0.183 -> 0.137 ms, 8 rows 0.314 -> 0.139 ms.
metal_decode.moe_decode_dedup (ds4 kernel_dsv41_moe_dedup_plan, TensorFold v4 routed()):
a one-thread plan lists the distinct experts (shared expert first, then routed experts in
first-use order) with their (row, slot) pairs; each threadgroup streams one tile of one
distinct expert once and runs the single-row lane walk for every pair; a last pass sums the
slots in order. Bit-identical to moe_decode's per-row path (tests at tiny and bundle dims,
2-8 rows, and a verify forward).

Measured (4 bundle-dim layers x 64 experts chained, min of 30 interleaved rounds, per layer):
rows    stock   fused   dedup
1       0.250   0.211   -
2       0.369   0.330   0.351
4       0.486   0.433   0.509
8       0.735   0.668   0.794
The per-row fused path is already bound by the distinct experts' bytes (repeated tiles hit
the GPU caches; a pair-major dispatch order also gave nothing), and the per-threadgroup pair
loop loses parallelism. So VMLX_DSV41_MOE_DEDUP defaults to 0.
…group

stack, 10 bundle-dim layers x 16 experts, ctx 1024, all four decode fusions off vs on, p10 under
a saturated shared GPU (95-98% busy from another process): 1 row 9.83 -> 8.05 ms (1.22x),
2 rows 12.19 -> 8.67 (1.41x), 6 rows 16.49 -> 12.39 (1.33x).
…31/1554 pp/s, DSpark code 90 tok/s

RUNTIME_SERVING: prompt-suffix pruning section (design, gating, exactness, 8k/32k/100k
cold prefill 1452/1641/1584 pp/s) and the 2026-10-26 serving round: cold prefill
845/1331/1554 pp/s at 1.6k/6.5k/26.5k, DSpark decode 90.2/62.3/111.9/38.7 tok/s,
TTFT 0.21-0.46 s, RAM hit 3.38 -> 0.36 s, SSD hit after restart 0.34 s, per-tool-call
persist 2-118 ms, multimodal + reuse pass, footprint 206.9 GB.
DECODE_DSPARK_METHODS: M3 corrected (AR decode was not at the floor), M5 fused decode
kernels: AR 29.0 -> 39.2 tok/s at 2k, 26.0 -> 34.3 at 100k, greedy tokens identical.
Removed (each measured, none faster): the standalone decode attention kernel
(metal_decode_attn.py, a wash at decode), MoE expert dedup across verify rows (slower
than the fused MoE), the DSpark refeed A/B switch for partial accepts, 64-lane os.pread
Engram reads (held the GIL), the unused GrowBuffer, the unused latch_after argument,
and the always-on WO_GROUP_MAJOR / HC_METAL toggles.

RUNTIME_SERVING.md opens with a speed ledger: for every prefill, decode and memory fix,
why it was slow before, the fix and where it lives, and the measured change.
metal_decode.py explains why decode was dispatch-bound (~150 dispatches per layer)
and what each kernel collapses.
…TF32 GEMMs

CI (macOS 15 runner) found:
- 13 new 'except Exception' sites (repo threshold 199) incl. 3 bare passes: each now
  catches what it guards (ImportError, OSError, TimeoutExpired, parse errors, kernel
  build/launch errors) and says why.
- json.load(open(...)) / json.dump(..., open(...)) / json.load(urlopen(...)) now use
  context managers.
- The fused hyper-connection expand reproduces the M5 matrix units' TF32 GEMM. On a GPU
  whose f32 GEMMs are not TF32 (or MLX_ENABLE_TF32=0) its 4-term sum follows another
  order; a random-stream self-check could pass by chance and real decode diverge. The
  path now enables only where f32 GEMMs measurably round to TF32 (metal_decode
  _gemm_rounds_to_tf32, probed with the expand's own einsum). Tests assert exactness
  there and the stock fallback elsewhere; both pass with MLX_ENABLE_TF32=0 and =1.
@jjang-ai
jjang-ai merged commit e3b5f39 into main Oct 26, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant