Repository navigation
fix(models): release long prefill inputs held by lazy recurrent state - #3063
Merged
Merged
Conversation
A recurrent cache entry stored as contiguous(slice(...)) of a full-length tensor, or a final SSM state that the layer output does not consume, is an unevaluated graph node. In a single-pass prefill nothing evaluates the caches until the forward ends, so each layer's full-length source stays alive at once. On an M5 Max at 28.7K tokens this was 10.8 GB on qwen3.5-4b and 27.7 GB on qwen3.8-27b, on top of the logits #3054 removed. mlxcel-core gains materialized_state_tail (the last n rows along the time axis as a fresh buffer) and schedule_prefill_state. Both call async_eval once the source has at least 256 rows, so the source is released after the layer's own consumers run, without a CPU sync and without touching decode. The conv and short-conv tails of the gated-delta, Mamba, Mamba2, hybrid, LFM2, Kimi, RecurrentGemma, Baichuan and Inkling layers use them, as do the SSM final states of Mamba2, Falcon-H1, GraniteMoeHybrid, the chunked gated-delta scan and the bailing GLA scan. RecurrentGemma stored a plain slice, which kept its padded input alive even after evaluation. Tests cover the helper against a control that shows the old form retains its source; the touched families' unit tests, clippy and fmt pass.
The eager async_eval in materialized_state_tail and schedule_prefill_state went through the infallible FFI binding, so an MLX failure it surfaced (a command buffer that ran out of memory earlier in the forward) crossed the FFI boundary and aborted the process. A 28K single-pass prefill on granite-4.0-h-tiny or falcon-h1-tiny, which runs out of memory on main as well, aborted instead of returning "generation failed", which in the server would take down every request. The helpers now call try_async_eval and keep the first error per thread. MLX hands each error out once, so the crate-root try_eval, which shadows the FFI export for every mlxcel_core::try_eval caller, returns the kept error before evaluating anything else. Both cells now fail with main's message and exit code.
The benchmark doc gives peak, prefill time and output for nine checkpoints across the gated-delta, Mamba, Mamba2, hybrid, Jamba and LFM2 families, main 20ff89d against the branch. It includes an order-reversed timing control showing the fix-first slowdowns came from run order, and the OOM path showing a 28K single-pass Granite or Falcon-H1 prefill still fails with main's error. It also covers the Gemma 4 sliding-window experiment tracked in #3062. The CSV holds one row per run, and the CHANGELOG entry covers the fix. Refs #3061
7 tasks
This was referenced Nov 15, 2026
inureyes
added a commit
that referenced
this pull request
Nov 15, 2026
MLX keeps one process-global default device while its default streams are per thread, so a test that pinned the CPU with DefaultDeviceGuard moved every concurrent test's ops onto the CPU. In a parallel `cargo test -p mlxcel-core --lib`, 5 of 6 runs failed. The failures were metal_few_row_qmm_matches_dequantized_reference, the direct_decode_rows seeded-sampler streams and the sampling_row_step loop test, each of which passes alone. conv_no_plan_tests and cpu_qmm_accum_tests were the movers. A core overlay, mlx/device.cpp, applied on every backend (with the same block in the ROCm copy), stores the default device per thread. A thread that never set one follows a process default, which the new set_process_default_device sets. The runtime now uses it for `--device cpu`, so worker threads spawned after startup stay on the CPU. On non-CUDA builds the CMake step that restores modified top-level mlx/*.cpp files now keeps the core overlay. The #3063 state-tail retention guards read process-wide MLX memory, so they move to their own test binary. The mlxcel-core lib suite passed 5 of 5 parallel runs, and new tests cover a CPU guard confined to its thread and a process default that reaches later threads. Closes #3066
inureyes
added a commit
that referenced
this pull request
Nov 15, 2026
## Summary MLX keeps one process-global default device, while its default streams are per thread. Tests that pin the CPU with `DefaultDeviceGuard::cpu()` (`conv_no_plan_tests`, `cpu_qmm_accum_tests`) moved every concurrently running test's unstreamed ops onto the CPU. In a parallel `cargo test -p mlxcel-core --lib`, 5 of 6 runs failed. The failures were `metal_few_row_qmm_matches_dequantized_reference`, the `direct_decode_rows` seeded-sampler streams and a `sampling_row_step` loop test, each of which passes 20 of 20 runs alone. - **Per-thread default device:** a core overlay, `mlx/device.cpp`, stores the default device per thread. It is applied on every backend, and the ROCm copy carries the same block. `set_default_device` now moves only the calling thread. - **Process default:** `set_process_default_device` sets the default for threads that never set their own. The runtime uses it for `--device cpu`, so generation and worker threads spawned after startup stay on the CPU. - **Overlay survives CMake:** on non-CUDA builds, the CMake step that restores modified top-level `mlx/*.cpp` files now keeps the core overlay. Without this, the overlay was silently reverted. - **Memory-reading tests moved:** the #3063 state-tail retention guards read process-wide MLX memory, so they move to their own test binary. In the lib suite they flaked once the other failures were gone. ## Validation (M5 Max, metal,accelerate) - **Parallel lib suite:** `cargo test -p mlxcel-core --lib` passed 5 of 5 parallel runs (2272 tests each). The same suite failed in 2 of 3 runs on main `37b053af`. - **New tests:** - `streams::a_cpu_guard_moves_only_its_own_thread`. - `tests/process_default_device.rs`: the process default reaches later threads, and a thread override takes precedence over it. - `tests/state_tail_retention.rs`. - **CI-faithful gate:** `cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-fast -- --test-threads=1` passed 15545 tests and failed 4. The four fail identically on main: `server_exit_joins_worker::embedding_worker_is_joined_when_a_later_side_model_fails_to_load` and three `mlxcel-xla` golden-MLIR tests (`emitter::tests::from_json_reproduces_bundled_assets_byte_for_byte`, `validation::tests::{emit_all_reproduces_registered_goldens, registered_fixtures_are_byte_exact}`). - **Lint:** workspace clippy, fmt and env-var docs pass. - **Not covered:** CUDA and ROCm builds are not run here. The overlay is backend-agnostic C++, and the CPU-only link job builds it. Closes #3066
inureyes
added a commit
that referenced
this pull request
Nov 15, 2026
The Falcon-H1, GraniteMoeHybrid and PLaMo 2 SSD scans built the [B, H, L, L] float32 surrogate attention over the whole prefill piece, so a 28K single-pass prefill of granite-4.0-h-tiny or falcon-h1-tiny ran out of GPU memory on M5 Max. The three families and NemotronH now share one float32-hardened chunked scan (src/models/ssd_scan.rs) with a chunk length independent of the piece: 256 tokens, as in mlx-lm's ssm_attn, for the three, and NemotronH's configured chunk_size with its per-chunk eval unchanged. A single pass longer than 2048 tokens schedules each window's output and state with schedule_prefill_state; the callers keep scheduling the final state and storing conv tails through materialized_state_tail as after #3063. Jamba's Mamba1 graph-scan fallback built (delta * x) B and exp(delta A) as [B, L, D, N] for the whole piece before its sequential loop. It now builds them per 256-step block in graph_selective_scan, which is bit-identical for any block length. Mamba's fallback already projects one timestep at a time and is unchanged. Validated on M5 Max: single pass completes for all three families (granite 17.1 GB), 2048-chunk greedy output is byte-identical to main for granite and PLaMo 2, and the teacher-forced logit trace shows 0 to 0.025% disagreement at decided positions. New unit tests cover chunked against unchunked scans and a forced Jamba fallback. Refs #3073
4 tasks done
inureyes
added a commit
that referenced
this pull request
Nov 15, 2026
…3087) ## Summary - The Falcon-H1, GraniteMoeHybrid and PLaMo 2 SSD scans built the `[B, H, L, L]` float32 surrogate attention over the whole prefill piece. They now share one float32-hardened chunked scan with NemotronH (`src/models/ssd_scan.rs`). The chunk is 256 tokens, as in mlx-lm's `ssm_attn`, independent of the piece. NemotronH keeps its configured `chunk_size` and per-chunk eval. A single pass longer than 2048 tokens schedules each window's output and state with `schedule_prefill_state`. The callers keep the #3063 behavior: the final state is scheduled and conv tails go through `materialized_state_tail`. - Jamba's Mamba1 graph-scan fallback built `(delta * x) B` and `exp(delta A)` as `[B, L, D, N]` before its sequential loop. `graph_selective_scan` now builds them per 256-step block, and the result is bit-identical for any block length. The Mamba fallback (`mamba.rs`) already projects one timestep at a time, so its state is `[B, D, N]` per step, and it is unchanged. ## Measurements (M5 Max, 28K prompt, two order-reversed cooled rounds) | Checkpoint | Single pass, main / branch | 2048 chunks peak, main / branch | 2048 chunks prefill tok/s, main / branch | 2048 greedy output | |---|---|---|---|---| | granite-4.0-h-tiny-4bit | OOM / 17.10 GB | 9.85 / 7.46 GB | 1,834-2,345 / 3,639-5,872 | identical | | falcon-h1-tiny-90m-instruct-4bit | OOM / 9.99 GB | 3.99 / 2.28 GB | 6,756-7,222 / 17,916-20,439 | differs (see trace) | | plamo-2-1b | OOM abort / 25.62 GB | 12.21 / 9.90 GB | 5,191-6,115 / 8,130-8,910 | identical | | ai21-jamba-reasoning-3b-4bit | 6.45 / 6.45 GB | 3.25 / 3.25 GB | unchanged within noise | identical | The chunk changes the arithmetic order. Teacher-forced `logit_trace` at forward width 2112 (16,896 positions each), main as the reference, decided gap 2: | Checkpoint | Decided disagreement | Perplexity delta | |---|---|---| | granite-4.0-h-tiny-4bit | 4 / 16,148 (0.025%), largest gap 2.75 | -0.098% | | falcon-h1-tiny-90m-instruct-4bit | 0 / 12,168 | -0.024% | | plamo-2-1b | 0 / 9,400 | +0.007% | Falcon-H1 tiny's greedy divergence is in output that is already degenerate at 28K on both arms. Full tables and CSVs are in `docs/benchmark_results/ssm-prefill-scan-chunking-m5max-2026-11-15.md`. ## Test plan - [x] New unit tests: chunked against unchunked SSD for f32 and f16, with and without a prior state, and every eval policy bit-identical (`ssd_scan::tests`). Jamba graph-scan blocks bit-identical, and a forced fallback prefill over three blocks matches the fused kernel (`jamba::tests`). - [x] Family unit tests for ssd_scan, jamba, falcon_h1, granitemoehybrid, plamo2 and nemotron_h, including nemotron_h's ignored chunked-SSD oracles. - [x] `tests/mamba2_hybrid_finite.rs` and `tests/mamba2_hybrid_decode_finite.rs` with `--include-ignored` against the real checkpoints (`MLXCEL_REQUIRE_MODELS=1`). - [x] clippy, fmt, `check_env_var_docs.py`, `check_benchmark_raw_logs.py`, `make verify-kernel-dtype-keys`. Closes #3073
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Recurrent and hybrid layers stored their cache state as lazy graph nodes derived from full-length tensors: conv and short-conv tails as
contiguous(slice(conv_input)), and final SSM states that the layer output never consumes. Nothing evaluates the caches until the forward ends, so a prefill held every layer's full-length source at once. In the Granite and Falcon-H1 Mamba layers the held state includes the scan's[B, H, C, C]f32 decay matrix, so they waste a lot of memory even with 2048-token chunks.mlxcel_core::utils::materialized_state_tailandschedule_prefill_statestore the state as a fresh buffer. They start evaluating it withasync_evalonce the source has at least 256 rows, so decode and short verify blocks are untouched. Every site listed in fix(models): lazy recurrent cache state keeps full-length prefill inputs alive #3061 uses one of them. RecurrentGemma stored a plain slice, which kept its padded input alive even after evaluation, and now stores a fresh buffer too.mlxcel_core::try_eval, which now shadows the FFI export. The first build aborted the process instead.Verification (M5 Max, MLX
9f806b36, main20ff89d9, 28K-token prompt, greedy 48 tokens)generation failederror.docs/benchmark_results/lazy-recurrent-state-prefill-m5max-2026-11-15.md, which also covers the Gemma 4 sliding-window experiment that fix(cache): sliding-window caches keep the whole prompt after a single-pass prefill #3062 tracks.Test plan
mlxcel-core --lib: everything passes exceptffi_tests::metal_few_row_qmm_matches_dequantized_referenceand theengine::direct_decode_rows_testsstreams, which fail intermittently. They fail the same way on main20ff89d9, in 3 of 3 runs on this host.Closes #3061