Repository navigation
perf(kv-int8): dense GDN verify folds only the accepted steps - #370
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
c0ce73b to
f37b08a
Compare
0982cff to
c130078
Compare
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]>
f37b08a to
c2b7a02
Compare
) 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]>
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.Kernel (
gdn_fused_step.metal.inc,mlx_gdn_fused.cpp)tiled_headsparam. Tiled maps value headhvto key headhv % Hk(llama.cpp GGUF rows). Grouped maps it tohv / (Hv / Hk)(Splashkey_head). The q/k writer is one of the sharers per key head. With Hk = Hv, both maps are the identity.[1, T, W]as one more output (Splashstep_tape.inputs). The next verify reads that output as its pending tape, so no projection view and no copy at bind.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)andsettle(caches).retainswaps parity and refuses keep 0, keep > 8, or keep above any layer tape's rows (SplashGDN::addDecodechecks).settleexpands grouped keys forgated_delta_replay.qwen3_5/qwen3_5_moepaged_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_completelets grouped heads through, but only for a deferred cache. A decline under slot 4 errors:"deferred GDN complete kernel declined".retainon every commit,settleinfinish(before the draft-window stash). A GDN state that cannot be packed is an error.require_dflash2_poolrefuse a draft whose GDN layers failGatedDeltaNet::deferred_verify_refusal: 4 taps, 128-wide heads, Hv a multiple of Hk, f32 sidecars, bf16, Metal (SplashcompiledGdnfails 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).lane(512)(transient_charges_the_decode_free_pool)Deleted
mlx_gdn_commit.cpp,gdn_commit.metal.incand themlx_gdn_commit_allexternGdnStateBlobs::adopt/commit,GdnLayerTape::final_state/final_convsnapshot_all_mtp+replay_mtp_snapshot_tofallback in both steppersMLX_DFLASH2_GDN_BLOB,PAGED_ADOPTSTHIRD_PARTY_NOTICESanddocs/models.mdupdatedMTP keeps
gated_delta_replayand its snapshot (Splash has no MTP).Tests
Named mutations, each red when on and green when off (
MUTATIONS.md, Apple M5 Max, gen 17):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 andreplay_intobit for bitgrouped_deferred_matches_the_prepare_chain: grouped 27B matchesqwen4_gdn_prepare-> fused tail bit for bit, and the keep-T fold matches the window-final statedeferred_verify_takes_the_complete_kernel_for_both_orders: the layer under a deferred cacheretain_swaps_parity_and_settle_matches_replaypaged_dflash2_matches_paged_ar_for_every_keep: three head orders, every keep, one deferred launch per linear layer per cycle; the cells afterfinishmatch every cycle's kept rows replayed from the startfinish_settles_the_pending_rows: the cells afterfinishmatch the deferred kernel's own foldfinishskips settlepaged_moe_dflash2_lands_on_the_ar_cursor_for_every_keeppool_lane_charges_the_pending_gdn_tapedflash2_companion_needs_a_fused_gdn_targetFinal gates:
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warningscargo test -p mlx-paged-attn(17 binaries)--lib(RUST_TEST_THREADS=1)yarn build:nativeindex.d.ctsunchanged (no napi file touched)yarn typecheckGaps
tiled_heads.finishsettles 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.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:🤖 Generated with Claude Code