Skip to content

perf: support variable-length prompts in B>1 batched MTP bursts - #162

Merged
inureyes merged 8 commits into
mainfrom
feature/issue-161-ragged-mtp-batch-window
Jun 5, 2026
Merged

inureyes merged 8 commits into
mainfrom
feature/issue-161-ragged-mtp-batch-window

Conversation

@inureyes

@inureyes inureyes commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements variable-length-prompt support for B>1 batched MTP speculative bursts (issue #161), behind a new MLXCEL_ENABLE_MTP_BATCH_RAGGED opt-in subordinate to MLXCEL_ENABLE_MTP_BATCH. Today the batched burst only groups concurrent requests whose prompt length is identical, so a variable-length mix serializes into head-of-line-blocking B=1 bursts (~0.78x). This lets burst-eligible rows of different prompt lengths form a single B>1 batched MTP burst, served via left-padding to max_prompt_len.

The production default path — including MLXCEL_ENABLE_MTP_BATCH=1 alone — is unchanged: the validated same-length batched burst stays the default behaviour until the operator also sets the new ragged opt-in. This keeps the work strictly out of the production default while the orchestrator's real-model greedy-parity gate validates the on-hardware behaviour.

Real-model validation (31B, M5 Max)

Greedy parity: PASSED. Four variable-length concurrent requests at temperature 0 form a single ragged B>1 burst and every row's output is byte-identical to classic decode. The previously-broken most-padded row (whose prompt padding was not masked on the single-token l==1 verify path) now produces the correct output and hits EOS at the right position. The root fix was ensuring the resident prompt-padding mask is applied consistently on the single-token verify forward, not only on the multi-token path.

Throughput: marginal and not a consistent win. Measured ~0.94–1.13x vs classic batched decode across runs (confounded by short-row early-EOS). This recovers the prior variable-length serialization penalty (~0.78x) but is not a clear speedup, so MLXCEL_ENABLE_MTP_BATCH_RAGGED stays off by default. The issue's conditional default-on flip remains deferred pending a more definitive throughput measurement.

Greedy-parity mechanism (the must-have)

Parity is preserved by construction via the left-padding uniform per-row position shift:

  • Row r (length L_r) is left-padded to max_len, so its real tokens occupy padded indices [lp_r, max_len) with lp_r = max_len - L_r. Proportional RoPE is applied with a single scalar offset (0 at prefill -> position == padded index), so every real token of row r is shifted right by the same constant lp_r versus a standalone B=1 run that would place it at [0, L_r). Because attention depends only on the relative RoPE phase q_pos - k_pos, and both query and key of any in-row pair carry the same +lp_r shift, every in-row relative phase — and thus every attention score and every argmax — is preserved. The left-padding mask blocks every real query from attending to the leading padding keys.
  • In subsequent verify rounds the shared physical cache offset is uniform for every row (unchanged from the same-length path), so each row's appended verify tokens carry the same +lp_r shift end-to-end.
  • Seed/finalize metadata is unified through seed_anchors_from_valid_len / build_seed_metadata with the shifted-frame formula kv_offset = left_padding + kv_valid_len, bonus_position = kv_offset - 1. The drafter's set_shared_kv_batched (already per-row aware) normalizes each row's K/V to the prefix-valid layout via kv_valid_len + left_padding, and rotates its query at position_per_row[r] = lp_r + kv_valid_len[r] - 1. The lp_r cancels in every query-key difference, so the drafter's cross-attention relative phases are byte-identical to the same-length path. For equal-length rows (left_padding == 0) the formula reduces to the legacy kv_offset == kv_valid_len metadata exactly, so the same-length burst is byte-for-byte unchanged.

Net: the ragged path is parity-correct iff the existing same-length batched path is, modulo the prefill left-padding (proven correct) and a metadata shift (shown to cancel). It rides entirely on the same-length foundation the orchestrator already validates.

CRITICAL fix: out-of-regime windows now fall back cleanly to classic

The capped-regime eligibility check (max_prompt_len > sliding_window) originally lived inside the committed batched burst, so when the burst was already in flight its Err surfaced as a client-facing GenerateEvent::Error to every row in the window rather than the documented per-row classic re-enqueue. Added ragged_target_sliding_window() and a pre-gate in try_run_burst_batched that returns Err(seqs) (clean re-enqueue) before committing the burst whenever a ragged-allowed window exceeds the target sliding window. Confirmed with a real 2576-token prompt (longer than the sliding window): HTTP 200, no error or crash. (Found by pr-reviewer; committed in fcba29f, unit-tested.)

What changed

  • src/lib/mlxcel-core/src/utils.rs — new create_causal_mask_with_window_and_left_padding helper (windowed counterpart of create_causal_mask_with_left_padding), restricted to the non-capped key-axis regime (size + offset <= window) via a debug assertion. Synthetic tests cover the no-padding fast path, per-row padding-column masking, the causal upper bound, and equivalence to the plain left-padding mask in the non-capped prefill regime.
  • src/server/batch/scheduler.rs — relax the burst-window predicate (drain_matching_window) to drop the prompt-length equality when the ragged flag is on; all other window checks (lane, max_tokens, sampling, can_join) are unchanged.
  • src/server/batch/speculative_burst.rs — new mtp_batched_ragged_window_enabled flag; try_run_burst_batched admits ragged windows only for the MTP dispatch under the flag (DFlash and the unflagged path keep strict equal-length and re-enqueue via Err); pre-gate for out-of-regime sliding-window fallback.
  • src/models/gemma4.rs — new sliding_window_value() accessor for the ragged eligibility gate.
  • src/models/gemma4_mtp_target.rs — left-padding prefill path: left_padded_input builder, prefill_and_seed_batched_ragged (routed automatically on length mismatch), batched_sink_forward_with_mask (passes the single left-padding mask, correct for both full-attention and sliding-window layers in the eligible regime), persisted per-row left_padding state threaded through verify_finalize_batched, and the unified build_seed_metadata / seed_anchors_from_valid_len formula. Eligibility is restricted to max_prompt_len <= sliding_window; outside it the adapter declines (Err) and the scheduler re-enqueues for per-row B=1 service.
  • src/server/model_worker.rs — server-startup notice updated to document the opt-in.
  • Synthetic tests in queue.rs (ragged window formation on/off), gemma4_mtp_target_tests.rs (padding builder, per-row position/anchor derivation), and speculative_burst.rs (flag default-off).

Implemented vs deferred

  • Implemented end-to-end behind MLXCEL_ENABLE_MTP_BATCH_RAGGED: ragged window formation, ragged left-padded prefill + per-row positions/mask, per-row accept/EOS/retire (the batched round loop and drafter were already per-row aware and are reused unchanged).
  • Deferred (clean fallback, not half-wired): the capped-RotatingKVCache regime (max_prompt_len > sliding_window) is declined per-row rather than served, because the windowed left-padding mask is only validated in the non-capped regime. The default-on flip of MLXCEL_ENABLE_MTP_BATCH is explicitly out of scope (the issue marks it conditional/future); this stays behind the existing flag.

Known follow-ups (not blocking)

MEDIUM — fully-masked padding query rows may produce NaN. When a row's prompt is the shortest in the window its first query positions are entirely padding (all keys masked). MLX SDPA currently returns finite values for fully-masked columns by convention, but this is not a guaranteed contract. The correct fix is to explicitly zero or skip those query rows rather than relying on the masked-column semantics. Not yet observed to cause incorrect output (the real-model parity gate passed), but is a latent correctness risk under future MLX updates.

MEDIUM — target verify forward does not mask each row's per-row valid-length tail after mixed accepts. After a round with mixed accept counts the rows have different numbers of newly accepted tokens appended. The verify forward does not yet mask the tail beyond each row's valid length. This is inherited from the validated same-length path (where all rows accept identically), but in the ragged case rows may diverge earlier. Not observed to affect output in the greedy parity runs, but is a correctness gap for future non-trivial mixed-accept sequences.

LOW — latent off-by-one in the test-only make_drafter_masks wrapper. The production drafter mask path is unaffected; this is isolated to the test helper. Tracked for a future test-cleanup pass.

Test plan

  • cargo check --lib --tests (clean)
  • cargo clippy --lib --tests -- -D warnings (clean)
  • cargo test -p mlxcel-core --lib utils::tests::windowed_left_padding (3 passed)
  • cargo test --lib gemma4_mtp_target (23 passed, incl. 6 new ragged)
  • cargo test --lib batch::queue (23 passed, incl. 3 new ragged-window)
  • cargo test --lib batch::speculative_burst (46 passed, incl. ragged flag)
  • cargo test -p mlxcel-core --lib round_loop_batched (21 passed — existing batched parity unchanged)
  • cargo test --lib scheduler (160 passed — no regression)
  • Real-model 31B greedy-parity gate PASSED: 4 variable-length requests, every row byte-identical to classic decode at temperature 0 (including the previously-broken most-padded row)
  • Real-model out-of-regime fallback confirmed: 2576-token prompt returns HTTP 200, no error or crash

Closes #161

inureyes added 3 commits June 5, 2026 01:34
Add create_causal_mask_with_window_and_left_padding, the sliding-window counterpart of create_causal_mask_with_left_padding. A B>1 batched MTP burst that mixes prompt lengths left-pads every row to max_prompt_len; the sliding-attention layers then need a mask that enforces both the windowed causal band and the per-row left-padding key exclusion.

The helper restricts itself to the non-capped key-axis regime (size + offset <= window) via a debug assertion, because under RotatingKVCache capping the column-to-position mapping is re-indexed and the left-padding filter would be wrong. The ragged batched MTP caller enforces this by only forming ragged windows when max_prompt_len <= sliding_window and declining otherwise.

Synthetic tests cover the no-padding fast path (byte-identical to the plain windowed mask), per-row padding-column masking, the causal upper bound, and equivalence to the plain left-padding mask in the non-capped prefill regime.
Allow a B>1 batched MTP speculative burst to span rows with different prompt lengths in a single burst, gated behind the new MLXCEL_ENABLE_MTP_BATCH_RAGGED opt-in (subordinate to MLXCEL_ENABLE_MTP_BATCH). The default path — including MLXCEL_ENABLE_MTP_BATCH=1 alone — keeps the validated same-length-only batched burst untouched.

Scheduler (scheduler.rs): drop the prompt-length equality in the burst-window predicate when the ragged flag is on, so burst-eligible rows of different lengths join one window; all other window checks (lane, max_tokens, sampling, can_join) are unchanged.

Burst driver (speculative_burst.rs): admit ragged windows only for the MTP dispatch under the flag; DFlash and the unflagged path keep the strict equal-length requirement and re-enqueue ragged windows via Err.

Gemma 4 batched adapter (gemma4_mtp_target.rs): add a left-padding prefill path. Variable-length rows are left-padded to max_prompt_len with a per-row left-padding causal mask; in the eligible non-capped regime (max_prompt_len <= sliding_window) that single mask is byte-identical to the windowed left-padding mask, so it is correct for both full-attention and sliding-window layers. Per-row seed/finalize metadata is unified through build_seed_metadata using the shifted-frame formula kv_offset = left_padding + kv_valid_len, bonus_position = kv_offset - 1; for equal-length rows (left_padding == 0) this reduces to the legacy metadata exactly. The constant per-row left_padding is stashed at prefill and threaded through every verify round so rounds stay parity-correct.

Greedy parity (temperature 0) is preserved by the left-padding uniform per-row position shift: every token in a row (prompt and every verify round) is shifted by the same constant left_padding[r], so all intra-row relative RoPE phases — and thus every argmax — match the row's standalone B=1 run. The drafter already honours per-row kv_valid_len / left_padding / position metadata, and the batched round loop already retires finished rows per-row, so neither needed changes.

Eligibility is restricted to max_prompt_len <= sliding_window; outside that the adapter declines (Err) and the scheduler re-enqueues the rows for per-row B=1 service. The on-hardware greedy-parity validation is left to the orchestrator's real-model gate; the flag keeps the path out of the production default until then.
Add synthetic coverage for the variable-length batched MTP path:

- queue.rs: variable-length window formation via drain_matching_window — ragged-off keeps the length-equality gate (stops at the first mismatch), ragged-on groups different-length burst-eligible candidates into one window while still honouring the other window checks (max_tokens).
- gemma4_mtp_target_tests.rs: left_padded_input right-aligns rows and reports per-row left_padding/valid_len; padded tensor places real tokens at the [lp, max_len) suffix with zeroed leading pad; empty rows rejected. seed_anchors_from_valid_len shifted-frame formula (kv_offset = left_padding + kv_valid_len, bonus = kv_offset - 1), its equal-length reduction to legacy metadata, and per-row round-advance divergence.
- speculative_burst.rs: MLXCEL_ENABLE_MTP_BATCH_RAGGED defaults off.

Also refresh the server-startup notice and the batched-adapter docstring to document the new opt-in and the left-padding parity mechanism.
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority area:models Model architectures, weights, loading, metadata labels Jun 4, 2026
inureyes added 4 commits June 5, 2026 02:15
The ragged (variable-length) B>1 batched MTP burst (issue #161, behind MLXCEL_ENABLE_MTP_BATCH_RAGGED) broke greedy parity for the most-left-padded (shortest) row: classic decode stopped at EOS but the ragged row emitted empty content and ran the full token budget. The divergence scaled with the row's left-padding `lp = max_len - L`, so the three less-padded rows stayed byte-identical while only the shortest broke.

Two independent frame-mismatch defects are fixed, both rooted in the same cause: a left-padded row's real keys live at padded indices `[lp, max_len)` (target/cache frame, carrying a uniform `+lp` RoPE shift), but two consumers compared against the unshifted prefix-valid frame.

1. Verify-round prompt-padding contamination (the active real-model defect at the production sliding_window). The ragged prefill masks each row's leading `[0, lp)` padding via an explicit left-padding mask, but every subsequent verify round took the `mask == None` forward path, which derived purely offset-based causal / windowed masks that do NOT exclude the padding columns. The padding K/V (token id 0) is never evicted from the unbounded full-attention cache, so the verify query attended `lp` spurious padding keys every round; the perturbation accumulates and flips the greedy argmax once `lp` is large enough. Fix: thread the per-row `left_padding` through `forward_with_speculative_sinks` into the `mask == None` branch and build per-attention-family left-padding-aware masks — `create_causal_mask_with_left_padding` for full attention (padding resident for the whole run) and `create_causal_mask_with_window_and_left_padding` for the sliding family while the rotating cache has not yet wrapped past the padding (once capped, the oldest padding keys are evicted and the plain windowed mask is already correct). When `left_padding` is absent or all-zero — every non-ragged path, including the equal-length batched burst and ordinary decode — the selection is byte-identical to the previous plain masks.

2. Drafter SWA window distance used the padded RoPE anchor (a latent defect that surfaces in the capped / small-window regime). After K/V normalization the drafter's shared keys are rolled to the prefix-valid frame `[0, kv_valid_len)`, yet `make_swa_mask_with_local_offsets` measured the bidirectional-window distance from `query_offset = bonus_position = lp + kv_valid_len - 1` (padded frame). That injects a spurious `+lp` into every query−key distance and over-masks the most-padded row's front keys by exactly `lp`. The RoPE anchor must stay padded (it cancels against the baked keys' `+lp` phase), but the mask distance must use the valid-frame position `kv_valid_len - 1`. Fix: derive the SWA query offset from `kv_valid_len`, not the padded anchor. For every non-padded path `bonus_position == kv_valid_len - 1`, so this is byte-identical there and only diverges (correctly) when `lp > 0`.

Regression tests (unit proxies for the real-model parity gate):

- `drafter::masks` — a 2-row ragged batch with a large length gap asserts the most-padded row's valid SWA keys are attended (pre-fix every valid key was -inf, i.e. the bonus query saw nothing).
- `utils` — a verify-round left-padding mask at a nonzero cache offset with a large per-row gap asserts the most-padded row's leading padding columns are masked while every real key the standalone B=1 run exposes attends, plus the causal upper bound on the appended query columns.

The same-length batched path and the production default remain byte-for-byte unchanged (all-zero left_padding takes the original mask branches). The orchestrator re-runs the real 31B greedy-parity + throughput gate.
The ragged (variable-length) B>1 batched MTP burst (issue #161, behind MLXCEL_ENABLE_MTP_BATCH_RAGGED) still broke greedy parity for the most-left-padded (shortest) row after the verify-contamination fix in 6f89aee: the row generated its full token budget of empty/pad output and never hit EOS while classic decode emitted a short answer then stopped. The prior fix's regression tests were mask/logit-level and passed, yet real generation still diverged — so this adds an end-to-end probe that actually generates through the real adapter and pins the defect.

Root cause: two regimes of the ragged verify forward attended the row's resident prompt padding (token id 0), perturbing the most-padded row's logits every round until the perturbation accumulated enough to flip the greedy argmax.

1. Single-token (`l == 1`) verify steps ignored left_padding entirely. The per-row left-padding mask construction in `Gemma4TextModel::forward_with_speculative_sinks` was gated on `l > 1`, so any width-1 step took the `mask == None` fast path and never masked the padding. This hit the unbounded full-attention cache (padding resident forever) hardest; the synthetic-model hidden-state probe shows the full-attention most-padded-row hidden diverging from the standalone B=1 run by ~3e-4 and growing with depth (vs the ~1.5e-5 RoPE-rounding floor).

2. The sliding-attention branch fell back to a padding-UNAWARE plain windowed mask as soon as `sliding_offset + l > sliding_window`. But the MTP rollback buffer (`RotatingKVCache::buffer_size`) keeps the sliding cache uncompacted up to a logical capacity of `sliding_window + buffer_size`, so the resident padding survives at columns `[0, lp)` long past `sliding_offset + l > window`. The gate therefore stopped masking the padding exactly while it was still resident, leaking `lp` padding keys into the most-padded row's window every verify step.

Fix: build per-row left-padding-aware masks whenever any row has left_padding, for ANY query width (including `l == 1`). Full attention uses `create_causal_mask_with_left_padding` over the full key axis. Sliding attention uses `create_causal_mask_with_window_and_left_padding` over the full key axis unconditionally — that mask already enforces both the sliding-window band (tril(offset) ∩ triu(offset - window + 1)) and the `[0, lp)` padding filter, so it is correct for `size + offset > window` too while the buffered cache is uncompacted (which the eligible regime, `max_prompt_len <= sliding_window` with realistic output lengths, never exceeds; a compacted axis has already evicted the oldest padding so `trim_mask_to_keys` crops to the padding-free suffix). The over-strict `size + offset <= window` debug-assert in `create_causal_mask_with_window_and_left_padding` is relaxed accordingly and its doc rewritten to state the real precondition (full key axis, not `size + offset <= window`).

Both the equal-length batched burst and ordinary decode have all-zero left_padding and take the unchanged plain-mask branches, so the production default (including B=1 MTP) is byte-for-byte unchanged; only the flagged ragged path changes.

End-to-end regression tests (the proxy the prior mask-level tests missed): drive the real Gemma4MtpBatchedTargetAdapter against a tiny synthetic 1-layer Gemma 4 wrapper (sliding and full-attention variants).

- `ragged_most_padded_row_verify_hidden_has_no_padding_contamination` runs the real prefill + multi-round verify/finalize loop and asserts the most-padded row's verify hidden state stays within the RoPE-rounding floor (8e-5) of the standalone B=1 run. This FAILS without the fix (~1.6e-4 sliding / ~2.8e-4 full, both above the ceiling) and PASSES with it (~1.5e-5). Bitwise parity is intentionally not asserted: left-padding shifts every real token's absolute RoPE position by `lp`, and the two absolute rotations round differently in fp even though the relative phase (and thus the attention) is identical.
- `ragged_end_to_end_greedy_parity_most_padded_row_multiround` / `_hits_eos` greedily GENERATE multiple tokens through the same loop and assert the most-padded row's emitted token sequence (and EOS stop) is byte-identical to that row run alone as B=1, for both attention families.
- `windowed_left_padding_mask_masks_padding_and_band_when_buffered_over_window` pins the relaxed mask in the `size + offset > window` buffered regime.

The shared synthetic 1-layer Gemma 4 wrapper builder is exposed (parameterized by attention family) for these tests.

Closes #161
… fallback

The capped-regime eligibility check (max_prompt_len > sliding_window) lived
inside the committed batched burst, so its Err surfaced as a client-facing
GenerateEvent::Error to every row instead of the documented per-row classic
fallback. Add ragged_target_sliding_window() and a pre-gate in
try_run_burst_batched that returns Err(seqs) (clean re-enqueue) before
committing the burst when a ragged-allowed window exceeds the target sliding
window. (pr-reviewer finding.)
Add a brief factual note to the B>1 section recording that variable-length
ragged batching is now available behind MLXCEL_ENABLE_MTP_BATCH_RAGGED=1,
with confirmed greedy parity on the 31B and measured throughput (~0.94-1.13x)
explaining why the flag stays off by default.
@inureyes

inureyes commented Jun 5, 2026

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Summary

  • Tests: all narrow suites passing (26 gemma4_mtp_target, 21 round_loop_batched, 47 speculative_burst); cargo check --lib --tests and cargo clippy --lib --tests -- -D warnings both clean
  • Documentation: added a brief factual note to docs/benchmark_results/gemma4-mtp-speculative-decoding.md (B>1 section) recording ragged MTP availability, confirmed parity, and marginal throughput
  • PR body: updated with real-model greedy-parity result, throughput measurement, root fix description, CRITICAL out-of-regime fallback fix, and MEDIUM/LOW deferred follow-ups
  • Lint/Format: no issues found

Docs commit: 6172695. Not merged.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 5, 2026
@inureyes
inureyes merged commit 9bc3fb0 into main Jun 5, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-161-ragged-mtp-batch-window branch June 5, 2026 03:07
@inureyes inureyes added this to the 0.2 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…up#162)

* feat(mask): add windowed left-padding causal mask for ragged MTP prefill

Add create_causal_mask_with_window_and_left_padding, the sliding-window counterpart of create_causal_mask_with_left_padding. A B>1 batched MTP burst that mixes prompt lengths left-pads every row to max_prompt_len; the sliding-attention layers then need a mask that enforces both the windowed causal band and the per-row left-padding key exclusion.

The helper restricts itself to the non-capped key-axis regime (size + offset <= window) via a debug assertion, because under RotatingKVCache capping the column-to-position mapping is re-indexed and the left-padding filter would be wrong. The ragged batched MTP caller enforces this by only forming ragged windows when max_prompt_len <= sliding_window and declining otherwise.

Synthetic tests cover the no-padding fast path (byte-identical to the plain windowed mask), per-row padding-column masking, the causal upper bound, and equivalence to the plain left-padding mask in the non-capped prefill regime.

* feat(mtp): variable-length-prompt ragged batched MTP burst (flagged)

Allow a B>1 batched MTP speculative burst to span rows with different prompt lengths in a single burst, gated behind the new MLXCEL_ENABLE_MTP_BATCH_RAGGED opt-in (subordinate to MLXCEL_ENABLE_MTP_BATCH). The default path — including MLXCEL_ENABLE_MTP_BATCH=1 alone — keeps the validated same-length-only batched burst untouched.

Scheduler (scheduler.rs): drop the prompt-length equality in the burst-window predicate when the ragged flag is on, so burst-eligible rows of different lengths join one window; all other window checks (lane, max_tokens, sampling, can_join) are unchanged.

Burst driver (speculative_burst.rs): admit ragged windows only for the MTP dispatch under the flag; DFlash and the unflagged path keep the strict equal-length requirement and re-enqueue ragged windows via Err.

Gemma 4 batched adapter (gemma4_mtp_target.rs): add a left-padding prefill path. Variable-length rows are left-padded to max_prompt_len with a per-row left-padding causal mask; in the eligible non-capped regime (max_prompt_len <= sliding_window) that single mask is byte-identical to the windowed left-padding mask, so it is correct for both full-attention and sliding-window layers. Per-row seed/finalize metadata is unified through build_seed_metadata using the shifted-frame formula kv_offset = left_padding + kv_valid_len, bonus_position = kv_offset - 1; for equal-length rows (left_padding == 0) this reduces to the legacy metadata exactly. The constant per-row left_padding is stashed at prefill and threaded through every verify round so rounds stay parity-correct.

Greedy parity (temperature 0) is preserved by the left-padding uniform per-row position shift: every token in a row (prompt and every verify round) is shifted by the same constant left_padding[r], so all intra-row relative RoPE phases — and thus every argmax — match the row's standalone B=1 run. The drafter already honours per-row kv_valid_len / left_padding / position metadata, and the batched round loop already retires finished rows per-row, so neither needed changes.

Eligibility is restricted to max_prompt_len <= sliding_window; outside that the adapter declines (Err) and the scheduler re-enqueues the rows for per-row B=1 service. The on-hardware greedy-parity validation is left to the orchestrator's real-model gate; the flag keeps the path out of the production default until then.

* test(mtp): cover ragged window formation, padding builder, seed anchors

Add synthetic coverage for the variable-length batched MTP path:

- queue.rs: variable-length window formation via drain_matching_window — ragged-off keeps the length-equality gate (stops at the first mismatch), ragged-on groups different-length burst-eligible candidates into one window while still honouring the other window checks (max_tokens).
- gemma4_mtp_target_tests.rs: left_padded_input right-aligns rows and reports per-row left_padding/valid_len; padded tensor places real tokens at the [lp, max_len) suffix with zeroed leading pad; empty rows rejected. seed_anchors_from_valid_len shifted-frame formula (kv_offset = left_padding + kv_valid_len, bonus = kv_offset - 1), its equal-length reduction to legacy metadata, and per-row round-advance divergence.
- speculative_burst.rs: MLXCEL_ENABLE_MTP_BATCH_RAGGED defaults off.

Also refresh the server-startup notice and the batched-adapter docstring to document the new opt-in and the left-padding parity mechanism.

* fix: mask prompt padding in ragged batched MTP verify + drafter SWA

The ragged (variable-length) B>1 batched MTP burst (issue lablup#161, behind MLXCEL_ENABLE_MTP_BATCH_RAGGED) broke greedy parity for the most-left-padded (shortest) row: classic decode stopped at EOS but the ragged row emitted empty content and ran the full token budget. The divergence scaled with the row's left-padding `lp = max_len - L`, so the three less-padded rows stayed byte-identical while only the shortest broke.

Two independent frame-mismatch defects are fixed, both rooted in the same cause: a left-padded row's real keys live at padded indices `[lp, max_len)` (target/cache frame, carrying a uniform `+lp` RoPE shift), but two consumers compared against the unshifted prefix-valid frame.

1. Verify-round prompt-padding contamination (the active real-model defect at the production sliding_window). The ragged prefill masks each row's leading `[0, lp)` padding via an explicit left-padding mask, but every subsequent verify round took the `mask == None` forward path, which derived purely offset-based causal / windowed masks that do NOT exclude the padding columns. The padding K/V (token id 0) is never evicted from the unbounded full-attention cache, so the verify query attended `lp` spurious padding keys every round; the perturbation accumulates and flips the greedy argmax once `lp` is large enough. Fix: thread the per-row `left_padding` through `forward_with_speculative_sinks` into the `mask == None` branch and build per-attention-family left-padding-aware masks — `create_causal_mask_with_left_padding` for full attention (padding resident for the whole run) and `create_causal_mask_with_window_and_left_padding` for the sliding family while the rotating cache has not yet wrapped past the padding (once capped, the oldest padding keys are evicted and the plain windowed mask is already correct). When `left_padding` is absent or all-zero — every non-ragged path, including the equal-length batched burst and ordinary decode — the selection is byte-identical to the previous plain masks.

2. Drafter SWA window distance used the padded RoPE anchor (a latent defect that surfaces in the capped / small-window regime). After K/V normalization the drafter's shared keys are rolled to the prefix-valid frame `[0, kv_valid_len)`, yet `make_swa_mask_with_local_offsets` measured the bidirectional-window distance from `query_offset = bonus_position = lp + kv_valid_len - 1` (padded frame). That injects a spurious `+lp` into every query−key distance and over-masks the most-padded row's front keys by exactly `lp`. The RoPE anchor must stay padded (it cancels against the baked keys' `+lp` phase), but the mask distance must use the valid-frame position `kv_valid_len - 1`. Fix: derive the SWA query offset from `kv_valid_len`, not the padded anchor. For every non-padded path `bonus_position == kv_valid_len - 1`, so this is byte-identical there and only diverges (correctly) when `lp > 0`.

Regression tests (unit proxies for the real-model parity gate):

- `drafter::masks` — a 2-row ragged batch with a large length gap asserts the most-padded row's valid SWA keys are attended (pre-fix every valid key was -inf, i.e. the bonus query saw nothing).
- `utils` — a verify-round left-padding mask at a nonzero cache offset with a large per-row gap asserts the most-padded row's leading padding columns are masked while every real key the standalone B=1 run exposes attends, plus the causal upper bound on the appended query columns.

The same-length batched path and the production default remain byte-for-byte unchanged (all-zero left_padding takes the original mask branches). The orchestrator re-runs the real 31B greedy-parity + throughput gate.

* fix: mask resident prompt padding in every ragged MTP verify step

The ragged (variable-length) B>1 batched MTP burst (issue lablup#161, behind MLXCEL_ENABLE_MTP_BATCH_RAGGED) still broke greedy parity for the most-left-padded (shortest) row after the verify-contamination fix in 6f89aee: the row generated its full token budget of empty/pad output and never hit EOS while classic decode emitted a short answer then stopped. The prior fix's regression tests were mask/logit-level and passed, yet real generation still diverged — so this adds an end-to-end probe that actually generates through the real adapter and pins the defect.

Root cause: two regimes of the ragged verify forward attended the row's resident prompt padding (token id 0), perturbing the most-padded row's logits every round until the perturbation accumulated enough to flip the greedy argmax.

1. Single-token (`l == 1`) verify steps ignored left_padding entirely. The per-row left-padding mask construction in `Gemma4TextModel::forward_with_speculative_sinks` was gated on `l > 1`, so any width-1 step took the `mask == None` fast path and never masked the padding. This hit the unbounded full-attention cache (padding resident forever) hardest; the synthetic-model hidden-state probe shows the full-attention most-padded-row hidden diverging from the standalone B=1 run by ~3e-4 and growing with depth (vs the ~1.5e-5 RoPE-rounding floor).

2. The sliding-attention branch fell back to a padding-UNAWARE plain windowed mask as soon as `sliding_offset + l > sliding_window`. But the MTP rollback buffer (`RotatingKVCache::buffer_size`) keeps the sliding cache uncompacted up to a logical capacity of `sliding_window + buffer_size`, so the resident padding survives at columns `[0, lp)` long past `sliding_offset + l > window`. The gate therefore stopped masking the padding exactly while it was still resident, leaking `lp` padding keys into the most-padded row's window every verify step.

Fix: build per-row left-padding-aware masks whenever any row has left_padding, for ANY query width (including `l == 1`). Full attention uses `create_causal_mask_with_left_padding` over the full key axis. Sliding attention uses `create_causal_mask_with_window_and_left_padding` over the full key axis unconditionally — that mask already enforces both the sliding-window band (tril(offset) ∩ triu(offset - window + 1)) and the `[0, lp)` padding filter, so it is correct for `size + offset > window` too while the buffered cache is uncompacted (which the eligible regime, `max_prompt_len <= sliding_window` with realistic output lengths, never exceeds; a compacted axis has already evicted the oldest padding so `trim_mask_to_keys` crops to the padding-free suffix). The over-strict `size + offset <= window` debug-assert in `create_causal_mask_with_window_and_left_padding` is relaxed accordingly and its doc rewritten to state the real precondition (full key axis, not `size + offset <= window`).

Both the equal-length batched burst and ordinary decode have all-zero left_padding and take the unchanged plain-mask branches, so the production default (including B=1 MTP) is byte-for-byte unchanged; only the flagged ragged path changes.

End-to-end regression tests (the proxy the prior mask-level tests missed): drive the real Gemma4MtpBatchedTargetAdapter against a tiny synthetic 1-layer Gemma 4 wrapper (sliding and full-attention variants).

- `ragged_most_padded_row_verify_hidden_has_no_padding_contamination` runs the real prefill + multi-round verify/finalize loop and asserts the most-padded row's verify hidden state stays within the RoPE-rounding floor (8e-5) of the standalone B=1 run. This FAILS without the fix (~1.6e-4 sliding / ~2.8e-4 full, both above the ceiling) and PASSES with it (~1.5e-5). Bitwise parity is intentionally not asserted: left-padding shifts every real token's absolute RoPE position by `lp`, and the two absolute rotations round differently in fp even though the relative phase (and thus the attention) is identical.
- `ragged_end_to_end_greedy_parity_most_padded_row_multiround` / `_hits_eos` greedily GENERATE multiple tokens through the same loop and assert the most-padded row's emitted token sequence (and EOS stop) is byte-identical to that row run alone as B=1, for both attention families.
- `windowed_left_padding_mask_masks_padding_and_band_when_buffered_over_window` pins the relaxed mask in the `size + offset > window` buffered regime.

The shared synthetic 1-layer Gemma 4 wrapper builder is exposed (parameterized by attention family) for these tests.

Closes lablup#161

* fix: pre-gate ragged MTP burst out-of-regime windows to clean classic fallback

The capped-regime eligibility check (max_prompt_len > sliding_window) lived
inside the committed batched burst, so its Err surfaced as a client-facing
GenerateEvent::Error to every row instead of the documented per-row classic
fallback. Add ragged_target_sliding_window() and a pre-gate in
try_run_burst_batched that returns Err(seqs) (clean re-enqueue) before
committing the burst when a ragged-allowed window exceeds the target sliding
window. (pr-reviewer finding.)

* docs: note ragged B>1 MTP batching availability in benchmark results

Add a brief factual note to the B>1 section recording that variable-length
ragged batching is now available behind MLXCEL_ENABLE_MTP_BATCH_RAGGED=1,
with confirmed greedy parity on the 31B and measured throughput (~0.94-1.13x)
explaining why the flag stays off by default.

* style: cargo fmt for ragged batched MTP
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:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: support variable-length prompts in B>1 batched MTP speculative bursts

1 participant