Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
c46b72c
dsv41: DeepSeek-V4.1-Flash JANG runtime + engine wrapper + DSpark draft
jjang-ai Oct 25, 2026
b5d44c7
dsv41: adaptive DSpark width (never-below-AR floor) + quant/MTP eval …
jjang-ai Oct 25, 2026
9d13e56
dsv41: DSpark adaptive latch guarantees spec >= AR (never-below-AR PASS)
jjang-ai Oct 25, 2026
844c70f
dsv41: KL/top-1 harness (ready for this quant) + prefill pp/s probe
jjang-ai Oct 25, 2026
7d8aebb
dsv41: port mlx-serve PR#911 MLA decode-attention kernel (fp32-acc, i…
jjang-ai Oct 25, 2026
aa6af84
dsv41: fix adaptive MTP eval crash (stale min_accept kwarg)
jjang-ai Oct 25, 2026
beb1a40
dsv41: DSpark no-refeed fast path (whole-block accept) -> ~2x decode
jjang-ai Oct 25, 2026
43a4fd5
dsv41: document exact decode/DSpark methods (blueprint for engine + v…
jjang-ai Oct 25, 2026
819bce7
dsv41: expose DSparkRunner.stream() generator (engine spec-decode dri…
jjang-ai Oct 25, 2026
fc0ea45
dsv41: mark engine DSpark wiring DONE + add vmlx-swift mirror note
jjang-ai Oct 25, 2026
6598b1a
dsv41: 4-bit (FP4-parity) DSA cache -> ~890MB @ 1M (was ~3.2GB bf16)
jjang-ai Oct 25, 2026
86e1adb
dsv41: 4-bit DSA cache in the ENGINE path too (890MB resident + prefi…
jjang-ai Oct 25, 2026
76013d5
dsv41: DSpark prefill/decode split + _SeqState checkpoint/restore; hy…
jjang-ai Oct 25, 2026
d3ef9f5
dsv41: prefill() forwards from sess.pos (prefix-hit contract), drop s…
jjang-ai Oct 25, 2026
3ad07c8
dsv41: DSpark adaptive governs depth, recoverable (no permanent AR la…
jjang-ai Oct 25, 2026
967fab7
dsv41: engram aux-table export (for vmlx-swift) + dspark adaptive verify
jjang-ai Oct 25, 2026
ae82d16
dsv41: concurrent Engram row reads + pipelined text prefill (cold pre…
jjang-ai Oct 25, 2026
623fd96
dsv41: overlap Engram reads with compute inside one forward + next-ch…
jjang-ai Oct 25, 2026
a1e1d85
dsv41: runtime/serving contract doc + serve acceptance harness; corre…
jjang-ai Oct 25, 2026
1ae29c2
dsv41 serve_acceptance: multimodal prefix-reuse check (stored-size co…
jjang-ai Oct 25, 2026
2bd89b4
dsv41 dspark: prefill at the N-1 prompt boundary, chunked, bounded dr…
jjang-ai Oct 25, 2026
5f3397f
dsv4_1 cache: serialize/clone the 4-bit pools as stored (format v2); …
jjang-ai Oct 25, 2026
f9e12c4
dsv41 dspark: wall-clock governor (never slower than AR, no latch); h…
jjang-ai Oct 25, 2026
2d9118b
dsv41 tests: scope the CPU default device to each test
jjang-ai Oct 25, 2026
fe8185d
dsv41 dspark: carry the draft-window seed in boundary snapshots; rese…
jjang-ai Oct 25, 2026
97ed53a
dsv41 model: decode gathers only the selected compressed rows; one po…
jjang-ai Oct 25, 2026
6ca8817
dsv41 dspark: chunked prefill passes the next chunk as engram_lookahead
jjang-ai Oct 25, 2026
ac5b88d
dsv41 RUNTIME_SERVING: serving memory settings (allocator floor, draf…
jjang-ai Oct 25, 2026
e234076
dsv41: fp32 logits from the LM head (as the reference); correct the D…
jjang-ai Oct 25, 2026
95ef4ea
dsv41 dspark: commit partial accepts in place (one forward per step)
jjang-ai Oct 25, 2026
960126c
dsv41 DECODE_DSPARK_METHODS: in-place partial-accept commit (M1 step …
jjang-ai Oct 25, 2026
68652f1
dsv41 RUNTIME_SERVING: final serving results (DSpark code 60.8 / code…
jjang-ai Oct 25, 2026
7c8babc
dsv41 RUNTIME_SERVING: SSD restore after restart 0.38 s (earlier 3 s …
jjang-ai Oct 26, 2026
c52269d
dsv41 RUNTIME_SERVING: measured KV at 8k/32k/128k (marginal 900 B/tok…
jjang-ai Oct 26, 2026
66966c2
dsv41: group-major wo_a for prefill (9x faster projection; cold prefi…
jjang-ai Oct 26, 2026
b58c03c
dsv41 RUNTIME_SERVING: group-major wo_a and serving prefill 822/933/8…
jjang-ai Oct 26, 2026
3c64d3a
dsv41: fused DSA index scores for prefill (long-context prefill +18%)
jjang-ai Oct 26, 2026
dc09b99
dsv41: block top-k for long index rows (exact; 100k keys 2.4x, 1M 16x)
jjang-ai Oct 26, 2026
a9565ad
dsv41 RUNTIME_SERVING: KV measured at 1M (905 MiB resident, 909 MiB s…
jjang-ai Oct 26, 2026
bb435ed
dsv41: block top-k for prefill rows only; decode keeps the direct par…
jjang-ai Oct 26, 2026
991d102
dsv41 RUNTIME_SERVING: serving prefill 822/955/940 pp/s, long-context…
jjang-ai Oct 26, 2026
195d6a3
dsv41 RUNTIME_SERVING: long-context prefill is indexer-compute-bound …
jjang-ai Oct 26, 2026
78b4843
dsv41: index scores on the M5 matrix units (bf16 operands) when vMLX …
jjang-ai Oct 26, 2026
4d455f5
dsv41 RUNTIME_SERVING: matrix-unit index scores, 100k cold prefill 88…
jjang-ai Oct 26, 2026
84a6f6d
dsv41: prompt-suffix pruning for prefill (layers 21-39 run only the r…
jjang-ai Oct 26, 2026
7a4d527
dsv41: submit each decode layer to the GPU as it is built (per-layer …
jjang-ai Oct 26, 2026
91661f1
dsv41: router logits from the bf16 gate weight (MLX f32 GEMV order), …
jjang-ai Oct 26, 2026
951b2d7
dsv41: router GEMV only where MLX uses the same tiling (K < 16 E, E <…
jjang-ai Oct 26, 2026
346f3af
dsv41: fused routed + shared MoE decode in two Metal dispatches (mlx-…
jjang-ai Oct 26, 2026
c43c5e0
dsv41: fused hyper-connection stage, split and expand for decode / ve…
jjang-ai Oct 26, 2026
d5fb6cf
dsv41: MoE expert dedup across verify rows (opt-in; no gain on M5 Ultra)
jjang-ai Oct 26, 2026
315e6e3
dsv41 bench_decode: --rows for verify-shaped stack steps, 'all' flag …
jjang-ai Oct 26, 2026
78495c3
dsv41 docs: suffix pruning, fused decode kernels (M5), serving 845/13…
jjang-ai Oct 26, 2026
cd274fb
dsv41: remove dead paths; document why each hot path is fast
jjang-ai Oct 26, 2026
d1b4d15
dsv41 tests: parity_vision usage example uses a home-relative path
jjang-ai Oct 26, 2026
75f45bb
dsv41: narrow exception handling, close JSON files; fused hc only on …
jjang-ai Oct 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions jang-tools/jang_tools/dsv41/DECODE_DSPARK_METHODS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# DeepSeek-V4.1-Flash — decode & DSpark exact methods

Canonical, cross-machine blueprint for the validated V4.1 decode/speculative methods. Reference
implementation: this directory (`jang_tools/dsv41/`, jangq). Mirror these verbatim into (a) the vMLX
engine's V4.1 SingleBatchGenerator spec-decode path and (b) vmlx-swift
(`Libraries/MLXLMCommon/SpecDec`). All numbers measured on an M5 Ultra (256 GB) against the
`DeepSeek-V4.1-Flash-1017-JANG-Q2Q3-IMATRIX` bundle.

## M1 — DSpark speculative decode loop (`dspark.py::DSparkRunner.generate`)

Output is **greedy by construction**: `emit` is composed only of backbone verify-forward argmaxes,
so the draft changes the *acceptance rate* (the speedup), not the decision rule. It is identical to
single-token AR **except at near-ties**: a W+1-row verify forward (and a chunked prefill) computes
bf16 hidden states that differ in the last bits from a 1-row decode, which can flip a top-2 whose
margin is below ~0.05. Measured (256 tokens, fp32 logits): structured identical; code / code2 /
prose first diverge at AR margins 0.0056 / 0.0045 / 0.040. With bf16 logits the top-2 tied exactly
every ~50-100 tokens, so the head now produces fp32 logits as the reference does.

State: `c` = frontier (last position whose hidden is committed to the draft windows); `pending` =
backbone logits predicting position `c+1`. Per step:

1. `p0 = argmax(pending)` — backbone truth for `c+1` (free).
2. `draft_ids, conf = draft(p0, c)` → `[p0@c+1, d1@c+2, …, dW@c+1+W]`.
**CRITICAL off-by-one:** seed the draft with the backbone's already-predicted `p0` (position
`c+1`) and draft `c+2` onward, with `main_hidden` taken at position `c`. Seeding the committed
token at `c` (drafting `c+1`) gives ~35 % accept + divergence.
3. `feed = [p0, d1..dW]` (W+1 tokens at `c+1..c+1+W`); `ck = checkpoint()` (O(1) ref snapshot).
4. `vlog, vmh = forward(feed, all_logits=True, return_hidden=True)` — **one** backbone forward.
`vlog` has W+1 rows; `vlog[j]` predicts position `c+2+j`, so `truth[j] = argmax(vlog[j])`, and the
bonus `truth[W]` exists.
5. Accept: `k` = longest prefix where `draft_ids[1+j] == truth[j]` (`j = 0..W-1`).
6. **NO-REFEED FAST PATH — `k == W` (~2× on high-accept content):** the verify forward already wrote
exactly-correct *causal* KV for every accepted position (no rejected tail to undo), so **do not
restore+refeed**. Keep the verify cache: `seed_windows(vmh, c+1..c+1+W)`; `c += W+1`;
`pending = vlog[W]`; `emit = [p0,d1..dW]`. `truth[W]` becomes the next step's `p0`. → **1 forward/step.**
7. **PARTIAL ACCEPT — `0 < k < W` (in-place commit, 1 forward/step):** the verify forward ran with
`capture_verify=True`, so every layer holds references to its per-token cache inputs (post-RoPE
window KV; the compressor's `(kv, score)` projections, or the normed latent at ratio 1).
`emit = [p0, d1..dk]`; `DSV41.commit_prefix(sess, ck, k+1)` restores the checkpoint and replays only
those k+1 tokens' cache updates (window append; compressor pooling → pending tail + completed
groups → compressed / index pool rows with the same RoPE positions; history + position);
`seed_windows(vmh[:k+1], …)`; `c += k+1`; `pending = vlog[k]`, so `truth[k]` is the next p0.
**`k == 0`** keeps the old path: `emit = [p0, truth[0]]`, `restore(ck)`, `forward(emit)` (2 forwards,
but cheaper per token than a 1-token step). The refeed path for partial accepts (and its A/B switch) is
removed: it ran a second forward over the kept tokens every step. Measured (256 tokens, chat prompts): code 44.9 → 57.5 tok/s, code2
41.3 → 48.7, Rust 50.9 → 59.1, prose unchanged. `tests/test_commit_prefix.py` proves the replay exact
(`commit_prefix(W+1)` == the capture forward's own state, bit for bit).

Why it works: a 6-row verify forward ≈ 62 ms ≈ 2× a 1-row decode (32 ms) — the backbone forward
scales with rows — so eliminating the second (commit) forward ≈ 2× per step, on full and partial accepts alike.

**Measured (n=80, adaptive, WITH fast path):** code **1.88× / 55.7 t/s**, structured **2.00× / 57.1**,
low_accept **1.93× / 50.1**, prose 1.04× / 31.5. MIN 1.04× (never-below-AR PASS). Output
identical to greedy on code (59/59) and structured (29/29) over those short runs (see the near-tie note in M1). = parity with antirez `ds4.c`
56.8 t/s serial.

## M2 — Adaptive never-below-AR (`DSparkRunner(adaptive=True)`)

- `accept_ema = 0.7*ema + 0.3*(k/W)` each step; draft width `W = clamp(round(self.width * ema), 1,
self.width)` — depth is **acceptance-governed**, shrinking as acceptance falls AND growing back as
it recovers, always within the draft head's physical size `bs` (a capacity bound, not a policy depth).
- **Wall-clock governor (replaces the zero-accept streak trigger, 2026-10-25 audit).** Acceptance
alone cannot keep speculation at or above AR speed: a step that accepts 1 of 5 drafts resets any
zero-accept streak yet still pays draft + verify + commit forwards. `_Governor` keeps an EMA of
seconds per emitted token for speculative steps and for AR steps (step start to next step start,
every sync included) and speculates only while that is cheaper than AR. AR mode issues a
speculative probe every `probe_every = 16` AR tokens (a probe replaces the stale estimate, so one
good probe switches back); spec mode re-measures AR every `ar_probe_every = 64` steps (AR cost
grows with context). Neither mode is terminal. Synthetic-timing test:
`jang-tools/tests/dsv41_dspark_governor_test.py` (low acceptance stays within a few % of AR,
high acceptance beats it, acceptance returning mid-stream recovers within one probe period).
- **Verified (`tests/verify_dspark_adaptive.py`):** output matches plain greedy (up to near-ties, M1)
AR, and on a low-accept→easy prompt drafting re-engages (accepted > 0), proving recovery.
- Swift parity: the vmlx-swift port should mirror this recoverable mode (no permanent latch).

## M3 — Where single-stream AR decode time goes (it was not at the floor)

- 10.6 GB read/token; stock decode 29–31 t/s = **~330 GB/s of ~800 peak**. The earlier reading
("MLX qmv is ~50 % bandwidth-efficient, so AR is at the floor and MTP is the only lever") was wrong:
the gap was dispatch count and host/GPU serialization, not the GEMVs. M5 below moves AR decode
29.0 → 39.2 tok/s (2k context) and 26.0 → 34.3 (100k), token-identical.
- Still true: `mx.compile` does not merge independent GEMVs; `gather_qmm` is slower than qmv at
M=1; `lane_qmm` (TensorFold) is 11 % slower at M=1; the MLA decode-attention kernel alone (M4) is a
wash. Each is one dispatch out of ~150 per layer; only removing most of them pays.
- MTP (M1) still multiplies whatever AR is: a wide verify costs about one forward.
- Prefill: the 865 pp/s figure was measured on repetitive text, where the Engram rows stay
page-cache warm. On unique text cold prefill is bound by Engram row reads; see
`RUNTIME_SERVING.md`.

## M4 — Removed: standalone decode attention kernel, MoE expert dedup

Both were measured and deleted so nothing dead stays in the runtime:
- `metal_decode_attn.py` (port of the engine's `glm5_mla_decode_attn`: 64 heads x rank-512 latent, rows
read in place by index, fp32 accumulation, sink in the combine pass). Equivalent (cos 0.999999) but a
wall-clock wash (31.08 vs 31.42 tok/s): attention is one of ~150 dispatches per layer, and replacing
one dispatch with another does not move a dispatch-bound step. M5 fused the rest instead.
- MoE expert dedup across verify rows (ds4 `moe_dedup_plan`): bit-identical, but slower than M5's fused
MoE at 2/4/8 rows (0.351/0.509/0.794 vs 0.330/0.433/0.668 ms per layer). The fused MoE is already bound
by the distinct experts' bytes (repeated tiles hit the GPU caches); the plan's pair loop only costs
parallelism.

## M5 — Fused decode / verify kernels (`metal_decode.py`, default ON)

Four bit-exact changes for forwards of at most 8 rows (decode, DSpark verify); prefill is untouched.
Each kernel copies MLX's accumulation order (quantized GEMV walk, f32 GEMV tiling, row reduction,
RMSNorm), so greedy decode is bit-equal with each flag off or on.

| change | flag (`=0` disables) | per layer (synthetic, real dims) |
|---|---|---|
| per-layer `mx.async_eval` (<= 16 rows): the GPU runs early layers while later ones are encoded | `VMLX_DSV41_LAYER_ASYNC` | ~-0.14 ms |
| router logits from the bf16 gate weight (MLX f32 GEMV order, no per-call f32 copy); only where MLX uses the same tiling (K < 16 E) | `VMLX_DSV41_ROUTER_GEMV` | 1 row 86 → 68 µs |
| 6 routed + shared expert in 2 dispatches (mlx-serve `MOE_GU`/`MOE_DN`) instead of ~25 | `VMLX_DSV41_FUSED_MOE` | 1 row 0.279 → 0.226 ms |
| hyper-connection collapse + mixes + Sinkhorn split + expand in 3 dispatches per sublayer instead of ~14; self-checks once against the stock path | `VMLX_DSV41_FUSED_HC` | 1 row 0.183 → 0.137 ms |

Real model (M5 Ultra, AR greedy, all four on vs off): 2k context 29.0–29.3 → 39.1–39.2 tok/s, 256 greedy
tokens identical; 100k context 26.0–26.3 → 34.3 tok/s, 64 tokens identical. Verify rows (2–8) now each
compute what a 1-row decode of that token computes, so verify is closer to sequential decode than the
stock batched path (tiny model: max logit gap 1.61 → 0.35); it is still not bit-identical to it.

Note: MLX runs f32 matmuls as TF32 on M5 by default (`MLX_ENABLE_TF32=1`); the hyper-connection einsum
carries ~4e-4 relative error from it. The fused HC kernel reproduces that rounding to stay bit-equal.

Tests: `tests/dsv41_decode_fusion_test.py` (op-level bit-equality, greedy identity on random-weight
models from `dsv41/tests/synth.py`); benchmark harness `dsv41/tests/bench_decode.py`.

## Engine (vmlx-py) wiring status — DONE (vmlx `bf1ce697`)

V4.1 DSpark speculative decode is wired into the engine serving path and verified live:
- **Draft load** (`loaders/load_jangtq_dsv41.py`): `_maybe_load_dsv41_dspark` calls
`jang_tools.dsv41.dspark.load_dspark(runtime.args, runtime.model.embed, runtime.model.head)` and
attaches `model._dspark`. Default ON for bundles that ship `dspark/`; `VMLX_DSV41_DSPARK=0` disables.
- **Generator** (`utils/dsv41_dspark_generator.py::DSV41DSparkGenerator`): subclasses
`SingleBatchGenerator`; overrides `_start_request`/`_yield_current_and_schedule_next` to drive
`DSparkRunner.stream()` on `model.runtime` (its own runtime `Session` + checkpoint/restore + the
no-refeed fast path), yielding one committed token per scheduler step and reusing the inherited
finish-reason/Response/stop machinery. Greedy text only: requests with images still to prefill, a
non-greedy sampler, logits processors or logprobs take the inherited AR path. A VL prefix-cache hit
that covers every image leaves a text-only tail, which DSpark serves.
- **Selection** (`scheduler.py::_create_batch_generator`): a branch before the SBG fallback returns
`DSV41DSparkGenerator` iff `model._dspark` is attached — so the default AR path is never affected.
- **Verified live** (`vmlx serve`, warmed, thinking-off code request): coherent output, `finish=stop`,
**decode-only ~65.9 tok/s vs AR ~31** (2x+); generator selection confirmed in logs; output
greedy by construction (identical except at near-ties, M1).
- Note: the engine's older `vmlx_engine/dspark/` (drafter/generate/session) is Qwen3/MiniCPM DSpark,
unrelated to V4.1. Future: the engine's `DeepseekV41Cache` exposes `trim`, so a later version can do
M1-step-7 no-refeed for *partial* accept too (the standalone runtime skips it).

### vmlx-swift mirror (Libraries/MLXLMCommon/SpecDec)
Same shape: load the bundle `dspark/` draft, keep a draft-windows + backbone `Session` per sequence,
and in the decode step run M1 (draft → verify forward → accept → fast-path|commit) + M2 (adaptive
width + AR latch, **plus** the re-entry hysteresis the Python reference lacks).
Loading
Loading