Skip to content

fix(models): release long prefill inputs held by lazy recurrent state - #3063

Merged
inureyes merged 3 commits into
mainfrom
fix/issue-3061-lazy-recurrent-state
Nov 15, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/issue-3061-lazy-recurrent-state

Conversation

@inureyes

Copy link
Copy Markdown
Member

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_tail and schedule_prefill_state store the state as a fresh buffer. They start evaluating it with async_eval once 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.
  • A failure surfaced by that early evaluation (for example out of memory) is kept per thread and returned by the next mlxcel_core::try_eval, which now shadows the FFI export. The first build aborted the process instead.

Verification (M5 Max, MLX 9f806b36, main 20ff89d9, 28K-token prompt, greedy 48 tokens)

model prefill peak, main peak, branch
qwen3.5-4b-4bit single pass 25.35 GB 14.53 GB
qwen3.8-27b-4bit single pass 59.50 GB 31.83 GB
qwen3-next-80b-a3b-instruct-4bit single pass 77.88 GB 62.01 GB
granite-4.0-h-tiny-4bit 2048 chunks 50.10 GB 9.85 GB
falcon-h1-tiny-90m-instruct-4bit 2048 chunks 13.48 GB 3.99 GB
mamba2-1.3b-4bit single pass 46.38 GB 18.26 GB
falcon-mamba-7b-4bit-instruct single pass 32.83 GB 11.40 GB
ai21-jamba-reasoning-3b-4bit single pass 13.81 GB 6.45 GB
lfm2.5-2.6b-8bit single pass 15.08 GB 13.47 GB
  • Output: byte-identical in all 25 A/B cells, single pass and 2048-token chunks (all cells are in the doc).
  • Prefill time: within ±3.5% in an order-reversed repeat. The first, fix-first run read up to 10% slower, and that difference went away when the order was reversed.
  • Out of memory: a 28K single-pass Granite or Falcon-H1 prefill runs out of memory on both builds, and both exit with main's generation failed error.
  • Details: 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

  • New tests: the state tail releases a long source, with a control showing the old lazy form keeps it. A deferred error is reported once, keeps the first error, and stays on its thread.
  • Unit tests for every touched family (1,184), the Mamba2 hybrid integration tests (ignored ones included), workspace clippy and fmt all pass.
  • mlxcel-core --lib: everything passes except ffi_tests::metal_few_row_qmm_matches_dequantized_reference and the engine::direct_decode_rows_tests streams, which fail intermittently. They fail the same way on main 20ff89d9, in 3 of 3 runs on this host.

Closes #3061

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
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:macos macOS (Apple Silicon) specific labels Nov 15, 2026
@inureyes
inureyes merged commit 37b053a into main Nov 15, 2026
31 checks passed
@inureyes
inureyes deleted the fix/issue-3061-lazy-recurrent-state branch November 15, 2026 09:05
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
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
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
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) platform:macos macOS (Apple Silicon) specific priority:high High priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(models): lazy recurrent cache state keeps full-length prefill inputs alive

1 participant