Skip to content

fix(cache): unbreak rotating-cache chunked prefill and default the CLI prefill to chunked - #679

Merged
inureyes merged 2 commits into
mainfrom
fix/678-chunked-prefill-rotating-cache
Jul 6, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/678-chunked-prefill-rotating-cache

Conversation

@inureyes

@inureyes inureyes commented Jul 6, 2026

Copy link
Copy Markdown
Member

Summary

Two coordinated changes: the #678 rotating-cache fix that unblocks chunked prefill for the gemma family (including the production server path), and the #674 default flip that makes cache-level chunked prefill (2048) the default for the single-sequence CLI/bench path with a per-model opt-out hook.

The #678 bug

A multi-token continuation append into a populated RotatingKVCache clamped both the stored buffer and the RETURNED K/V to max_size, so the earliest rows of any chunk with new_seq_len >= window lost their entire attention window: all-masked rows softmax to NaN and decode collapses to endless <pad> once the sliding window reaches the poisoned keys. This has been live in the PRODUCTION server path (default prefill_chunk_size 512) for every gemma-4/gemma-3 request longer than 512 prompt tokens; a 6k-token request only degenerates ~8-10 tokens in, which is why short smokes never caught it. Lineage: #401 fixed the fresh single-pass case, #413 fixed the dense-cache rolled-over case and explicitly assumed the rotating path was correct.

update_concat now mirrors upstream RotatingKVCache._update_concat: keep at most max_size - 1 prior tokens, append ALL new tokens, store and return the full concatenation; the next single-token update pre-trims back to max_size exactly as it does after a fresh over-window prefill. create_sliding_window_prefill_mask follows the same contract (kept prior + all new keys), which also fixes the broadcast_shapes abort the wider return exposed in gemma3. The Turbo4Asym rotating path carries the same historical clamp and is noted in #678 for a follow-up.

The #674 default flip

MLXCEL_PREFILL_CHUNK defaults to 2048 (matching upstream mlx-lm/mlx-vlm DEFAULT_PREFILL_STEP_SIZE); 0 forces single-pass. LanguageModel::supports_chunked_prefill (default true, mirroring mlx-vlm chunked_prefill_policy) lets models opt out; gemma3n does, with the battery evidence in the commit message. docs/environment-variables.md documents this knob and MLXCEL_ATTENTION_CHUNK_BUDGET_MB from #676.

Validation (GB10 CUDA)

check result
gemma-4-31b-it-4bit chunked-2048 vs single-pass, greedy 32 tok @ ~6k prompt token-identical (was <pad> flood)
gemma3-4b-4bit same comparison token-identical (was broadcast_shapes SIGABRT)
gemma-4-e2b-it-4bit chunks 512/1024/2048/4096 coherent (all previously <pad>)
mlxcel-server (default chunked-512), the previously failing 80-chapter shape, 48 tokens complete coherent continuation (was 10 tokens then pads)
llama-3.1-8b, qwen2.5-7b token-identical
qwen3-30b-a3b, qwen3.5-2b near-tie single-token jitter, coherent both sides
gemma-2-9b-8bit, deepseek-v2-lite coherent chunked; their single-pass sides carry separate pre-existing long-prompt degenerations
gemma3n-e2b opted out (multi-call parity unvalidated; single-pass unchanged)

Unit coverage: a cache-level sequence test driving four prefill shapes through 16 decode steps against the upstream contract, a gemma4 synthetic chunked-vs-single-pass logits parity test (including chunks exceeding the window), updated mask-shape pins (utils, gemma3), the effective_prefill_chunk gate, trait default, and opt-out override tests. cargo clippy -D warnings clean on default and cuda; mlxcel-core suite passes with only the three pre-existing environment-bound failures (verified identical on a clean tree earlier today).

Memory context (measured in #676, benchmarks/cuda_gb10_gemma_longprompt_672_2026-07-06.csv): gemma-4-12b at 32k tokens drops 56.8 to 16.6 GB MLX peak with prefill 285 to 706 tok/s under chunked prefill; 31b at 32k completes at 29.9 GB.

Closes #678
Closes #674

inureyes added 2 commits July 6, 2026 21:50
…ontinuation appends (#678)

A multi-token continuation append (chunked-prefill chunk, multi-token verify) into a populated RotatingKVCache clamped BOTH the stored buffer and the returned K/V to max_size, so the earliest rows of any chunk with new_seq_len >= window lost their entire attention window: all-masked rows softmax to NaN and every later decode step argmaxes to <pad>. This hit the production server path (default prefill_chunk_size 512) for every gemma-4/gemma-3 request longer than 512 prompt tokens, surfacing only after enough decode steps for the sliding window to reach the poisoned keys, and made the #674 chunked-prefill battery fail its whole gemma family.

update_concat now mirrors upstream mlx-lm/mlx-vlm RotatingKVCache._update_concat: keep at most max_size - 1 prior tokens in temporal order, append ALL new tokens, and store and return that full concatenation; the next single-token update already pre-trims the oversized buffer back to max_size, exactly as it does after a fresh over-window prefill (#401). create_sliding_window_prefill_mask follows the same contract, spanning min(sliding_offset, window - 1) kept prior keys plus all new keys instead of clamping to [size, window], which both removes the all-masked rows and fixes the broadcast_shapes crash the wider cache return exposed in gemma3 (its callers pass the mask with no trim_mask_to_keys step). The Turbo4Asym rotating path carries the same historical clamp and is noted in #678 for a dedicated follow-up.

Validated on GB10 CUDA: gemma-4-31b-it-4bit and gemma3-4b-4bit chunked prefill (2048) are token-identical to single-pass on a ~6k varied prompt (previously <pad> floods and a broadcast_shapes abort respectively); gemma-4-e2b-it-4bit is coherent at chunks 512/1024/2048/4096; mlxcel-server with default chunked-512 returns a complete coherent continuation at the exact shape that previously degenerated after 10 tokens. New regression tests: a cache-level sequence test driving four prefill shapes (single-pass over-window, chunk == window, oversized first chunk, sub-window chunks) through 16 decode steps against the upstream contract, a gemma4 synthetic chunked-vs-single-pass logits parity test covering chunks that exceed the window, and updated mask-shape pins in utils and gemma3.
…ith a per-model opt-out (#674)

MLXCEL_PREFILL_CHUNK now defaults to 2048 (upstream mlx-lm/mlx-vlm DEFAULT_PREFILL_STEP_SIZE) instead of 0, so mlxcel generate and mlxcel-bench-decode bound prefill memory the way the server already does; 0 still forces single-pass and any explicit value wins. A new LanguageModel::supports_chunked_prefill hook (default true, mirroring mlx-vlm chunked_prefill_policy) lets models without validated multi-call prefill parity opt out; the pure effective_prefill_chunk gate combines the env value, the model hook, and the prompt length, and is unit-tested alongside the trait default and an opt-out override.

gemma3n opts out: in the parity battery its e2b checkpoint degenerates into repeated code fences under multi-call prefill (its AltUp / per-layer-input stack has no validated multi-call parity), while its single-pass output stays unchanged.

Parity battery on GB10 CUDA (chunk 2048 vs single-pass, greedy 32 tokens, ~6k varied prompt), after the #678 rotating-cache fix in the previous commit: token-identical for llama-3.1-8b-4bit, qwen2.5-7b-4bit, gemma3-4b-4bit, and gemma-4-31b-it-4bit; near-tie jitter-class single-token differences for qwen3-30b-a3b-4bit and qwen3.5-2b-4bit (both coherent, both directions); gemma-2-9b-8bit and deepseek-v2-lite-4bit are coherent chunked while their single-pass sides carry separate pre-existing long-prompt degenerations. Peak-memory effect measured earlier on gemma-4: 12b at 32k tokens 56.8 -> 16.6 GB MLX peak with prefill 285 -> 706 tok/s, 31b at 32k completes at 29.9 GB (see benchmarks/cuda_gb10_gemma_longprompt_672_2026-07-06.csv).

docs/environment-variables.md documents MLXCEL_PREFILL_CHUNK and MLXCEL_ATTENTION_CHUNK_BUDGET_MB.
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) type:enhancement New features, capabilities, or significant additions labels Jul 6, 2026
@inureyes
inureyes merged commit 95c733a into main Jul 6, 2026
4 checks passed
@inureyes
inureyes deleted the fix/678-chunked-prefill-rotating-cache branch July 6, 2026 12:52
inureyes added a commit that referenced this pull request Jul 7, 2026
… gate (#688)

The pipeline-parallel CI's `clippy -p mlxcel --lib --tests -D warnings` step is path-gated to PRs touching the distributed modules, so this pre-existing unnecessary_cast in gemma4_tests.rs (from #679) only surfaced now that this branch adds the pipeline-parallel guard. Trivial lint fix, no behavior change.
inureyes added a commit that referenced this pull request Jul 7, 2026
#689)

* fix(gemma4): disable CUDA graphs for decode graph-race collapse (#688)

On CUDA, gemma-4 greedy decode collapsed to <pad> after 1-3 tokens and, decisively, varied run to run for the same model, prompt, and greedy settings, which is a race signature rather than a deterministic numerical bug. Prefill and the first token were already correct; the collapse was purely in the incremental single-query KV-cache decode.

Localization against an mlx_lm gemma4_text oracle: disabling the head_dim-256 sdpa_vector overlay kernel (MLXCEL_SDPA_VECTOR_LARGE_D=0), the maskless single-query path (MLXCEL_DISABLE_SINGLE_QUERY_MASKLESS=1), or mx.compile (MLX_DISABLE_COMPILE=1) each only lengthened the coherent prefix and stayed nondeterministic. Only MLX_USE_CUDA_GRAPHS=0 fully fixed it (5/5 identical, coherent 110-token decodes matching the reference). An eager unit test shows the sdpa_vector kernel is numerically correct, so the fault appears only under CUDA graph capture/replay.

Root cause: mlxcel's gemma-4 incremental decode has a CUDA-graph read-before-write hazard (missing ordering between the in-place KV-cache write and its reads under graph capture), with two contributors: the head_dim-256 sdpa_vector kernel reading the rotating sliding-window cache slice (dominant; also the source of gemma-3's latent nondeterminism) plus a residual gemma-4-specific hazard that is not in the SDPA dispatch and not in any compiled kernel. Apple mlx_lm's gemma4_text decode is graph-safe on the same hardware. The 8-bit-MLP "secondary GEMV factor" was only a sensitivity amplifier, not a separate bug.

Fix: force MLX_USE_CUDA_GRAPHS=0 for gemma-4 model types (Gemma4/Gemma4VLM/Gemma4Unified) in the shared model-load path, before the first GPU eval, honoring an explicit operator override. Non-gemma-4 families keep graph capture on and are unchanged.

Validation (GB10, release, greedy temp 0): gemma-4-12b-it-4bit-uniform and the shipped 8-bit-MLP variant both decode deterministically and coherently for 110+ tokens; gemma-4-31b-it-4bit coherent; explicit MLX_USE_CUDA_GRAPHS=1 reproduces the collapse. gemma-3-4b, qwen3.5-4b, qwen3-4b unchanged. Steady-state decode cost ~2.3% (13.51 vs 13.83 tok/s). Numbers in benchmarks/cuda_gb10_gemma4_decode_688_2026-07-07.csv.

* fix(gemma4): hoist CUDA-graph disable to main thread and cover pipeline-parallel load (#688)

Move the gemma-4 MLX_USE_CUDA_GRAPHS=0 env write to the main thread before the generation worker is spawned (new path-based helper called from server startup), so the set_var is not raced against a concurrent getenv on a request-handler thread under --no-warmup, matching the ensure_persistent_ptx_cache precedent. Also apply the guard on the in-process pipeline-parallel load path, which bypassed the four backend-seam entry points and otherwise served gemma-4 with graphs still on. The per-load-site calls remain as idempotent defense-in-depth. Correct the SAFETY comment's ordering rationale and its stale symbol reference.

* style(gemma4): drop redundant i32 cast tripping the PP-modules clippy gate (#688)

The pipeline-parallel CI's `clippy -p mlxcel --lib --tests -D warnings` step is path-gated to PRs touching the distributed modules, so this pre-existing unnecessary_cast in gemma4_tests.rs (from #679) only surfaced now that this branch adds the pipeline-parallel guard. Trivial lint fix, no behavior change.
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added status:done Completed and removed type:enhancement New features, capabilities, or significant additions labels Sep 6, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…I prefill to chunked (lablup#679)

* fix(cache): expose the prior window plus all new tokens on rotating continuation appends (lablup#678)

A multi-token continuation append (chunked-prefill chunk, multi-token verify) into a populated RotatingKVCache clamped BOTH the stored buffer and the returned K/V to max_size, so the earliest rows of any chunk with new_seq_len >= window lost their entire attention window: all-masked rows softmax to NaN and every later decode step argmaxes to <pad>. This hit the production server path (default prefill_chunk_size 512) for every gemma-4/gemma-3 request longer than 512 prompt tokens, surfacing only after enough decode steps for the sliding window to reach the poisoned keys, and made the lablup#674 chunked-prefill battery fail its whole gemma family.

update_concat now mirrors upstream mlx-lm/mlx-vlm RotatingKVCache._update_concat: keep at most max_size - 1 prior tokens in temporal order, append ALL new tokens, and store and return that full concatenation; the next single-token update already pre-trims the oversized buffer back to max_size, exactly as it does after a fresh over-window prefill (lablup#401). create_sliding_window_prefill_mask follows the same contract, spanning min(sliding_offset, window - 1) kept prior keys plus all new keys instead of clamping to [size, window], which both removes the all-masked rows and fixes the broadcast_shapes crash the wider cache return exposed in gemma3 (its callers pass the mask with no trim_mask_to_keys step). The Turbo4Asym rotating path carries the same historical clamp and is noted in lablup#678 for a dedicated follow-up.

Validated on GB10 CUDA: gemma-4-31b-it-4bit and gemma3-4b-4bit chunked prefill (2048) are token-identical to single-pass on a ~6k varied prompt (previously <pad> floods and a broadcast_shapes abort respectively); gemma-4-e2b-it-4bit is coherent at chunks 512/1024/2048/4096; mlxcel-server with default chunked-512 returns a complete coherent continuation at the exact shape that previously degenerated after 10 tokens. New regression tests: a cache-level sequence test driving four prefill shapes (single-pass over-window, chunk == window, oversized first chunk, sub-window chunks) through 16 decode steps against the upstream contract, a gemma4 synthetic chunked-vs-single-pass logits parity test covering chunks that exceed the window, and updated mask-shape pins in utils and gemma3.

* feat(generate): default the single-sequence prefill to chunked 2048 with a per-model opt-out (lablup#674)

MLXCEL_PREFILL_CHUNK now defaults to 2048 (upstream mlx-lm/mlx-vlm DEFAULT_PREFILL_STEP_SIZE) instead of 0, so mlxcel generate and mlxcel-bench-decode bound prefill memory the way the server already does; 0 still forces single-pass and any explicit value wins. A new LanguageModel::supports_chunked_prefill hook (default true, mirroring mlx-vlm chunked_prefill_policy) lets models without validated multi-call prefill parity opt out; the pure effective_prefill_chunk gate combines the env value, the model hook, and the prompt length, and is unit-tested alongside the trait default and an opt-out override.

gemma3n opts out: in the parity battery its e2b checkpoint degenerates into repeated code fences under multi-call prefill (its AltUp / per-layer-input stack has no validated multi-call parity), while its single-pass output stays unchanged.

Parity battery on GB10 CUDA (chunk 2048 vs single-pass, greedy 32 tokens, ~6k varied prompt), after the lablup#678 rotating-cache fix in the previous commit: token-identical for llama-3.1-8b-4bit, qwen2.5-7b-4bit, gemma3-4b-4bit, and gemma-4-31b-it-4bit; near-tie jitter-class single-token differences for qwen3-30b-a3b-4bit and qwen3.5-2b-4bit (both coherent, both directions); gemma-2-9b-8bit and deepseek-v2-lite-4bit are coherent chunked while their single-pass sides carry separate pre-existing long-prompt degenerations. Peak-memory effect measured earlier on gemma-4: 12b at 32k tokens 56.8 -> 16.6 GB MLX peak with prefill 285 -> 706 tok/s, 31b at 32k completes at 29.9 GB (see benchmarks/cuda_gb10_gemma_longprompt_672_2026-07-06.csv).

docs/environment-variables.md documents MLXCEL_PREFILL_CHUNK and MLXCEL_ATTENTION_CHUNK_BUDGET_MB.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…up#688) (lablup#689)

* fix(gemma4): disable CUDA graphs for decode graph-race collapse (lablup#688)

On CUDA, gemma-4 greedy decode collapsed to <pad> after 1-3 tokens and, decisively, varied run to run for the same model, prompt, and greedy settings, which is a race signature rather than a deterministic numerical bug. Prefill and the first token were already correct; the collapse was purely in the incremental single-query KV-cache decode.

Localization against an mlx_lm gemma4_text oracle: disabling the head_dim-256 sdpa_vector overlay kernel (MLXCEL_SDPA_VECTOR_LARGE_D=0), the maskless single-query path (MLXCEL_DISABLE_SINGLE_QUERY_MASKLESS=1), or mx.compile (MLX_DISABLE_COMPILE=1) each only lengthened the coherent prefix and stayed nondeterministic. Only MLX_USE_CUDA_GRAPHS=0 fully fixed it (5/5 identical, coherent 110-token decodes matching the reference). An eager unit test shows the sdpa_vector kernel is numerically correct, so the fault appears only under CUDA graph capture/replay.

Root cause: mlxcel's gemma-4 incremental decode has a CUDA-graph read-before-write hazard (missing ordering between the in-place KV-cache write and its reads under graph capture), with two contributors: the head_dim-256 sdpa_vector kernel reading the rotating sliding-window cache slice (dominant; also the source of gemma-3's latent nondeterminism) plus a residual gemma-4-specific hazard that is not in the SDPA dispatch and not in any compiled kernel. Apple mlx_lm's gemma4_text decode is graph-safe on the same hardware. The 8-bit-MLP "secondary GEMV factor" was only a sensitivity amplifier, not a separate bug.

Fix: force MLX_USE_CUDA_GRAPHS=0 for gemma-4 model types (Gemma4/Gemma4VLM/Gemma4Unified) in the shared model-load path, before the first GPU eval, honoring an explicit operator override. Non-gemma-4 families keep graph capture on and are unchanged.

Validation (GB10, release, greedy temp 0): gemma-4-12b-it-4bit-uniform and the shipped 8-bit-MLP variant both decode deterministically and coherently for 110+ tokens; gemma-4-31b-it-4bit coherent; explicit MLX_USE_CUDA_GRAPHS=1 reproduces the collapse. gemma-3-4b, qwen3.5-4b, qwen3-4b unchanged. Steady-state decode cost ~2.3% (13.51 vs 13.83 tok/s). Numbers in benchmarks/cuda_gb10_gemma4_decode_688_2026-07-07.csv.

* fix(gemma4): hoist CUDA-graph disable to main thread and cover pipeline-parallel load (lablup#688)

Move the gemma-4 MLX_USE_CUDA_GRAPHS=0 env write to the main thread before the generation worker is spawned (new path-based helper called from server startup), so the set_var is not raced against a concurrent getenv on a request-handler thread under --no-warmup, matching the ensure_persistent_ptx_cache precedent. Also apply the guard on the in-process pipeline-parallel load path, which bypassed the four backend-seam entry points and otherwise served gemma-4 with graphs still on. The per-load-site calls remain as idempotent defense-in-depth. Correct the SAFETY comment's ordering rationale and its stale symbol reference.

* style(gemma4): drop redundant i32 cast tripping the PP-modules clippy gate (lablup#688)

The pipeline-parallel CI's `clippy -p mlxcel --lib --tests -D warnings` step is path-gated to PRs touching the distributed modules, so this pre-existing unnecessary_cast in gemma4_tests.rs (from lablup#679) only surfaced now that this branch adds the pipeline-parallel guard. Trivial lint fix, no behavior change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

1 participant