Skip to content

Studio MLX estimate: ask the quantized-attention route about a cache longer than the chunk - #15970

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
debojyoti-dev:fix/mlx-estimate-quantized-route-15935
Oct 30, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
debojyoti-dev:fix/mlx-estimate-quantized-route-15935

Conversation

@debojyoti-dev

Copy link
Copy Markdown
Contributor

What was wrong

_dequantized_row_bytes asks unsloth-zoo's fused_kernel_exists which route a quantized-KV prefill chunk takes. Since unsloth-zoo c6d8465 ("dequantize quantized-KV attention wherever MLX 0.32.3 fuses it"), that check reads the cache length and returns False for a causal call with more queries than keys. The estimator built its probe cache with one token, so a 2048-query chunk over 1 key never routed to the dequantized copy, and every quantized-KV MLX estimate fell back to the full [heads, chunk, n_ctx] score matrix.

What changed

The probe cache is now one token longer than the prefill chunk, which is what every chunk after the first sees at runtime (and the last chunk is where the widest scores sit). _row_bytes and dequantizing_is_smaller only read the per-token widths, so the charged copy is unchanged; only the routing answer is fixed.

Effect on the quantized-attention term at 262,144 tokens with 8-bit KV, using the zoo routing rules:

Model shape Before After
GQA, head_dim 128 (Qwen2.5-7B-like), any Mac 63.97 GiB 1.53 GiB
MHA, head_dim 128 63.97 GiB 6.12 GiB
head_dim 256 (Ternary-Bonsai-27B / Qwen3.5), M5 (neural accelerators) 47.98 GiB 1.53 GiB
head_dim 256, M4 and earlier 47.98 GiB 47.98 GiB

The last row is the reporter's setup. There mlx really does build the score matrix for every chunk after the first (no fused head_dim 256 kernel for a non-square causal chunk without NAX), so ~48 GiB is the real peak of the last 2048-token chunk of a full 262K prompt. The model loads because nothing that size is allocated until a prompt gets that long. That number is left as is.

Testing

  • New test_the_route_is_asked_about_a_cache_longer_than_the_chunk (chunk 256 and 2048) stubs mlx.core and the zoo wrapper, so it runs without MLX. It fails on main and passes with the fix. The existing MLX-gated TestTheQuantizedAttentionRouteIsTheOneZooTakes::test_both_halves_of_the_wrappers_choice_are_asked[GQA-2048-True] covers the same thing against real MLX and the current zoo; I could not run it here.
  • tests/test_memory_estimate.py: 280 passed, 98 skipped; 1 failure and 4 errors (TestAnUnloadableSidecarIsNotCharged, TestSpeculationOffChargesNoDrafter) that also fail on clean main on this Windows machine.
  • tests/test_mlx_inference_backend.py (356 passed), tests/test_multi_model_primary_fit.py (41 passed), tests/test_utils.py (51 passed): same as main.
  • Tested on Windows only (no Mac here), so the MLX-gated tests were skipped.

Fixes the estimator part of #15935.

…longer than the chunk (unslothai#15935)

unsloth-zoo's fused_kernel_exists now reads the cache length and never
fuses a causal chunk over fewer keys than queries. The estimator probed
it with a one-token cache against a full prefill chunk, so every
quantized-KV MLX estimate fell back to the full score matrix. Probe with
a cache one token longer than the chunk, as every chunk after the first
sees.
@danielhanchen danielhanchen self-assigned this Oct 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #15970, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#609.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror c8a1eb93be (this PR's 2fc8a876d)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: c8a1eb93be

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror c8a1eb93be (this PR's 2fc8a876d).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 29, 2026
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…y host (#16014)

## Summary

Five tests in
`studio/backend/tests/test_memory_estimate.py::TestAnAutoContextIsMarkedShrinkable`
fail on any Apple Silicon host. The regular CI does not run this file on
macOS, so they surface when a PR touching memory estimation gets a macOS
leg (the staging xplat run for #15970 on `macos-26`; that PR changes
only the MLX estimate):

```
test_an_unnamed_context_is_priced_at_the_fit_floor[request_fields0-True-8192]
    assert shorter.gpu_bytes < resp.gpu_floor_bytes == floor.gpu_bytes < resp.gpu_bytes
E   assert 18402857 < 18402857
test_tensor_mode_takes_the_layer_fallback_floor[None]
E   assert 1102368297 == 1264897577
```

Since #12555, `_estimate_context_floor` uses `_FIT_FLOOR_MIN_CTX` (256)
on Apple Silicon, where Metal reprices down to the smallest context it
searches, and `_FIT_MIN_CTX` (8192) for a layer split elsewhere.
`TestTheContextFloorFollowsThePlacementPath` pins both paths explicitly;
this class assumes the layer-split one but reads the real host, so on a
Mac its auto-mode floor is the 256 context it compares against. The
product is right; the class never said which host it prices.

Reproduced on main on Linux with `is_apple_silicon()` forced to `True`
(the macOS runner's answer): the same 5 fail.

## What changed

The class's autouse fixture pins `utils.hardware.is_apple_silicon` to
`False`, with a comment pointing at the class that covers Metal.

## Verification

- Main with `is_apple_silicon()` forced `True`: 5 failed in this class.
- Head, same forcing: this class and
`TestTheContextFloorFollowsThePlacementPath` 39 passed.
- Head on Linux: `tests/test_memory_estimate.py` 283 passed, 98 skipped.
- With `_FIT_MIN_CTX` changed from 8192 to 4096, 7 tests in this class
fail, so it still pins the layer-split floor.
@danielhanchen
danielhanchen merged commit 245b9d0 into unslothai:main Oct 30, 2026
47 of 48 checks passed
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
…em, at the width it holds them (unslothai#16021)

## What was wrong

The MLX memory estimate only charged an attention score matrix when the
KV cache was quantized. With the default full-width (f16) cache, mlx
0.32.4 still falls back to its unfused attention whenever it has no
fused kernel for the call, and that fallback builds the full `[heads,
chunk, keys]` scores (`mlx/fast.cpp`, `scaled_dot_product_attention`
fallback; `ScaledDotProductAttention::use_fallback` in
`mlx/backend/metal/scaled_dot_product_attention.cpp`). On Macs without
neural accelerators this is every head_dim 256 or 192 prefill chunk
except the square causal one, so Qwen3.5 / Qwen3.6 / Qwen3-Next class
models were priced as if long prompts cost nothing extra, and the fitted
context could be one the prompt cannot actually fill.

For `prism-ml/Ternary-Bonsai-27B-mlx-2bit` (the model in unslothai#15935) with
the default cache, the compute buffers were 0.94 GiB at any context.

## What changed

- `_compute_bytes` asks unsloth-zoo's `fused_kernel_exists` (the same
routing table the quantized path already uses, and what mlx's fused SDPA
really accepts) which full-width calls fuse: the whole prefill chunks,
the shorter tail, and the decode step, each with the key count it really
sees. The charge is the widest unfused call over every prompt length the
context admits (a context is a ceiling, so a shorter prompt whose tail
does not fuse counts too, and the total never falls as the context
grows), at the queries' width.
- On NAX Macs (M5) the head_dim 256 split kernel needs 1024 queries, so
tails of 9 to 1023 tokens stay unfused and are now priced; tails of up
to 8 tokens whose GQA factor puts them over the vector kernel's 32-row
limit are priced too (both per `has_fused_kernel` / `use_fallback` in
mlx 0.32.4).
- Both score charges (this new one and the existing quantized-KV one)
now use the same measured width: 1.25 copies of the scores at the
queries' dtype. The quantized path charged 4 bytes per cell (float32),
but mlx-lm's quantized attention keeps the scores in the queries' dtype;
on Metal an hd256 8-bit call held 1.05 bf16 copies.
- Models with windowed caches keep the old price: the config's
`head_dim` need not be the width of their full-context layers (Gemma 4's
global layers are 512 wide, and mlx 0.32.4 blocks those), so pricing
them needs per-layer geometry this estimate does not have.
- No zoo wrapper or no MLX: unchanged.

## Effect

Real configs, priced on main vs this branch (real MLX 0.32.4, current
unsloth-zoo, no NAX = M1 to M4), sparse local snapshots with the real
safetensors headers so weights and KV bytes match the recorded values
exactly:

| Checkpoint (cache) | Context | main | this PR |
|---|---:|---:|---:|
| Qwen3.6-35B-A3B-UD-MLX-4bit (f16), M1 to M4 | 32768 | +0 | +2.50 GiB |
| Qwen3.6-35B-A3B-UD-MLX-4bit (f16), M5 (NAX) | 32768 | +0 | +1.21 GiB
(1023-token tail) |
| tiny-random-Llama, head_dim 4 (f16) | 512 | +0 | +2.49 MiB |
| Molmo-7B (f16, GQA 7: 5 to 8 token tails) | 4096 | +0 | +1.10 MiB |
| Qwen3-4B (4-bit KV, scores route on main) | 32768 | +0 | -3.00 GiB
(-7.84 GiB with unslothai#15970: the copy route) |
| Qwen2.5-VL-3B (4-bit KV) | 32768 | +0 | -1.50 GiB (-3.96 GiB with
unslothai#15970) |
| Qwen3-4B, gemma-3-270m, gemma-3n-E2B, deepseek-vl2-tiny (f16) | 32768
/ 8192 / 4096 | unchanged | unchanged |

Measured on Apple Silicon (GitHub macOS 15 and 26 runners, mlx 0.32.4 on
`Device(gpu, 0)`, no NAX), one prefill attention call, peak above its
inputs over one bf16 copy of `[heads, queries, keys]`:

| Call | Peak / one copy |
|---|---:|
| hd256 f16, 2048 x 4097 | 1.08 to 1.15 |
| hd256 f16, 2048 x 8193 | 1.08 |
| hd256 f16, 1023 x 8193 | 1.08 |
| hd128 f16, 2048 x 8193 (fused) | 0.016 |
| hd256 8-bit, 2048 x 8193 (zoo keeps the scores) | 1.05 |
| hd128 8-bit GQA, 2048 x 8193 (zoo dequantizes, unslothai#15970's route) | 0.034
|
| hd128 8-bit MHA, 256 x 8193 (zoo keeps the scores) | 1.03 |

For unslothai#15935's model (Ternary-Bonsai-27B, M1 to M4), compute buffers with
this PR and unslothai#15970: f16 KV 0.94 -> 4.69 GiB at 32K and 0.94 -> 30.93 GiB
at 262K; 8-bit KV 6.94 -> 4.69 GiB at 32K and 48.92 -> 30.93 GiB at
262K.

## Testing

- New
`test_a_full_width_cache_pays_for_the_widest_call_mlx_does_not_fuse`
(all fused / M1 to M4 routing / NAX routing with the 1023-token tail),
`test_the_scores_charged_never_fall_as_the_context_grows` and
`test_a_windowed_model_and_an_unreachable_zoo_keep_the_old_price` stub
`mlx.core` and the zoo wrapper, so they run in Linux CI; the first two
fail on main.
- New MLX-gated
`test_a_full_width_cache_is_charged_the_scores_mlx_builds_below_nax`
against the real zoo routing; fails on main.
- `test_a_real_checkpoint_is_priced_to_the_byte`: tiny Llama
690_952_857, Molmo 1_282_888_719, and the Qwen3.6 row adds 2_682_961_960
below NAX or 1_298_923_560 on NAX (computed with the real zoo table,
`nax_available` flipped). Deltas reproduced exactly on the sparse
snapshots.
- `test_the_decode_step_still_scores_where_that_is_the_wider_of_the_two`
now uses 256 heads, so the decode scores stay wider than the copy at the
measured width.
- Merged with unslothai#15970: all 34 route and score tests pass with real MLX.
- macOS 15 and 26 runners (real mlx 0.32.4 on `Device(gpu, 0)`): the new
tests pass; the only failures are the 6 MLX route tests main already
fails, which unslothai#15970 fixes.
- `tests/test_memory_estimate.py`,
`tests/test_mlx_inference_backend.py`,
`tests/test_multi_model_primary_fit.py` with real MLX on Linux: same
failures as main (all environment-specific: byte values recorded on a
Mac), plus the new tests passing. Merged with unslothai#15970 the two changes
combine cleanly and 8 more tests pass.

Related to unslothai#15935 (the reporter's estimate with the default cache).
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.

2 participants