Repository navigation
Studio MLX estimate: ask the quantized-attention route about a cache longer than the chunk - #15970
Merged
danielhanchen merged 4 commits intoOct 30, 2026
Conversation
…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.
This was referenced Oct 29, 2026
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
|
danielhanchen
added a commit
to Etherll/unsloth
that referenced
this pull request
Oct 29, 2026
This was referenced 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.
1 of 5 tasks
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).
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.
What was wrong
_dequantized_row_bytesasks unsloth-zoo'sfused_kernel_existswhich 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_bytesanddequantizing_is_smalleronly 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:
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
test_the_route_is_asked_about_a_cache_longer_than_the_chunk(chunk 256 and 2048) stubsmlx.coreand the zoo wrapper, so it runs without MLX. It fails on main and passes with the fix. The existing MLX-gatedTestTheQuantizedAttentionRouteIsTheOneZooTakes::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.Fixes the estimator part of #15935.