Skip to content

perf: harden ragged B>1 MTP batching masks and verify tail - #202

Merged
inureyes merged 6 commits into
mainfrom
update/issue-163-harden-ragged-mtp-batching
Jun 10, 2026
Merged

inureyes merged 6 commits into
mainfrom
update/issue-163-harden-ragged-mtp-batching

Conversation

@inureyes

@inureyes inureyes commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Hardens the experimental variable-length ("ragged") B>1 batched MTP speculative path (PR #162, behind MLXCEL_ENABLE_MTP_BATCH_RAGGED) by removing its two latent correctness dependencies and resolving a low-severity drafter-mask off-by-one, plus adds the throughput-study plumbing. Greedy parity is preserved (the changes can only move batched logits onto the standalone B=1 semantics); no defaults or env-var semantics change.

Changes

Item 1 (NaN-safe fully-masked padding rows): both left-padding causal mask builders in mlxcel-core/src/utils.rs (create_causal_mask_with_left_padding, create_causal_mask_with_window_and_left_padding) now rescue the self/diagonal column (k == q + offset) for leading-padding query rows (q + offset < left_padding[r]), so every query row attends at least one key and softmax over any row is finite regardless of the fused-SDPA masked-column semantics; the rescue removes the NaN at the source (downstream layers' K/V at padding positions stay finite) instead of relying on the kernel's hard skip of masked columns. The self column is on the causal diagonal (distance 0) so it is always inside any sliding window, and real query rows are byte-identical to the pre-rescue construction.

Item 2 (per-row valid-length verify tail): adds mask_stale_key_gap(base, per_row_valid_end, gap_end) to utils.rs and threads a new trailing per_row_valid_end: Option<&[i32]> through Gemma4TextModel::forward_with_speculative_sinks, the Gemma4Wrapper seq-id and explicit-cache entrypoints, and the VL / Unified vision delegators. After divergent accepts a shorter row's logical valid end (left_padding[r] + positions[r]) lags the physical cache offset; the verify forward (the sole Some producer) now excludes that row's stale [ve[r], offset) rejected-draft K/V (full-attention Cache::Standard, never zeroed) and zeroed phantom tail (sliding Cache::Rotating) from the offset-derived masks. The sliding penalty is applied only when the key axis is the full uncompacted [0, sliding_offset + l) (has_padding branch or sliding_offset + l <= window); a possibly-capped axis is left to the rotating cache's zero_partial_accept_tail. A uniform round (every ve[r] == offset, always true for the first verify after prefill) and the None path are byte-identical no-ops. Applies to both ragged and equal-length batched bursts.

Item 3 (drafter wrapper off-by-one): make_drafter_masks in mlxcel-core/src/drafter/masks.rs now delegates with kv_valid_len = query_offset + 1 instead of None, restoring the documented invariant query_offset == kv_valid_len - 1 (the SWA query position becomes query_offset again). This is the full fix, not the documentation fallback: the +1 does not flip the fast-path None behavior (verified by the existing fast-path test plus a new byte-equality regression on a non-fast-path shape). The wrapper has no production callers.

Item 4 (throughput study, code only): adds the #[ignore]-gated mtp_gemma4_ragged_throughput_probe to tests/speculative_parity.rs (serial B=1 vs ragged B=4 over variable-length prompts plus a classic equal-length control, prints tok/s and ratios, asserts only run success) and a new greedy_parity_mtp_gemma4_batched_b4_ragged_matches_b1 real-model parity gate over four variable-length prompts (lengths 6/7/9/12) on REACHABLE_PAIRINGS[1]. The ragged gate asserts byte-equality over each row's hole-free lockstep prefix (the prefill bonus, which doubles as the NaN canary, plus every round before the row's first sub-round-max accept); full-stream equality after divergent accepts is blocked by the pre-existing per-row position holes tracked in #203 and the strict assertion is restored there.

Validation

Developer pass (narrow suites, warm, default features): mlxcel-core utils 25 passed (5 new: padding-row rescue trio + gap helper), ffi_tests 73, cache::batch_quant 44, drafter::masks 19 (incl. the new wrapper byte-equality regression), root-crate gemma4_mtp_target 26 (incl. synthetic ragged end-to-end greedy parity), models::gemma4_tests 7 passed 5 ignored.

Orchestrator pass (M1 Ultra): cold clippy --all-targets clean on both CI feature sets (metal,accelerate and metal,accelerate,test-utils, after cargo clean -p mlxcel -p mlxcel-core); root lib 3086 passed 0 failed; mlxcel-core lib 859 passed 0 failed (serial, --test-threads=1); cargo fmt --check clean.

Real-model 31B verification (M1 Ultra, gemma-4-31b-it-4bit target + gemma-4-31B-it-assistant-bf16 drafter, block 4): the new ragged gate passes (every row byte-identical to its isolated B=1 run over the hole-free lockstep prefix, prefill-bonus NaN canary green on all rows; row 3 held 9/24 guaranteed tokens and tracked B=1 for 17). Item 1 is validated end to end: on current main this machine's SDPA kernel does NOT confine the fully-masked-row NaNs and the ragged path emits token id 0 garbage from the very first token; with this PR the ragged prefill bonus and lockstep prefix match B=1. Full-stream parity after divergent (mixed-accept) rounds is blocked by a pre-existing structural gap filed as #203 (per-row position holes: the batched verify writes and rotates every row's window at the shared physical offset, so a sub-max row keeps inflated relative RoPE distances that no mask can repair). An env-gated A/B with the stale-gap mask disabled reproduced main's failure signature bit-exactly on the equal-length case, proving this PR's only behavioral delta there is the mask itself; the pre-existing strict equal-length gate is red on current main on this hardware for the same #203 reason and is owned there, not here.

Throughput study (item 4, mtp_gemma4_ragged_throughput_probe, 192 tokens per leg): serial B=1 over variable-length prompts 2.5 tok/s; ragged B=4 over the same prompts 3.2 tok/s (1.25x, the #161 serialization penalty is fixed); classic equal-length B=4 9.9 tok/s vs classic serial B=1 13.3 tok/s (0.74x at high accept rates). Batched MTP is still not a consistent win over serial B=1, so default-on is not justified: MLXCEL_ENABLE_MTP_BATCH / MLXCEL_ENABLE_MTP_BATCH_RAGGED stay opt-in (full table and caveats in the issue #163 comment).

Closes #163

inureyes added 4 commits June 10, 2026 09:02
Issue #163 items 1 and 2 (core). Both left-padding causal mask builders (create_causal_mask_with_left_padding and create_causal_mask_with_window_and_left_padding) now rescue the self/diagonal column for leading-padding query rows (q + offset < left_padding[r]), so every query row attends at least one key and softmax over any row is finite regardless of the fused-SDPA masked-column semantics. Previously an all-minus-inf padding row produced NaN that only the kernel's hard skip of masked columns kept confined; the rescue removes the NaN at the source so downstream layers' K/V at padding positions stay finite. The self column lies on the causal diagonal (distance 0) so it is always inside any sliding window; real query rows are byte-identical to the pre-rescue construction.

Adds mask_stale_key_gap(base, per_row_valid_end, gap_end): adds minus-inf to each row's stale [valid_end, gap_end) key columns in a batched additive mask (2-D or 4-D base, returns [B,1,n,K]). This is the per-row valid-length tail exclusion primitive for the batched MTP verify forward. Adding 0/minus-inf to 0/minus-inf cannot produce a NaN (no plus-inf operands).

Tests: padding query rows attend exactly their self column, every query row has an attended cell, real query rows match causal-AND-padding(-AND-window), and the gap helper excludes only the per-row gap (2-D broadcast + 4-D preserve). Existing left-padding tests (offset > 0, no padding query rows) stay byte-identical.
Issue #163 item 2 (wiring). Threads per_row_valid_end: Option<&[i32]> through Gemma4TextModel::forward_with_speculative_sinks, the Gemma4Wrapper seq-id and explicit-cache entrypoints, and the VL / Unified vision delegators. The batched MTP verify forward (verify_forward_batched) is the sole producer of Some: it computes each row's logical valid key end (left_padding[r] + positions[r]) from the post-finalize state before the forward; every other call site passes None.

In the forward mask derivation, after the existing (global_mask, sliding_mask) selection and before the bidirectional overlay, when per_row_valid_end is Some the full-attention mask excludes each row's stale [ve[r], global_offset) rejected-draft K/V (the unbounded Cache::Standard is never zeroed) via mask_stale_key_gap, materializing the base when the fast branch left it None. The sliding mask gets the same treatment only when its key axis is the full uncompacted [0, sliding_offset + l) (the has_padding branch or sliding_offset + l <= window); a possibly-capped axis is skipped and left to the rotating cache's zero_partial_accept_tail. A uniform round (every ve[r] == offset, always true for the first verify after prefill) and the None path are byte-identical no-ops.

This moves a shorter row's batched logits onto its standalone B=1 semantics (whose exact cache trim has no gap), so it can only improve greedy parity. Applies to both ragged and equal-length batched bursts. Single-row and explicit-mask-prefill paths are unchanged.
Issue #163 item 3. make_drafter_masks (the kv_valid_len-less wrapper) now delegates with kv_valid_len = query_offset + 1 instead of None. The _with_valid_len fallback set effective_valid = query_offset, which made make_swa_mask_with_local_offsets derive the SWA query position as effective_valid - 1 = query_offset - 1, one short of the documented invariant query_offset == kv_valid_len - 1. The +1 recovers the SWA query position query_offset. For BatchScalar::PerRow the owned (arr + 1) tensor is declared before the BatchScalar that borrows it so it outlives the borrow.

The +1 does not flip the fast-path None behavior: the SWA no-mask criterion is unchanged (the local query position is clamped into the K/V axis) and the full-attention key_offset compensates (ko + kv_len <= v still holds). Verified by the existing make_drafter_masks_returns_none_for_both_layer_types_in_fast_path test and a new make_drafter_masks_wrapper_matches_valid_len_query_offset_plus_one regression that pins byte-equality with the explicit Some(query_offset + 1) call on a non-fast-path (kv_len > sliding_window) shape. The wrapper has no production callers; all production paths already use _with_valid_len with an explicit kv_valid_len.
Adds greedy_parity_mtp_gemma4_batched_b4_ragged_matches_b1: four variable-length prompts (lengths 6/7/9/12) over REACHABLE_PAIRINGS[1] (Gemma 4 31B + MTP assistant, block_size 4), with per-row B=1 MtpGenerator references (unique SequenceIds) compared token-for-token against one MtpBatchedGenerator::run_batched. Different lengths auto-route the adapter to the ragged left-padding prefill, exercising the NaN-safe padding rows and per-row valid-length verify tail. Mirrors the existing equal-length B=4 test structure.

Adds mtp_gemma4_ragged_throughput_probe (code-only, no measurements, no default or env-var changes): times serial B=1 vs ragged B=4 over variable-length prompts plus a classic equal-length B=4-vs-serial control, prints tok/s per leg and the ragged/serial and classic/serial ratios, asserts only run success. Both tests are #[ignore]-gated real-model heavy; the orchestrator runs them on local 31B hardware and records the throughput study.
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:low Low priority area:models Model architectures, weights, loading, metadata labels Jun 10, 2026
Full-stream byte-parity after divergent accepts is blocked by the pre-existing per-row position holes now tracked in issue #203 (observed on M1 Ultra, where the strict equal-length gate is red on main as well). The ragged gate asserts byte-equality over the structurally guaranteed region instead: the prefill bonus (which doubles as the NaN canary for the issue #163 item 1 fix) plus every round before the row's first sub-round-max accept, derived from MtpBatchedRunOutput::accept_lens. When a run stays lockstep throughout, the gate degenerates to the original full strict assertion. Restore the full-stream assertion when #203 lands.
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

What was checked

Tests: Coverage is complete. The PR adds mask_stale_key_gap (6 unit tests covering gap-exclusion, 4D base preservation, nan-safe rescue), left_padding_mask_* (3 unit tests), make_drafter_masks_wrapper_matches_valid_len_query_offset_plus_one (wrapper regression), plus synthetic ragged end-to-end in gemma4_mtp_target and two #[ignore]-gated real-model gates in tests/speculative_parity.rs. No uncovered branches found in the new code.

Documentation: Grepped all docs for MTP_BATCH, ragged, speculative, MLXCEL_ENABLE_MTP. The PR changes no defaults and no env semantics; nothing in the existing docs is now factually wrong. The pre-existing gap of MLXCEL_ENABLE_MTP_BATCH_RAGGED not listed in docs/environment-variables.md predates this PR (#162) and is already covered in docs/benchmark_results/gemma4-mtp-speculative-decoding.md.

Lint/Format: cargo fmt --check clean. cargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings clean. cargo clippy -p mlxcel --lib --tests --features metal,accelerate -- -D warnings clean. cargo check -p mlxcel --lib --tests --features metal,accelerate clean.

Commits: Nothing required; working tree was already clean.

All checks passing. Ready for merge.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 10, 2026
@inureyes
inureyes merged commit 0356ed6 into main Jun 10, 2026
4 checks passed
@inureyes
inureyes deleted the update/issue-163-harden-ragged-mtp-batching branch June 10, 2026 12:45
@inureyes inureyes self-assigned this Jun 10, 2026
@inureyes inureyes added this to the 0.2 milestone Jun 21, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
* perf: NaN-safe MTP padding rows + stale-tail verify mask helper

Issue lablup#163 items 1 and 2 (core). Both left-padding causal mask builders (create_causal_mask_with_left_padding and create_causal_mask_with_window_and_left_padding) now rescue the self/diagonal column for leading-padding query rows (q + offset < left_padding[r]), so every query row attends at least one key and softmax over any row is finite regardless of the fused-SDPA masked-column semantics. Previously an all-minus-inf padding row produced NaN that only the kernel's hard skip of masked columns kept confined; the rescue removes the NaN at the source so downstream layers' K/V at padding positions stay finite. The self column lies on the causal diagonal (distance 0) so it is always inside any sliding window; real query rows are byte-identical to the pre-rescue construction.

Adds mask_stale_key_gap(base, per_row_valid_end, gap_end): adds minus-inf to each row's stale [valid_end, gap_end) key columns in a batched additive mask (2-D or 4-D base, returns [B,1,n,K]). This is the per-row valid-length tail exclusion primitive for the batched MTP verify forward. Adding 0/minus-inf to 0/minus-inf cannot produce a NaN (no plus-inf operands).

Tests: padding query rows attend exactly their self column, every query row has an attended cell, real query rows match causal-AND-padding(-AND-window), and the gap helper excludes only the per-row gap (2-D broadcast + 4-D preserve). Existing left-padding tests (offset > 0, no padding query rows) stay byte-identical.

* perf: thread per-row valid-length verify tail through Gemma 4

Issue lablup#163 item 2 (wiring). Threads per_row_valid_end: Option<&[i32]> through Gemma4TextModel::forward_with_speculative_sinks, the Gemma4Wrapper seq-id and explicit-cache entrypoints, and the VL / Unified vision delegators. The batched MTP verify forward (verify_forward_batched) is the sole producer of Some: it computes each row's logical valid key end (left_padding[r] + positions[r]) from the post-finalize state before the forward; every other call site passes None.

In the forward mask derivation, after the existing (global_mask, sliding_mask) selection and before the bidirectional overlay, when per_row_valid_end is Some the full-attention mask excludes each row's stale [ve[r], global_offset) rejected-draft K/V (the unbounded Cache::Standard is never zeroed) via mask_stale_key_gap, materializing the base when the fast branch left it None. The sliding mask gets the same treatment only when its key axis is the full uncompacted [0, sliding_offset + l) (the has_padding branch or sliding_offset + l <= window); a possibly-capped axis is skipped and left to the rotating cache's zero_partial_accept_tail. A uniform round (every ve[r] == offset, always true for the first verify after prefill) and the None path are byte-identical no-ops.

This moves a shorter row's batched logits onto its standalone B=1 semantics (whose exact cache trim has no gap), so it can only improve greedy parity. Applies to both ragged and equal-length batched bursts. Single-row and explicit-mask-prefill paths are unchanged.

* fix: restore drafter mask wrapper kv_valid_len invariant

Issue lablup#163 item 3. make_drafter_masks (the kv_valid_len-less wrapper) now delegates with kv_valid_len = query_offset + 1 instead of None. The _with_valid_len fallback set effective_valid = query_offset, which made make_swa_mask_with_local_offsets derive the SWA query position as effective_valid - 1 = query_offset - 1, one short of the documented invariant query_offset == kv_valid_len - 1. The +1 recovers the SWA query position query_offset. For BatchScalar::PerRow the owned (arr + 1) tensor is declared before the BatchScalar that borrows it so it outlives the borrow.

The +1 does not flip the fast-path None behavior: the SWA no-mask criterion is unchanged (the local query position is clamped into the K/V axis) and the full-attention key_offset compensates (ko + kv_len <= v still holds). Verified by the existing make_drafter_masks_returns_none_for_both_layer_types_in_fast_path test and a new make_drafter_masks_wrapper_matches_valid_len_query_offset_plus_one regression that pins byte-equality with the explicit Some(query_offset + 1) call on a non-fast-path (kv_len > sliding_window) shape. The wrapper has no production callers; all production paths already use _with_valid_len with an explicit kv_valid_len.

* test: ragged B>1 MTP parity + throughput probe (lablup#163 item 4)

Adds greedy_parity_mtp_gemma4_batched_b4_ragged_matches_b1: four variable-length prompts (lengths 6/7/9/12) over REACHABLE_PAIRINGS[1] (Gemma 4 31B + MTP assistant, block_size 4), with per-row B=1 MtpGenerator references (unique SequenceIds) compared token-for-token against one MtpBatchedGenerator::run_batched. Different lengths auto-route the adapter to the ragged left-padding prefill, exercising the NaN-safe padding rows and per-row valid-length verify tail. Mirrors the existing equal-length B=4 test structure.

Adds mtp_gemma4_ragged_throughput_probe (code-only, no measurements, no default or env-var changes): times serial B=1 vs ragged B=4 over variable-length prompts plus a classic equal-length B=4-vs-serial control, prints tok/s per leg and the ragged/serial and classic/serial ratios, asserts only run success. Both tests are #[ignore]-gated real-model heavy; the orchestrator runs them on local 31B hardware and records the throughput study.

* docs: drop em dashes from new comments per writing convention

* test: scope ragged MTP parity gate to the hole-free lockstep prefix

Full-stream byte-parity after divergent accepts is blocked by the pre-existing per-row position holes now tracked in issue lablup#203 (observed on M1 Ultra, where the strict equal-length gate is red on main as well). The ragged gate asserts byte-equality over the structurally guaranteed region instead: the prefill bonus (which doubles as the NaN canary for the issue lablup#163 item 1 fix) plus every round before the row's first sub-round-max accept, derived from MtpBatchedRunOutput::accept_lens. When a run stays lockstep throughout, the gate degenerates to the original full strict assertion. Restore the full-stream assertion when lablup#203 lands.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: harden ragged B>1 MTP batching (NaN-safe masked rows, per-row valid-length verify mask)

1 participant