Skip to content

perf(kv-int8): dense GDN verify folds only the accepted steps - #370

Merged
Brooooooklyn merged 1 commit into
mainfrom
feat/kv-int8-s14-gdn-deferred-fold
Nov 12, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
feat/kv-int8-s14-gdn-deferred-fold

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Stage S14 of the Splash int8 KV alignment (stack #344). Base: S10f (#369).

S14 needs only S8, so it sits right after S10f in the stack (the plan lists it after S13). S11 is rebased onto it.

The Qwen3.5 dense and MoE DFlash2 verify now folds the last cycle's kept GDN rows into the lane's other cell before its own 8 rows, and the commit only swaps the two cells. No GDN commit kernel and no replay run per cycle. Splash: gdn_decode_batch_phase, QwenStateStorage::swapDecodeParity, GdnTapeLane.

before:  verify n: kernel writes the window-final state into the spare cell
         commit:   keep == 8 -> adopt the spare cell
                   else      -> mlx_gdn_commit_all replays the kept rows (every cycle on grouped 27B)
                   declined  -> per-layer replay from a per-cycle snapshot
after:   verify n: one deferred kernel per GDN layer
                   fold tape(n-1)[0..keep(n-1)] into the other cell -> run 8 rows -> write tape(n) + raw inputs
         commit:   swap parity, pending := (tape(n), keep(n))          (no kernel)
         finish:   fold the last pending rows once (replay_into)
         kernel declines -> the turn errors; a load it cannot serve refuses the draft

Kernel (gdn_fused_step.metal.inc, mlx_gdn_fused.cpp)

  • New tiled_heads param. Tiled maps value head hv to key head hv % Hk (llama.cpp GGUF rows). Grouped maps it to hv / (Hv / Hk) (Splash key_head). The q/k writer is one of the sharers per key head. With Hk = Hv, both maps are the identity.
  • The deferred entry writes the window's raw conv inputs [1, T, W] as one more output (Splash step_tape.inputs). The next verify reads that output as its pending tape, so no projection view and no copy at bind.
  • Only the deferred entry carries the flag. The step kernel and the non-deferred complete entries pass tiled_heads = true, so their routes do not change.

Changes in the model

  • GdnStateBlobs (gdn_blob.rs): pack(caches, tiled), pending(row) (the tape and keep, or a zero 1-row tape with keep 0 after a prefill), retain(tape, keep) and settle(caches). retain swaps parity and refuses keep 0, keep > 8, or keep above any layer tape's rows (Splash GDN::addDecode checks). settle expands grouped keys for gated_delta_replay.
  • Both verify cores (qwen3_5 / qwen3_5_moe paged_forward.rs) use 10 cache slots: 2/3 are the other cell, 4..9 hold the pending tape and keep. A wrong cell count is now an error, not a silent filter.
  • GatedDeltaNet::forward_complete lets grouped heads through, but only for a deferred cache. A decline under slot 4 errors: "deferred GDN complete kernel declined".
  • Both steppers: no per-cycle snapshot, retain on every commit, settle in finish (before the draft-window stash). A GDN state that cannot be packed is an error.
  • Load: both require_dflash2_pool refuse a draft whose GDN layers fail GatedDeltaNet::deferred_verify_refusal: 4 taps, 128-wide heads, Hv a multiple of Hk, f32 sidecars, bf16, Metal (Splash compiledGdn fails closed).

Memory plan

The lane now charges the pending tape between cycles (Splash DecodeTensor::GdnTape, gdn_tape_layer_bytes): per linear layer, 8 rows × ((W + Hk·Dk + Hv·Dv) × 2 + Hv × 6).

plan before after
pending tape, 27B (48 layers × 297,216) – 14,266,368 B
27B lane(512) (transient_charges_the_decode_free_pool) 232,587,264 246,853,632
35B-A3B + DFlash2 lane, every window (30 layers × 230,912) 196,165,632 203,092,992

Deleted

  • mlx_gdn_commit.cpp, gdn_commit.metal.inc and the mlx_gdn_commit_all extern
  • GdnStateBlobs::adopt / commit, GdnLayerTape::final_state / final_conv
  • the per-cycle snapshot_all_mtp + replay_mtp_snapshot_to fallback in both steppers
  • MLX_DFLASH2_GDN_BLOB, PAGED_ADOPTS
  • THIRD_PARTY_NOTICES and docs/models.md updated

MTP keeps gated_delta_replay and its snapshot (Splash has no MTP).

Tests

Named mutations, each red when on and green when off (MUTATIONS.md, Apple M5 Max, gen 17):

test mutation
deferred_fold_matches_t1_settle_on_model_shapes: 27B and 35B shapes, both head orders, both storage schedules, keep 0..=8, tape rows past keep poisoned with NaN; the fold matches the T=1 chain and replay_into bit for bit F1: fold all 8 rows
grouped_deferred_matches_the_prepare_chain: grouped 27B matches qwen4_gdn_prepare -> fused tail bit for bit, and the keep-T fold matches the window-final state G1: deferred maps tiled heads
deferred_verify_takes_the_complete_kernel_for_both_orders: the layer under a deferred cache G2: gate refuses grouped
retain_swaps_parity_and_settle_matches_replay R1: keep 0 accepted; E1: no grouped key expansion
paged_dflash2_matches_paged_ar_for_every_keep: three head orders, every keep, one deferred launch per linear layer per cycle; the cells after finish match every cycle's kept rows replayed from the start K1: retain 8 whatever the keep
finish_settles_the_pending_rows: the cells after finish match the deferred kernel's own fold U1: finish skips settle
paged_moe_dflash2_lands_on_the_ar_cursor_for_every_keep MV1: no pending tape in slots 4..9
pool_lane_charges_the_pending_gdn_tape X1: term left out
dflash2_companion_needs_a_fused_gdn_target L2: no GDN check at load

Final gates:

gate result
cargo fmt --all -- --check clean
cargo clippy --workspace --all-targets -- -D warnings clean
cargo test -p mlx-paged-attn (17 binaries) 332 passed, 0 failed, 13 ignored
mlx-core --lib (RUST_TEST_THREADS=1) 4,735 passed, 0 failed, 220 ignored
yarn build:native ok; index.d.cts unchanged (no napi file touched)
yarn typecheck ok

Gaps

  • 35B MoE safetensors rounding (grouped, Hk16 Hv32 W8192). AR still decodes through the MLX conv chain there, while the verify now uses the complete kernel. Their q/k norm and decay differ by up to one bf16 / f32 step. Measured in the unit fixture: q/k max diff 2e-3, decay 1 ULP on half the heads, v and raw inputs equal, output max diff 2.7e-4. On that model, DFlash2 now matches AR only up to bf16 ties. It was already no bit reference for AR there (verify attention vs the decode kernel). The 27B (both head orders) stays bit-identical. Fix: run grouped AR/MTP on the same kernel; the MTP replay then also needs expanded keys. This is a later stage.
  • Grouped heads reach the complete kernel only through the deferred entry. AR, MTP and prefill routes are unchanged.
  • Head order: Splash re-orders GGUF rows to grouped at load and keeps one key map. mlx-node keeps the tiled rows and picks the map per call with tiled_heads.
  • finish settles the pending rows once per turn. Splash never settles (requireCommitted), because mlx-node resumes the live cells on the next turn and runs the turn tail on them.
  • Tiny-fixture token checks: tokens are compared with AR only for Hk = Hv. The Hv = 4 fixtures leave the AR tokens on rounding (tiled at token 62, grouped at 52), so they check the cursor, the launches and the replay-chain cells.
  • Bit-exact gates ran on one GPU family (M5 Max). T1 needs no model and can re-run on any machine.
  • The load gate (deferred_verify_refusal) checks the norm dtype, not each projection. A hand-made checkpoint with bf16 norms and f32 GDN projections would load and then fail its first verify. No supported input has this mix: GGUF imports cast every dense tensor to bf16, and every local safetensors checkpoint has bf16 projections (local Codex finding, checked by three verifiers).

Not in this PR (live, not run)

LIVE.md:

  • L0: builds and sanity on the GGUF 27B (tiled) and the safetensors 27B (grouped)
  • L1: DFlash2 vs AR output hashes, both head orders
  • L2: fold vs commit, S14 vs base: same tokens, decode speed ≥ 0.99× (GGUF) / ≥ 1.00× (safetensors)
  • L3: native MTP unchanged
  • L4: second turn resumes the live window after a partial accept
  • The 35B MoE is not live-gated: no such model is on the machine.

🤖 Generated with Claude Code

@Brooooooklyn
Brooooooklyn added this pull request to stack #344 November 12, 2026 01:13
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0e6ff9c2-1bb1-454d-8a9b-9ca022eff184

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Pre-merge checks: Passed 1 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Title check Pending This assessment has not completed. The check will be retried on the next pre-merge check run.
Passed Passed checks: 1 passed

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T15:57:45.301350Z c2b7a02 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s14-gdn-deferred-fold branch from c0ce73b to f37b08a Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn removed this pull request from stack #344 November 12, 2026 15:43
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s10f-drop-flat-path branch from 0982cff to c130078 Compare November 12, 2026 15:55
Base automatically changed from feat/kv-int8-s10f-drop-flat-path to main November 12, 2026 15:55
Like Splash gdn_decode_batch_phase, each DFlash2 verify folds the last
cycle's kept GDN rows from their tape into the lane's other cell before
its own 8 rows, and the commit only swaps parity (swapDecodeParity).
No commit kernel or replay runs per cycle; finish folds the last kept
rows once. The deferred kernel takes grouped heads and writes its raw
inputs as the next tape; the pending tape is charged in the lane
transient. A load whose GDN the kernel cannot run refuses the draft.
The GDN commit kernel, the adopt path and MLX_DFLASH2_GDN_BLOB are gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s14-gdn-deferred-fold branch from f37b08a to c2b7a02 Compare November 12, 2026 15:55
@Brooooooklyn
Brooooooklyn merged commit a3b38a7 into main Nov 12, 2026
0 of 6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s14-gdn-deferred-fold branch November 12, 2026 15:56
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
)

Stage S30 of the Splash int8 KV alignment (stack #344). Base: S14
(#370).

A `/v1/messages` `stop_sequences` match now ends decode at the step the
model is running, streaming or not, and the turn finishes as a
completion. Splash: `stop_matched` → `RuntimeCall.stop` → `Engine::stop`
→ `settle` → `finish(Stop)`; `release` → `vacateLane` keeps the
generated KV in the cache.

```
before:  delta ─► StopSequenceBuffer match ─► keep consuming
         native decodes on to max_tokens (32,000 from Claude Code) or EOS
         ChatSession commits the full native text; non-streaming rescans the final ChatResult
after:   delta ─► StopSequenceBuffer match ─► session.stop(cut) ─► ChatStreamHandle.stop()
         stop bit, then the cancel flag ─► the existing cancel break, within one step
         ─► finish_paged_turn (blocks registered, history saved)
         ─► sink: done "cancelled" + stop bit + tokens > 0 ─► "stop"
         ─► ChatSession commits the cut text, no tool calls, next send = full replay
         non-streaming with stops: the same stream path (one scan decides text and sequence)
```

## Changes
- **Native handle:** `ChatStreamHandle.stop()` stores a stop bit, then
the cancel flag (Release / Acquire). `StreamTx` watches both. Its sink
renames a done `"cancelled"` to `"stop"` when the stop bit is set and
the turn generated tokens. With 0 tokens the turn stays cancelled.
- **Turns that are not decoding:** a stop on a preempted turn
(`handle_preempted`), a waiting turn (`reap_cancelled_waiters`) or a
turn replaying its prefill (`HybridStepExecutor` and qwen3 ragged
`QwenStepExecutor` prefill rows) that holds tokens now ends as a
completion, not as the cancelled error. This includes a stop that lands
inside a replay slice the backend is running: the slice fails on the
live cancel flag ("prefill cancelled"), and `execute_prefill` ends the
turn through `stop_vacates`. The qwen3 ragged forward never reads the
cancel flag, so its replay slices cannot fail this way. Its leftover
pages are released by sequence id (its full blocks were registered at
preemption) and its owner state is dropped. It takes no recurrent slot
back and installs no owner state (Splash `vacateLane` → `finish(Stop)`),
so it completes even when peers hold both recurrent units. The done
chunk goes through `emit_paged_turn_result`, the result half of
`finish_paged_turn`, split out for this.
- **qwen4_exp (Flash Next):** a cancel no longer fails a decode pass
mid-forward. `Decoder::step`, `verify_chunk` and the scheduled decode /
propose / verify / commit entries finish their pass, and the
step-boundary snapshot ends the turn. A batched pass no longer fails its
peer rows on one row's stop. Prefill and media still stop on the flag.
- **`_runChatStream`:** one end latch for cancel and stop (Splash
`RuntimeCall._request_end`). A stop keeps reading to the done chunk.
`ChatStreamProgressRef` becomes `ChatStreamControl { read, stop }`.
- **`ChatSession.stop(committedText)`:** records the cut only when the
native stop is accepted (Splash `RuntimeCall._request_end`). Before the
native stream starts it returns `false` and changes nothing, so the
caller can retry. The done event carries the cut, `toolCalls: []` and
`finishReason: 'stop'`. History commits the cut, and `needsFullReplay`
is set. For a raw-replay family (LFM2 / lfm2_moe) the committed content
is the raw text before the visible stream (the reasoning block) followed
by the cut. If the raw text does not end with the visible stream, it
falls back to the structured message.
- **Server, streaming:** calls `stop` once, on the first match. The
committed text is the text the response holds.
- **Server, non-streaming:** a request with `stop_sequences` runs the
stream internally. The collector feeds visible deltas through the same
`ToolCallTagBuffer` → `StopSequenceBuffer` order, builds the text with
the `selectCommittedStreamText` rule (Gemma4 / Muse-Glimmer delta-only
text), and returns the match and cut that `handleNonStreaming` uses.
`selectCommittedStreamText` is exported from `@mlx-node/lm`.
- **Docs:** `docs/cli.md` (stop behaviour, `output_tokens` overshoot)
and `docs/models.md` (`ChatSession.stop`).

## Deleted
- `ChatStreamProgressRef` and `progressRef`. Replaced by
`ChatStreamControl` / `control`.
- `cancelRequested` and `cancelled` in `_runChatStream`. Replaced by the
one end latch.
- The "keep consuming after a match" behaviour in the streaming handler.

## Tests
Each named mutation was red with the mutation on and green with it off
(`MUTATIONS.md`):
- `engine::napi_glue::tests::a_stopped_stream_finishes_stop`. Mutation:
the sink skips the rename to "stop".
-
`engine::decode::run_decode_loop_tests::stop_at_token_20_ends_decode_within_one_step`.
Mutation: `stop()` sets only the stop bit, and the loop runs to the
32,000 cap.
-
`qwen3_5::model::dflash2_park_tests::a_stopped_turn_commits_through_the_match`.
Mutation: `finish_paged_turn` aborts the cancelled turn's pages, and the
prefix hit stops inside the prompt.
- `qwen4_exp::tests::a_stop_on_a_preempted_turn_finishes_stop`.
Mutation: `stop_vacates` returns false.
-
`qwen3::model::tests::a_stop_on_a_ragged_prefill_row_ends_as_a_completion`.
Mutation: the ragged prefill row ignores the stop.
- `qwen4_exp::tests::a_cancel_during_decode_ends_at_the_pass_boundary`.
Mutation: `check_cancelled` ignores `decode_pass`.
- `qwen35-stream.test.ts`, "stop shares the cancel latch…". Mutation: a
stop pushes the abort marker.
- `chat-session.test.ts`, "commits the text up to the match" and
"replays the full history". Mutations: commit the full text; skip the
full replay.
- `messages-handler.test.ts`, streaming and non-streaming "a stop match
ends decode within one step". Mutation: the handler or the collector
never calls stop.
- `messages-handler.test.ts`, "non-streaming with stops keeps delta-only
text". Mutation: the collector uses `done.text`.
- `messages-handler.test.ts`, "non-streaming takes the stop from the
decode deltas". Mutation: the response rescans the final text.
-
`qwen4_exp::tests::a_stop_inside_a_replay_prefill_slice_finishes_stop`.
Mutation: a failed replay slice skips `stop_vacates`; the turn fails
with "prefill cancelled".
- `chat-session.test.ts`, "a stop before the native stream starts
changes nothing". Mutation: the cut is latched before the stop is
accepted.
- `chat-session.test.ts`, "a stopped raw-replay turn keeps its reasoning
block in the content". Mutation: the cut commit drops the raw reasoning
block.
-
`engine::hybrid_scheduler::tests::a_vacated_stop_completes_beside_two_resident_qwen35_peers`
and `..._qwen35_moe_peers`. A preempted turn with 20+ generated tokens,
a parked peer and a second resident peer holding both recurrent units,
then a stop: done "stop" with the tokens it had, the full blocks through
the cut still hit, both peers keep their rows. Mutation:
`finish_completed` activates the turn before it reads `vacated_stop`;
the stop fails with the recurrent-unit cap error.

Changed test:
`interrupted_token_discards_partial_layer_state_and_can_restart`. Its
cancel half now interrupts a prefill, because a decode pass ends at its
boundary.

Gates, all at the final commit:

| gate | result |
|---|---|
| `cargo fmt --all -- --check` | clean |
| `cargo clippy --workspace --all-targets -- -D warnings` | clean |
| mlx-core `--lib`, `RUST_TEST_THREADS=1` | 4,741 passed, 0 failed, 220
ignored |
| `yarn build:native` | ok; `index.d.cts` matches the crate copy; no
codegen churn |
| `yarn typecheck`, `yarn tsc -b --force` | clean |
| `vp lint --type-aware --type-check`, `vp fmt --check` (9 touched TS
files) | clean |
| `vp test`, 4 touched test files | 310 passed |
| `vp test`, 3 related server test files | 313 passed |

Review round 1 (F1-F3), at the fix commit:

| gate | result |
|---|---|
| `cargo fmt --all -- --check` | clean |
| `cargo clippy --workspace --all-targets -- -D warnings` | clean |
| mlx-core `--lib` `engine::hybrid_scheduler` / `models::qwen4_exp`,
`RUST_TEST_THREADS=1` | 119 / 241 passed (7 ignored), 0 failed |
| `yarn typecheck`, `yarn tsc -b --force` | clean |
| `vp lint --type-aware --type-check`, `vp fmt --check` (touched TS
files) | clean |
| `vp test` chat-session, qwen35-stream, messages-handler | 303 passed |

Review round 2 (F4), at the fix commit:

| gate | result |
|---|---|
| `cargo fmt --all -- --check` | clean |
| `cargo clippy --workspace --all-targets -- -D warnings` | clean |
| mlx-core `--lib` `engine::hybrid_scheduler` / `models::qwen3_5::` /
`models::qwen3_5_moe` / `models::qwen4_exp`, `RUST_TEST_THREADS=1` | 121
/ 423 (37 ignored) / 133 (10 ignored) / 241 (7 ignored) passed, 0 failed
|
|
`models::qwen3::model::tests::a_stop_on_a_ragged_prefill_row_ends_as_a_completion`
| passed |

No model was loaded.

## Gaps
1. `usage.output_tokens` is the native `numTokens`, which includes the
overshoot. That is the step in flight plus the chunks already queued in
the native mailbox, the N-API callback queue and the JS queue (64 deep
each). Splash counts through the match token.
2. Native history and KV keep the overshoot, and only the JS history is
cut. Splash cuts nothing either (`vacateLane`).
3. Non-streaming requests without `stop_sequences` stay on the sync
path. Splash streams every request.
4. `sendStream`, `sendToolResultStream` and the restart stream take no
stop. No server caller uses them.
5. Flat-cache families on the warm slot miss the next prefix check,
because native history holds the overshoot. This was already true before
S30.
6. A client disconnect after a stop means `ChatSession` does not commit.
Native still registers the blocks.
7. A pump-side cancel (callback queue full or closed) racing a stop can
still produce a done named "stop".
8. There is no completed / cancelled counter for stopped turns.
9. `/v1/responses` has no stop field.
10. 00-DELTA gate 2's "commit the full text → miss" mutation does not
apply to the paged pool. Gate 2 is covered by the
commit-through-the-match test and LIVE L3.
11. Splash `StopSearch` also matches inside thinking and tool-call text.
mlx-node matches visible answer text only (S27's surface). Once this
closes, S31 and stops interact.
12. There is no DFlash2 / inline-MTP stop test. Their cancel break is
unchanged and already ends through their commit epilogues, and the sink
rename covers every path.
13. Stopped turns do not feed the MTP acceptance gate
(`record_turn_mtp_acceptance` skips "cancelled"). The gate gets fewer
samples, but no wrong sample.
14. The vacated-stop regression pins the second resident recurrent row
directly. With on-demand booking, `admit_prepared` holds new turns back
while a victim is preempted, so the fixture could not reach two resident
peers beside a preempted turn through admission alone. The path where a
stopped waiter is reaped (`reap_cancelled_waiters`) goes through the
same `finish_completed` arm.

## Not in this PR (live, not run)
- L1: streaming, a match near token 100 with `max_tokens` 32,000.
`output_tokens` ≤ 200, and wall time ≤ 1/5 of the base.
- L2: the same request, non-streaming.
- L3: the next request's prefix hit reaches into the stopped reply.

All three run against the base c0ce73b. The commands are in `LIVE.md`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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