Skip to content

fix: test precision (reranker f32, MoE autograd stop_gradient, deterministic draft parity) - #348

Merged
Brooooooklyn merged 3 commits into
mainfrom
fix/test-precision
Nov 12, 2026
Merged

Brooooooklyn merged 3 commits into
mainfrom
fix/test-precision

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Summary

Three precision fixes for tests that fail or flake on Apple Silicon.

Commit Cause Fix
fix(rerank) 3dd3bf9 NAX GPUs run f32 GEMMs in TF32, so batched and single XLM-R reranker scores differ. The reranker model thread runs in true f32 (per-thread TF32 off, as DeepSeek V4.1 does).
fix(training) 8772608 sparse_moe_functional gathered router scores with take_along_axis before stop_gradient on the top-k indices. Every Qwen3.5 MoE value_and_grad (GRPO and SFT) failed with [gather_axis] Cannot calculate VJP with respect to indices. Stop the gradient right after the top-k slice, as mlx-lm qwen3_moe.py does.
test(qwen3_5) ccbb0e6 merged_draft_projections_match_separate_bits drew new random weights each run (no seed). At T=8 the merged gate|up matmul flips last bits; down_proj spreads them over 5120 outputs, and the 5% limit sat inside that spread. Seed the RNG. Compare the merged gate|up swiglu output (gated()) with the separate path. The full output must equal down_proj(gated).

Evidence

  • MoE autograd: 2 new tests (sparse_moe_value_and_grad_unsorted_branch, ..._sorted_branch). Red on the old code with the VJP error, green after the fix.
  • Draft parity, 1000 seeds on M5 Max: old body failed 18/1000; new body failed 0/1000. gated max difference 0.10% (limit 5%).
  • cargo fmt --check, cargo clippy --all-targets -D warnings, and cargo test -p mlx-core --lib for the touched modules (599 passed) are green.

🤖 Generated with Claude Code

Brooooooklyn and others added 3 commits November 9, 2026 08:32
On gen>=17 GPUs MLX's default MLX_ENABLE_TF32=1 sends f32 GEMMs with
min(M, N) > 1 to the NAX kernels, which round inputs to TF32. A one-row
GEMM goes to gemv and stays true f32. The classifier dense layer gets
one row when a batch holds one pair and several rows otherwise, so the
same pair scored 2.7e-5 apart on its own vs. batched (bge-native
"single/batched/padded/reordered" test, M5 Max). Measured on this host:
1x64 @ 64x64 matmul error vs f64 2.4e-8; the same row inside 2x64 1.9e-4;
both 2.3e-8 with MLX_ENABLE_TF32=0.

The model thread now opts out of TF32 at load, as DeepSeek V4.1 does.
bf16/f16 checkpoints are unaffected (the gate only applies to f32).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sparse_moe_functional gathered the router scores with take_along_axis
on the top-k indices before stop_gradient, so MLX failed every Qwen3.5
MoE value_and_grad with "[gather_axis] Cannot calculate VJP with respect
to indices". GRPO and SFT both reach it through
forward_functional_dispatch. Stop the gradient right after the top-k
slice, as mlx-lm qwen3_moe.py does, and drop the later re-stop.

Regression: value_and_grad over sparse_moe_functional on both gather_mm
branches (unsorted and sorted). Red before the fix, green after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stic

merged_draft_projections_match_separate_bits drew its weights and inputs
from MLX's unseeded RNG (thread-local key seeded from the clock), so each
run drew new data. At T=8 the merged gate|up width changes the NAX
split-K and flips a few last bits of the swiglu output; down_proj then
spreads each flip over all 5120 outputs, so the share of differing MLP
outputs follows the draw (0.01%..8% over 1000 seeds) and the 5% count
bound failed on 18 of 1000 seeds.

Seed the RNG, and bound the MLP where the merge acts: at the gate|up
swiglu output (DFlash2Mlp::gated, at most 0.1% differ over 1000 seeds).
The full MLP output must equal down_proj of that output bit for bit,
and the separate path bit for bit at the exact heights.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 494dc321-78f3-4537-85e5-db93d076549b

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T01:00:51.040641Z ccbb0e6 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
…ash2 budget (Splash int8 align S4) (#356)

## What

Stage S4 of the Splash int8 KV alignment. It stacks on #355 (S28). The
reference is Splash `9124ff2c` (1.6.0), `evaluateEngineMemoryPlan`.

One memory plan now sizes the paged pool, both lane windows and the
DFlash2 KV budget for qwen3_5 dense and MoE. It replaces three separate
budgets (the 0.85 pool probe, DFlash2's 0.95 − 2 GiB then ×0.9, and
`live_prefill_headroom`).

```
hard    = WS − (15% + 1 GiB), lowered by --max-memory        (S11: Splash max(1 GiB, 2%))
fixed   = MLX active after load + other pools + 64 MiB staging + 256 MiB pipeline + 512 MiB runtime
dynamic = hard − fixed
lane    = lane state + transient(W) + growth copy + KV(W + scratch), in whole extents ≤ dynamic
window  = min(trained, largest W that fits)
```

## ⚠️ Window change on a 36 GB M3 Pro (needs your review)

The plan now charges what the old budgets left to the margin: Splash's
768 MiB reserves, the pool-growth copy, and the turn transients (verify
partials and paged prefill attention). The margin stays 15% + 1 GiB
until the governor (S11), as decided. Together this lowers the windows
until S11:

| M3 Pro inputs (27 GiB WS, 17,357 MiB active) | before S4 | S4 | with
S11's 2% margin |
|---|---|---|---|
| AR / pool window | 78,464 | 48,601 | ~120K |
| DFlash2 window | 139,257 | 61,433 | ~176K |
| pool ceiling (1 MiB blocks) | 5,051 | 3,186 | ~7.7K |

## Prefill chunk ceiling

Every qwen3_5 / MoE paged prefill (text, scheduler, serial, VLM) now
runs in chunks of at most 2,048 rows, as Splash
`ExecutionLimits::prefillTokenBudget` does, so the plan prices the chunk
the engine runs. `MLX_PAGED_PREFILL_CHUNK_SIZE` above 2,048 is capped,
and 0 (one shot) is gone for these families. CLI launchers already set
2,048.

The pool budget subtracts the lane state first (Splash
`availableForOneRequestKv = dynamic − laneStateBytes`). The scheduler
still charges the GDN cell inside the pool too, so the AR window pays it
twice versus Splash (50,585 if paid once); that is shared scheduler code
and stays a labelled gap.

## Deleted (no compatibility path)

`MLX_KV_MEMORY_UTILIZATION`, `MLX_KV_SAFETY_MARGIN_BYTES`,
`DFLASH2_KV_HEADROOM_RESERVE_BYTES`, `MLX_PAGED_CACHE_INITIAL_MB` /
`paged_cache_initial_memory_mb`, the qwen3_5 one-sequence pool cap,
qwen3_5/MoE reads of `MLX_PAGED_PER_SEQ_CTX`, the TS overlay's 16,384 /
2,048 MiB defaults and `MLX_PAGED_CACHE_MEMORY_MB`.
`MLX_PAGED_PER_SEQ_CTX` stays for the families outside this work.

## New

- `--max-memory SIZE` (lower only) on `mlx serve` and `mlx agent`,
through the host to `Qwen35LoadOptions.max_memory_bytes`. A value above
the automatic budget is ignored with Splash's log line.
- Load errors that name the limit: the plan cannot hold one lane and the
runway; an explicit pool above the plan (16,384 MiB on the M3 Pro inputs
→ "at most 3,186 MiB"); the startup audit finds memory over the plan.
- `/v1/models` before load: `estimateQwen35ContextWindow` plans from
file sizes without loading.

## Splash gaps (labelled)

- 27B lane: 355,217,408 B vs Splash 356,122,624 B (−905,216): no 4-bit
draft window, a 2,311-row ring, no 16 KiB conv alignment.
- Flash Next is FN1 (index plane, E1 64K allowance, E9 PLE share).
- `--max-memory` reaches qwen3_5/MoE loads only.

## Tests

Plan module: 18 tests, 25 named mutations. Wiring: 17 mutations. TS: new
flag and overlay tests with mutations. Golden: WS 25,769,803,776 → hard
20,830,591,385 with mlx-node's margin (Splash's 24,696,061,952 recorded
for S11; mutation "Splash margin" → red).
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`: clean.
- mlx-core `--lib` scoped: 784 + 379 passed; mlx-paged-attn profile 5 +
6 passed.
- `yarn typecheck`, `vp lint` (21 files), `vp test` on 75 touched and
importing files: 1,426 passed. `bge-native` fails at 2.7e-5 vs 5e-6:
that is the NAX TF32 reranker drift fixed by #348 (not in this stack's
base).
- No live model run yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
…indow (#358)

Stage S22 of the Splash int8 KV alignment (stack #344). Base: FN1
(#357).

`mlx serve` and `mlx agent` take `--max-context N`, as Splash 1.6 does.
Past the native window, the target RoPE uses static YaRN.

```
--max-context N  (K = 1024, M = 1,000,000; 1..=1,010,000; unset = auto)
  N ≤ native (262,144) → caps every window; RoPE unchanged (bit for bit)
  N > native           → YaRN factor N/native on the target RoPE; the draft keeps its own
  N > default-lane plan window → the load fails (Splash ServingRuntime::start text)
families: qwen3_5, qwen3_5_moe, qwen4_exp; others refuse the option
```

## Splash rules ported
- YaRN math as Splash `rotaryInverseFrequencies` / `attentionFactor`:
beta_fast 32, beta_slow 1, rotated q/k dims × `0.1·ln(f)+1`. YaRN is on
only where native is 262,144.
- The plan prices the served window. Flash Next's KV allowance is N.
- The default lane (DFlash2 with a draft, else the pool, else the flat
lane) refuses an N above its plan window. The other lanes clamp to N.
- A checkpoint whose RoPE is already scaled is refused (`rope_type` /
GGUF `rope.scaling.type`).
- The cold-tier key gets `rope yarn <%.17g> <native>` only with YaRN.
The saved `config.json` never carries the factor. Training refuses a
YaRN load.
- Deleted: the four draft-window caps and the draft's
`max_position_embeddings` accessors (Splash caps by the target only).

## Tests
- 400K: factor 1.5625, attention factor `0x3f85b665`, and Splash's table
bit for bit. A 100K cap publishes 102,400; 400K plans 409,600. A flat
load whose 4 GiB plan holds 45,056 rows refuses 45,057.
- 28 Rust and 15 TS named mutations, each red when on and green when
off.
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`, `yarn
typecheck`, `vp lint`, `vp fmt --check`: clean. Rust filters `nn::rope
engine:: paddleocr_vl qwen3_5 qwen4_exp functional hybrid_scheduler`:
all pass (`RUST_TEST_THREADS=1`).
- One TS test fails, `bge-native`: the reranker drift that #348 fixes.
#348 is not in this stack's base.

## Not in this PR
- No live run past 262,144 tokens. The live check (100K / 400K on
qwen3.8-27b, and T=0 output unchanged with no flag) is not run.
- Splash's prefill `attentionPairs` cap is not ported. Fused
`mlx_qk_norm_rope` steps aside under YaRN, so decode past native is
slower.
- YaRN angles match Splash within f32 tolerance, not bit for bit (MLX
inverts the periods on the GPU).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 61e72da into main Nov 12, 2026
10 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/test-precision branch November 12, 2026 16:01
Brooooooklyn added a commit that referenced this pull request Nov 13, 2026
…out MPP prefills through a portable path (#377)

## Why

main CI run 43254067201 (61e72da, after #344 and #348) failed three
jobs.

| Job | Cause | CI error |
|---|---|---|
| Clippy, cargo test (mlx-core lib) | #348's `tiny_moe_config` in
`utils/functional.rs` builds `Qwen3_5MoeConfig` with two fields #344
removed and misses `rope_scaling` | `error[E0560]: struct
Qwen3_5MoeConfig has no field named paged_cache_initial_memory_mb`
(functional.rs:2032), same for `use_block_paged_cache` (2034) |
| e2e qwen3_5-dense | Since #344 the memory plan refuses an explicit
pool above its own. The test pins 512 MiB; on the macos-26 runner the
plan allows 181 MiB | `Qwen3.5: paged_cache_memory_mb 512 exceeds the
181 MiB of KV pool the model and this Mac's memory allow; omit it or set
at most 181` (p2_paged_thinking_honors_enable) |

Cargo stops at the first failing test binary, so the rest of the leg
never ran. Two more tests in it had the same problem:

| Test | Explicit pool | Result on the runner |
|---|---|---|
| `p2_paged_thinking_honors_enable` | 512 MiB | failed in CI |
| `qwen3_5_session` | 512 MiB | would fail (never ran) |
| `qwen3_5_cold_tier_parity` (harness) | 1024 MiB | would fail (never
ran) |
| `qwen3_5_delta_chat`, `qwen3_5_concurrent_batched_parity` | none |
pass |
| lib_tests (2 tiny synthetic models, 256 MiB) | inside the plan | pass
|

## Fix

- `functional.rs`: drop `paged_cache_initial_memory_mb` and
`use_block_paged_cache`, add `rope_scaling: None`. `persist_paged_cache`
still exists on main and stays. The struct now matches
`Qwen3_5MoeConfig` and `tests/common/mod.rs`.
- `p2_paged_thinking_honors_enable`, `qwen3_5_session`: stop writing
`paged_cache_memory_mb`, so the plan sizes the pool. The 512 was only
there to keep the pool small, and the pool now grows by extents.
`paged_block_size = 16` stays because the session test's prefix
assertion depends on it.
- Cold-tier harness: `pool_memory_mb` becomes `Option<u32>`. The default
stays `Some(256)`, and the new `with_planned_pool()` leaves the key out.
The qwen3_5 gate uses it: the 181 MiB planned pool holds about 15k BF16
tokens, and the gate needs two prompts of about 1,260 tokens each.
Measured: `evictions=0`.

Other legs, checked:

| Leg / test | Explicit pool | Decision |
|---|---|---|
| qwen3: `qwen3_paged_vs_flat_parity`, `qwen3_cold_tier_parity`,
`qwen3-paged-*.test.ts` | 256 | Unchanged. The leg passed on the same
runner |
| lfm2: `lfm2_paged_vs_flat_parity`, `lfm2_cold_tier_parity` | 256 |
Unchanged. The leg passed on the same runner |
| gemma4 (PR opt-in): `gemma4_grouped_cold_tier_parity` | 1024 |
Unchanged. It needs a full-context lane, and it passes under the runner
simulation below |
| nemotron_h: `*_paged_vs_flat_parity`, `*_mtp_midcycle_state` | 512 |
Unchanged. The leg is skipped on every event (needs a self-hosted
runner) |

## Local repro

Model: `yarn mlx download model -m Qwen/Qwen3.5-0.8B` + `yarn mlx
convert -d bf16 -m qwen3_5`, as in ci.yml. The runner's working set is
simulated with an uncommitted, env-switched override of
`mlx_max_recommended_working_set_size` and the
`recommendedMaxWorkingSetSize` read in `mlx_paged_dispatch.cpp`. A
working set of 5,010,305,024 B reproduces the CI message exactly (`...
exceeds the 181 MiB ...`). The whole leg ran with the CI env (`CI=true`,
`MLX_METALLIB_STRICT=1`, `MLX_TEST_REQUIRE_METAL=1` for lib_tests,
`QWEN35_STAGE2_MODEL_PATH` + `MLX_SCHED_MAX_NUM_SEQS=2` for stage2,
`--test-threads=1`), with `--no-fail-fast`.

| Run | p2 | session | cold tier | delta_chat | lib_tests | stage2 |
|---|---|---|---|---|---|---|
| simulated runner, before | FAIL (512 > 181) | FAIL (512 > 181) | FAIL
(1024 > 181) | 6/6 | 2/2 | 1/1 |
| simulated runner, after | ok | ok | ok (hits=42, corruptions=0,
evictions=0) | 6/6 | 2/2 | 1/1 |
| native M5 Max, after (simulation removed) | ok | ok | ok | 6/6 | 2/2 |
1/1 |

## Gates

| Gate | Result |
|---|---|
| `cargo fmt --all -- --check` | pass |
| `cargo clippy --workspace --all-targets -- -D warnings` | pass |
| `cargo test -p mlx-core --lib` | 4823 passed, 0 failed, 221 ignored |
| `cargo test --workspace --test '*' --no-fail-fast`
(`MLX_TEST_REQUIRE_METAL=1`) | 111 binaries, 323 passed, 0 failed |

No TS changes.

## Portable prefill path for GPUs that cannot build the MPP kernel
(34d5b06)

**Problem.** Since S10 (#368) and S10f (#369), every Qwen3.5 dense / MoE
prefill chunk and every MTP / DFlash2 verify block attends only through
the MPP tensor-op kernel
`paged_prefill_attention_{bf16,q8}_split_g*_d*`. The hosted macOS VM
cannot build those pipelines, so the e2e `qwen3_5-dense` leg failed:

```
MLX eval failed in paged_prefill_layer_barrier while materializing 1 arrays: paged prefill attention kernel paged_prefill_attention_q8_split_g4_d256 has no pipeline on no known Apple GPU family
```

**Fallback.** `PagedKVCacheAdapter::paged_prefill_attention` now goes
one of two ways:

```
device_prefill_mpp_builds()?  (asked once per process, OnceLock)
   yes -> MPP split + reduce   (unchanged)
   no  -> gather_kv_for_prefill_chunk_varlen  (vLLM varlen kernel, plain Metal, already in the tree)
```

- **How it is chosen:** the new `mlx_paged_prefill_mpp_builds()` tries
to build all 24 MPP pipelines. If any build throws, the answer is false.
Linux returns false. The answer is never taken from catching an error on
a single call.
- **Same input as MPP:** the fallback reads the same stored rows,
including int8 values times their scale.
- **One warning:** the first time the device answers no, it logs
`paged_prefill_portable`.
- **Departs from Splash on purpose:** Splash has no such fallback. The
code comment names its kernel (`kernels/prefill/paged_attention.metal`,
`paged_attention_tile.h`).
- **About 40 lines of production code.** It adds no new kernel and
restores none of the deleted route.

**Tests**

| Test | Checks |
|---|---|
| `portable_prefill_matches_the_tile_kernel` | Fallback and MPP against
an f64 reference, within Splash's `checkOutput` bound. Pools: int8 and
bf16. Geometry: g4/D128, g8/D256, g16/D256. Cases (committed, rows): (0,
40), (40, 24), (600, 9) (past the 512-token switch), and a 5-row verify.
Largest difference between fallback and MPP: 0.25 (values carry ×60
outliers). On the VM it runs the fallback half only. |
| `prefill_routes_once_and_to_mpp_where_it_builds` | MPP is launched
once per chunk wherever it builds, and the device is asked exactly once
per process. |
| `portable_prefill_turn_matches_the_tile_turn` | Tiny seeded model,
70-token prompt, 16 greedy steps, bf16 pool (D128) and int8 pool (D256).
Logits stay within 0.02 (measured 0.0098 / 0.0078). With a tie screen,
16 of 16 tokens are equal. |
| `paged_attention_reads_its_own_rows_back` | Refactored onto the shared
reference helper; unchanged. |

**Mutations** (one build, runtime switches, removed before the commit)

| Id | Mutation | Red test | Failure |
|---|---|---|---|
| PF1 | Always take the fallback | routes test | `one tile launch per
chunk`, left 0, right 2 |
| PF2 | Fallback at `committed - 1` | parity test | Int8 8/2 D128 P 40 T
24: worst error 121 × bound |
| PF3 | Probe skips the OnceLock | routes test | asked 3 times, expected
1 |

All three passed with the switch off.

**VM simulation** (uncommitted; removed). It forces the working set to
5,010,305,024 B, makes every MPP pipeline throw the CI error text, and
makes `mlx_test_gpu_lacks_apple_family` return true. Each run is the
full `qwen3_5-dense` leg as `ci.yml` runs it.

| Run | Integration (4 binaries) | lib_tests | stage2 | "has no
pipeline" lines |
|---|---|---|---|---|
| sim, before (bf19716) | 0/1, 0/1, 1/6, 0/1 FAILED | 0/2 FAILED | 0/1
FAILED | 11 (the CI error, reproduced) |
| sim, with fallback | 1/1, 1/1, 6/6, 1/1 | 2/2, no `skipping` | 1/1 | 0
|
| native M5, sim removed | 1/1, 1/1, 6/6, 1/1 | 2/2, no `skipping` | 1/1
| 0 |

**Gates** (logs in
`/Volumes/PM9A1/claude-scratchpad/7e002cb3-kv-int8/fallback/`)

| Gate | Result |
|---|---|
| `cargo fmt --all -- --check` | ok (`gate-fmt.log`) |
| `cargo clippy --workspace --all-targets -D warnings` | ok
(`gate-clippy2.log`) |
| `cargo test -p mlx-core --lib` | 4826 passed, 0 failed
(`gate-lib.log`) |
| `cargo test -p mlx-paged-attn` | 334 passed (`gate-paged-attn.log`) |
| `cargo test --workspace --test '*' --no-fail-fast` | 323 passed, 0
failed (`gate-int.log`) |
| Live T=0 smoke, qwen3.5-0.8b (MPP), serial + scheduler, chunk 64 |
byte-equal to before (`smoke-{before,after}-*.json`) |

No `#[napi]` change, so no `index.d.cts` update.

**Known gaps**
- **bf16 scratch is not charged.** On a fallback device with a bf16
pool, the varlen partials are not charged by the memory plan: about
`rows × Hq × ceil(ctx/512) × (D+2) × 4 B`. int8 is bounded by the
kernel's 2,048 row-partition tiling.
- **Not bit-equal to MPP.** Tokens can differ at bf16 ties between a
device that builds MPP and one that does not. On one device the route
never changes.
- **Not yet run on the real VM.** The int8 varlen pipelines have not run
on the hosted VM; only CI can confirm it accepts them.
- **M1 / M2 still untested.** They take MPP if all 24 pipelines build,
otherwise the fallback.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 13, 2026
…art (#378)

Stage S13 of the Splash int8 KV alignment (follows stack #344, now in
main). Base: main.

> This branch sits on #377 (main CI fix) and shows its 2 commits until
#377 merges; then it is rebased onto main. Review only the last commit.

DFlash2 states (GDN cell + 4-bit draft window) now get an SSD tier, on
by default like Splash. An evicted state is written to disk and read
back on a later hit. With `--persistent-cache` the tier stays across
restarts. Splash: `StateCache` disk copies, `WriteBehind`, `SlotFile`,
`openDiskTier`, `DiskSpace`.

```
before:  evict state ──► gone (next turn re-prefills)
         qwen3_5 cold tier: off in serve; per-turn KV + GDN sidecar when on
after:   evict state ──► has disk copy?  yes ──► free RAM now
                                         no  ──► stage one write (NeedsWrite), free RAM now
         hit ──► RAM or disk (deepest) ──► read into lane ──► optional promotion
         tier: temp dir $TMPDIR/mlx-node-cache-*  (default, auto quota ≤ 32 GiB)
               <cache-dir>/<namespace> + flock    (--persistent-cache, adopted at load)
         stop: closeCache ──► one 6 s flush ──► temp dir removed
```

## Changes
- New `disk_tier.rs`: tier options, auto quota `min(32 GiB, room / 4)`,
a namespace from the target, draft and window, temp vs persistent, a
held lock, stale namespace removal at every start (Splash
`CacheDirectory::removeStale`).
- `cold_cache` (mlx-paged-attn): a `DFlash2State` object with spans
`[cell, window]`, charged its file size (Splash
`slotBytesFor(payload)`). A state lane goes before queued blocks. A
non-space write failure stops tracked writes; ENOSPC / EDQUOT count as
space errors.
- Store entries hold RAM, disk or both, with one staging buffer and one
write in flight. The memory plan sets the staging buffer aside
(`state_staging_bytes`, Splash `stateStagingBytes`).
- Ledger: `Victim.later`, uncopied runs and copy demand (60 s). An
Immediate claim passes units that land later; a CanWait claim waits on a
pending write.
- Copy demand is Splash's first term: 2 × the pages the running lanes'
next commands add beyond what they hold (`next_command_pages`,
`Tick::Full { command_pages }`).
- A disk state keeps its KV chain until the chain is on disk. A
reclaim's chain goes before a copy ahead.
- Write-behind (port of `WriteBehind`): ordinary points ≥ 2048 tokens
due after 10 s; a persistent tier copies all, a temp tier only on copy
demand; the state first, then its chain.
- A refused capture goes to disk from the lane (Splash
`publishStateToDisk`).
- Restore takes the deepest RAM or disk state; the payload must equal
the state size. A bad read discards the state and resumes lower.
Promotion is Optional and Immediate. AR turns read disk states too.
- Restart: `adopt_all` takes back states whose whole chain is on disk,
after fitting the quota.
- `closeCache` (napi, dense and MoE) flushes by a deadline. `serve` and
`mlx agent` take `--max-cache-disk`, `--persistent-cache` and
`--cache-dir`; the host closes every cache in one flush budget, and `mlx
agent` stops serve after 15 s (`supervision.ts`).
- `/health` `memory_governor.dflash2_states` gains the disk fields
(entries, bytes, offloads, failures, promotions, publications,
write-behind counts).

## Memory plan
| plan | before | after |
|---|---|---|
| 27B int8 + DFlash2 window (unit-test estimate, tier Auto) | 221,177 |
212,985 |
| state staging | – | 159,842,304 B |

The window drops 8,192 tokens: the staging buffer of one state is now
fixed. With the tier off the window stays 221,177.

## Deleted
- `--no-persist-cache`, `persistPagedCache` (agent and override),
qwen3_5 / MoE `persist_paged_cache` and their `MLX_PERSIST_PAGED_CACHE`
reads.
- The qwen3_5 per-turn KV and GDN cold sidecar path:
`ColdGroup::GdnState`, the sidecar capture / install,
`ColdTierContext.sidecar_policy` (now `ColdContextBacking`), qwen3_5 in
`COLD_RESTORE_FAMILIES`, the qwen3_5 cold parity tests.
- The GDN ladder retention (`want_ladder`, `GdnRetentionPolicy` Ladder,
the same-owner victim search); 2 checkpoints per owner.
- `Ledger::uncopied_need_bytes`, `SHUTDOWN_TIMEOUT_MS`,
`SERVE_STOP_GRACE_MS`.

## Tests
- 58 named mutations, each red when on and green when off: 53 Rust
runtime switches on one test binary, 5 TS source edits. Examples: state
charged the read bound (K81), state lane behind blocks (SL1), auto quota
ignores room (DQ1), held namespace not locked (PL1), staging left out of
the plan (SG1), `later` ignored by Immediate (LT1), failed copy kept
(WF1), chain mark dropped at landing (CM1), write-behind copies without
demand (WB1), no disk arm on a refused capture (DP1), a bad read not
discarded (BR1), adoption without the whole-chain check (AD1), flush
that writes nothing (FL3), reclaim chain behind a copy ahead (CY1), held
blocks not subtracted (CP1), stale namespaces kept on a temp open (SC1),
no quota fit at adoption (FQ1), write failure not stopping the tier
(WS1), full volume not refused (FS1), replaced lock file (NL1), host
flush budget per model (HC1), agent drops `--persistent-cache` (TSF1).
- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets
-D warnings`, `yarn build:native` (index.d.cts unchanged), `yarn
typecheck`, `yarn tsc -b --force`, `vp fmt --check` and `vp lint
--type-aware --type-check` on the touched TS files: clean.
- `RUST_TEST_THREADS=1`: `cargo test -p mlx-paged-attn` (lib + tests)
337 passed, 0 failed; mlx-core `--lib` 4,829 passed, 0 failed, 218
ignored; `cargo test --workspace --test '*'` 281 passed, 0 failed, 191
ignored; the other crates' lib / bin tests 25 passed.
- CI VM run (local switch, not committed: no Apple GPU family, paged
prefill pipelines fail to build, 4,259,180,544 B working set; CI env):
mlx-core `--lib` and `--test '*'` green after the skip below.
- `vp test` on `__test__/cli`, `__test__/server`,
`packages/{agent,cli,dashboard,lm}/__test__`, `packages/server`: 139
files, 2,936 tests passed, 8 skipped.

## Rebase onto main
- `draft_context.rs`: main added `eval()`, S13 added `write_bytes` /
`read_bytes`; both kept. `read_bytes` now evaluates with
`eval_arrays_with_context`, so a failed read is an error before the
bounds move (main's rule for `snapshot` / `copy_from`).
- `dflash2_decode.rs` tests: main's
`chunk_kv_is_booked_before_its_capture` and S13's disk tests both kept.
The 8 new disk tests that prefill on the pool take main's
`paged_prefill_unsupported` skip (they failed only on the CI VM).
- `utils/functional.rs` (#348): its MoE test config named fields main no
longer has (`paged_cache_initial_memory_mb`, `use_block_paged_cache`)
plus `persist_paged_cache`, which S13 removes; it now lists main's
fields (`rope_scaling: None`). This lib test target did not compile on
main.
- S13's deleted qwen3_5 cold parity tests and `retention_sim.rs`: main
had not changed them.

## Gaps
- No per-leaf KV demotion; a disk state writes its chain after itself
(S23).
- One object file per state or block, not slot files; a crash leaves the
temp dir until the next start (S23).
- No write budget (`--max-cache-disk-writes`) (S23).
- Disk recency is the object's last access; no relabel at stop (S23).
- Restore reads run on the model thread (S24).
- SHA-256 over every object, not CRC-32C per segment.
- Host staging copies from MLX arrays on write and on read.
- A qwen3_5 load without a DFlash2 draft has no SSD tier.
- Each loaded model opens its own tier and writer thread.
- Copy demand has no growth term; a whole DFlash2 turn adds nothing
between commands (S15).
- Old `gdn_state` objects in `~/.mlx-node/cache/paged/v1` are not
indexed or removed, and a crash between `mkdtemp` and the rename leaves
a `.mlx-node-cache-new-*` dir.
- No probation and no clean-end record (S23).
- During a long DFlash2 turn an owed chain moves only between commands
(S24).
- The R2 lock test checks `named()` directly; the R1 space check is
tested with a large reserve, not a real full volume.

## Not in this PR (live, not run)
- L0 window and `/health` disk fields on the 27B GGUF, S vs S12; L1
restart survival with `--persistent-cache` (turn 2 reads the prefix
back); L2 eviction writes under `--max-memory 22G` with the default temp
tier, temp dir gone after stop; L3 decode speed S vs S12 (within 3%).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant