Skip to content

fix(studio): price MLX attention on the route the runtime takes - #16517

Merged
danielhanchen merged 13 commits into
unslothai:mainfrom
Lyxot:fix/mlx-estimate-fused-d256
Nov 4, 2026
Merged

danielhanchen merged 13 commits into
unslothai:mainfrom
Lyxot:fix/mlx-estimate-fused-d256

Conversation

@Lyxot

@Lyxot Lyxot commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

The MLX memory estimate in Unsloth Studio charged attention as if every long prefill chunk built its full score tensor. Depends on unslothai/unsloth-zoo#2367, which moves those calls onto mlx's fused kernel. On Qwen3.5-4B at 262K tokens the estimate drops from 38.80 to about 19.4 GiB. The estimate then follows the route the runtime actually takes, so the fit can offer longer contexts without under-promising.

With an older unsloth-zoo, the estimate keeps its previous pricing: it asks zoo's runtime_fuses and falls back to fused_kernel_exists when that is missing.

What changed

  • Routes: attention is charged only for calls the runtime leaves unfused. Because forced routes start at a key count (8192), calls below it still build scores. The estimate walks each prompt's tail up to that floor, rather than asking only at the full context. A test compares the result against enumerating every prompt the context admits, for several route shapes and chunk sizes.
  • Padded copies: the padded K and V copies of a forced 192/128 call are charged where the route can run.
  • Quantized caches: the dequantize-or-score decision is probed at a long context, where the route applies.
  • TurboQuant: a TurboQuant KV cache was priced and fitted as a full-width cache, about 5× too large, and its prefill copy was not charged. The probe now converts the cache with mlx-vlm's own maybe_quantize_kv_cache. A prefill is charged its measured dequantized copy (10 bytes per cached K+V element) plus any scores the fused route leaves. A text model with TurboQuant is priced on the mlx-vlm route it actually takes.
  • _SCORE_LIVE 1.25 → 1.13: unfused calls measured 1.01–1.13× their score tensor on mlx 0.32.4. The one known exception is a NAX head_dim 512 tail (about 1.3×, under 100 MiB beyond this at 65K keys), which the fixed compute charge covers.

Effect on the estimate (off NAX, compute only unless noted)

Model Context Before After
Qwen3.5-4B 262K 38.80 GiB total 19.36 GiB total
MiMo-V2-Flash 262K ~82.7 GiB 3.17 GiB
DeepSeek-V4-Flash 262K 82.38 GiB 36.71 GiB

DeepSeek-V4 stays high because its tails under 1024 queries have no kernel off NAX. Models that build their own pe_scores matrix (DeepSeek-V3, GLM-5.2, Kimi) are still charged full scores, which matches what they hold.

Measured against the estimate: Qwen3.5-4B with 4-bit TurboQuant at 16K, estimated 2.87 GiB (cache plus compute) against a measured peak of 2.51 GiB.

Testing

cd studio/backend
python -m pytest -q tests/test_memory_estimate.py
python -m pytest -q tests/test_mlx_inference_backend.py -k "TurboQuant or turboquant or fit"

The selected tests pass on M3 Max. Every added test was checked against a mutation of the code it guards. TestALoadWithNoFootprintToQuote and the Qwen2.5-VL-3B and gemma-3n byte tests fail identically on main.

Lyxot added 4 commits November 3, 2026 11:42
…e takes

unsloth-zoo now runs long head_dim 256 prefill on mlx's fused kernel, so the estimate stops charging those calls the full scores and charges the shorter tail that still builds them. Qwen3.5-4B at 262K goes from 38.80 to about 19.4 GiB in total. An older zoo keeps its previous pricing.
…ull width

A TurboQuant load was estimated and fitted as a full-width cache, which overstates the cache about 5x and omits the prefill's dequantized copy. The probe now converts the cache with mlx-vlm's own routine, and a prefill is charged the measured copy plus the scores of any tail the fused route does not take. A text load is priced on the mlx-vlm route it takes.
Unfused calls measure 1.01 to 1.13 times their scores on mlx 0.32.4, so 1.25 overcharged every model that still builds them.
A forced route now starts at 8192 keys, so calls below it still build scores: the estimate walks every prompt's tail up to that floor rather than asking only at full context, and probes the quantized route at a long context. Padded K and V copies are charged where the route can run.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner November 3, 2026 03:44
@danielhanchen

Copy link
Copy Markdown
Member

(Python 3.13, g-r) fails here in studio/backend/tests/test_memory_estimate.py, and it passes on main (3 passed locally at 99d1bc6686):

test_a_full_width_cache_pays_for_the_widest_call_mlx_does_not_fuse[<lambda>-0]
test_a_full_width_cache_pays_for_the_widest_call_mlx_does_not_fuse[<lambda>-34568193]
    assert (2048, 16 * 2048) in asked
E   assert (2048, 32768) in [(1, 2), (1, 33793), (2048, 2048), (2048, 4096), (1, 32769), (2, 32770), ...]

This PR changes which route mlx_memory.py prices. The estimator no longer asks for the (2048, 32768) score shape the test expects for a full-width cache; it asks for (1, 32769) / (1, 33793) instead. If the new route is right, the test's expected shape needs updating with it. If the full-width prefill call should still be priced, the new routing has dropped it.

@Lyxot Lyxot added the MLX label Nov 3, 2026
The widest-call search now asks whether a full chunk over two chunks of keys is unfused, and bisects on key count only when it is, instead of probing a fixed mid-context chunk.
@Lyxot

Lyxot commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, this one is real and the new route is right, so the test's expected probe was stale. Fixed in 77d1f06.

The old search probed a fixed mid-context chunk, (2048, 16 * 2048). With a key floor, full chunks stop being unfused somewhere short of the context, so _widest_unfused_scores now asks whether a full chunk over two chunks of keys, (2048, 4096), is unfused, and bisects on key count only when it is. When that call fuses, no later chunk is priced, so (2048, 32768) is never asked. The full-width prefill call is still priced: the test's price assertion (priced - floor == cells * _SCORE) is unchanged and passes for all three route shapes. The probe assertion now expects (2048, 2 * 2048). Changing the probe back to the last chunk fails all three cases.

The other red jobs are not from this branch:

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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-11-04T07:09:54.446853Z c08ecf9 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[bot]

This comment was marked as resolved.

The runtime probe that can still refuse TurboQuant ran after the context was fitted at the compressed width, so a refused cache was allocated at full width for a context priced compressed. The probe now runs first, the fit uses the compressed width only when it accepts, and the KV policy reuses its answer.
danielhanchen added a commit that referenced this pull request Nov 3, 2026
## Summary

`MLX CI on Mac M1` (the `dispatch` job) is red for every unsloth PR it
runs on since unsloth-zoo #2365 (`57b40cc1`) landed. It hit #16517 at
08:16Z:

```
FAILED tests/test_mlx_inference_backend.py::test_the_stub_answers_every_helper_zoo_imports_from_inference
E   AssertionError: zoo imports ['_FIRST_USE_WORK'] from mlx.inference and the stub cannot answer them
```

zoo #2365 added `from .inference import _FIRST_USE_WORK` in
`unsloth_zoo/mlx/speculative.py`, a private counter that `inference.py`
defines and bumps. That is internal to zoo and fine. The guard is doing
its job: Studio's backend tests replace `unsloth_zoo.mlx.inference` with
a stub, the stub's fallback refuses private names on purpose, and the
guard checks that the stub still answers every name zoo imports from
that module. Without the entry, a real-model macOS test that reaches
zoo's speculative path through the stub would fail with an
`ImportError`.

## Change

`studio/backend/tests/test_mlx_inference_backend.py`: `_FIRST_USE_WORK`
joins `PLAIN_HELPERS` next to the other private names `speculative.py`
imports (`_SparseDrafter`, `_VERIFY_GDN_MAX_ROWS`). The value is a `[0]`
list, the same shape zoo uses. No product code changes.

## Testing

Linux, with unsloth-zoo main (`682b3108`) on the path,
`tests/test_mlx_inference_backend.py`:

| | result |
|---|---|
| main | `test_the_stub_answers_every_helper_zoo_imports_from_inference`
fails with the error above |
| this branch | it passes |

Apart from that test, both sides fail the same 7 cases. All of them need
`mlx_lm`, which only the macOS runner has.
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. 🚀

Reviewed commit: 8a7464a238

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

@Lyxot

Lyxot commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Review and CI status for 8a7464a238c

Codex: Didn't find any major issues on 8a7464a238c.

CI: 48 jobs pass, including the MLX inference backend and memory estimate tests. The 5 red jobs fail on tests this branch does not touch:

Job Failure Cause
dispatch test_the_stub_answers_every_helper_zoo_imports_from_inference zoo main (unslothai/unsloth-zoo#2365) imports _FIRST_USE_WORK from mlx.inference, and the inference stub doesn't provide it yet
Repo tests (CPU, studio) PowerShell runner lint, no-torch pair resolution tests/python/test_desktop_unsloth_spec_no_deps_pair.py calls subprocess.run directly
Repo tests (CPU, studio-install) Could not resolve a compatible unsloth / unsloth-zoo pair for no-torch mode install resolution
Repo tests (CPU, rest-2) file-read lint on tests/test_multi_lora_cold_compile_cpu.py unrelated test file
(Python 3.13, rest) offline scoped download tests Cannot resolve an immutable revision for black-forest-labs/FLUX.1-dev (network metadata)

The Core / Core zoo jobs were still queued when this was posted.

Changes during review:

  • 77d1f066281: updated the stale probe assertion from the CI comment. The estimator now asks whether a full chunk over two chunks of keys is unfused, instead of probing a fixed mid-context chunk. The price assertion is unchanged.
  • 8a7464a238c (thread): the load now runs the TurboQuant probe before fitting the context, and fits at full width when the probe refuses. The KV policy reuses that answer, so the probe still runs once.
  • Not changed (thread): the pre-load admission estimate can't run that probe without a loaded model, and loads run in a separate worker, so the verdict doesn't reach the API process. The gap is limited to pinned contexts on checkpoints whose cache converts but whose quantized forward fails.

@NilayYadav NilayYadav self-assigned this Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b9f8237d51

ℹ️ 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. Another round soon, please!

Reviewed commit: 7b401e339c

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026

@NilayYadav NilayYadav left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the PR! The goal of this PR is to make Studio's MLX memory estimate follow the attention route the runtime really takes once unsloth-zoo forces long causal prefill onto mlx's fused kernel, and to price a TurboQuant KV cache instead of fitting it at full width. As a summary, this PR asks zoo's runtime_fuses which calls still build full scores (walking each prompt's tail down to the forced route's key floor), charges the padded K/V copies of the 192/128 route, converts the probe cache with mlx-vlm's own maybe_quantize_kv_cache for TurboQuant and charges its dequantized prefill copy, fits the load at the TurboQuant width only after the load's probe accepts it, and lowers the unfused score multiple from 1.25 to 1.13.

Reviewers Severity Finding
- - No open findings on the current head. The NAX-specific test expectations, the stale tiny Llama byte count and the pre-load TurboQuant pricing for models whose attention cannot read the converted cache are fixed on the branch.

Concrete suggestions for each finding below.

@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: c24c320b4. 3 findings, fixed in 57481cc85 and 7b401e339.

I reproduced the long-context estimate for mlx-community/Qwen3.5-0.8B-4bit on the merge base 24d65c1 with unsloth-zoo main, and on this branch with unsloth-zoo#2367 (Apple M5 Pro, macOS, Chromium 1440x1400):

  • Before: Run settings shows Estimated Memory Usage 6.13 GiB at Context Length 131072 (compute 4.32 GB of 6.58 GB).
  • PR head: the same panel shows 3.77 GiB (compute 1.79 GB of 4.05 GB).
  • Real prefill peak above weights, same model and chunk size, base vs head: 1.625 / 1.625 GiB at 32K, 1.933 / 1.962 GiB at 64K, 2.736 / 2.736 GiB at 131K. The head estimate (kv + compute) is 2.07 / 2.44 / 3.19 GiB, still above every measured peak; the base estimate was 2.55 / 3.55 / 5.54 GiB.

PR 16517 before/after

  • Tests: 23 of the PR's tests fail on the merge base and pass here (11 behavioural, 12 new API); the full test_memory_estimate.py shows only the same 17 failures as the merge base, which come from checkpoints cached without tensors on that machine.

  • macOS 15 and macOS 26 (Apple Silicon) with unsloth-zoo#2367 installed: 931 passed, 33 skipped, plus a tiny MLX SFT run; Linux green. With the fix reverted, the TurboQuant fit tests fail.

  • Short forced calls on M5 Pro: head_dim 256, 16 queries over 32K keys goes from 2.9 to 3.9 ms per call, 64 queries from 5.3 to 3.8 ms; the 192/128 16-query call goes from 4.7 to 8.6 ms. This is the cost the zoo PR already lists.

  • With unsloth-zoo#2367 plus the padded-route change suggested there, these tests give the same results, so the estimate follows that route too.

Conclusion: real and fixed for the estimate, and it stays above the measured peak. It has to land after unsloth-zoo#2367 (with the padded-route change suggested on that PR); with an older zoo the estimate keeps the previous pricing.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c08ecf9210

ℹ️ 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 4691cc6 into unslothai:main Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants