Skip to content

Studio MLX estimate: price attention scores where mlx really holds them, at the width it holds them - #16021

Merged
danielhanchen merged 12 commits into
mainfrom
studio-mlx-estimate-unfused-scores
Oct 30, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
studio-mlx-estimate-unfused-scores

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

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 #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 #15970: the copy route)
Qwen2.5-VL-3B (4-bit KV) 32768 +0 -1.50 GiB (-3.96 GiB with #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, #15970's route) 0.034
hd128 8-bit MHA, 256 x 8193 (zoo keeps the scores) 1.03

For #15935's model (Ternary-Bonsai-27B, M1 to M4), compute buffers with this PR and #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 Studio MLX estimate: ask the quantized-attention route about a cache longer than the chunk #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 Studio MLX estimate: ask the quantized-attention route about a cache longer than the chunk #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 Studio MLX estimate: ask the quantized-attention route about a cache longer than the chunk #15970 the two changes combine cleanly and 8 more tests pass.

Related to #15935 (the reporter's estimate with the default cache).

@danielhanchen danielhanchen self-assigned this Oct 29, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T15:16:51.902892Z 975cf1a Manual request
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-29T17:52:48.173686Z
We couldn’t complete this review. Comment @codex review to try again.
2450774 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 29, 2026
@danielhanchen danielhanchen changed the title Studio MLX estimate: charge the score matrix mlx builds for an unfused full-width prefill Studio MLX estimate: price attention scores where mlx really holds them, at the width it holds them Oct 29, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: e4cba9088e

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: daa87b37a8

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 51e399e9c6

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 30, 2026
… installed (unslothai#16126)

## What was wrong

`test_twins_completed_by_a_supplied_component_skip_the_early_download`
(added in unslothai#16080) fails in Backend CI's `(Python 3.13, a-f)` shard on
main and on every PR: that shard installs transformers but not
diffusers, so `_class_pins_fp32("diffusers", "SD3Transformer2DModel")`
cannot import the class and conservatively reports an fp32 pin,
`plan_fp16_twins` returns None, and `local_fp16_variant` answers None
instead of `"fp16"`.

The fp32 pin is not what the test checks (it checks that a supplied
component completes the twins and skips the early download), so the test
now stubs `_class_pins_fp32` to False, the way a diffusers class without
`_keep_in_fp32_modules` answers.

## Testing

- Shard environment (transformers 5.17.0, no diffusers): main `1 failed,
34 passed, 1 skipped` (this test); this branch `35 passed, 1 skipped`.
- With diffusers 0.42.1 and transformers 5.22.1: 36 passed on both.
- Negative control with the stub in place: the same snapshot answers
`fp16` with the VAE supplied and `None` without it, so the test still
fails if the supplied-component handling regresses.
- Main's own Backend CI `(Python 3.13, a-f)` failed on this test (job
124087281866), as did `perf/r10-gemma3-decode` (124086773561) and unslothai#16021
(124087032249).
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 975cf1a01e

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 3ec3350 into main Oct 30, 2026
29 of 35 checks passed
@danielhanchen
danielhanchen deleted the studio-mlx-estimate-unfused-scores branch October 30, 2026 16:55
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