Skip to content

fix(studio): make room for the MLX drafter in the auto offload plan - #15342

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:mlx-offload-prices-drafter
Oct 27, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:mlx-offload-prices-drafter

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

On a memory-limited Mac where an MLX load needs PLE or expert offload on auto, speculative decoding never got its drafter. An explicit mode (speculative_type mtp / dflash / dspark / eagle3) logged MLX speculative decoding: ngram (mode mtp, reason drafter_no_memory), and the default auto mode logged off (mode auto, reason auto_context_cost). Both decoded at plain speed. This PR makes the auto offload plan leave room for the drafter: always for an explicit mode, and under auto only when that costs little.

Root cause

mlx_resolve_offload planned the auto offload for the target alone, as the least offload that fits. mlx_drafter_fit then checked the drafter against that same plan, which by construction had no headroom, so the drafter was refused at every context. This happened even when a few more percent of experts on disk would have fit it.

Measured on Jundot/Qwen3.8-Flash-Next-oQ4e-mtp on a 128 GB M3 Max: the target-only plan puts 23.4% of experts on disk and fits an 8k context. The built-in MTP head is no_fit on that plan at any context.

Change

Explicit modes (first commit):

  • mlx_offload_plan and mlx_resolve_offload take an optional drafter (the first source resolve_speculation returns, via mlx_speculative.offload_drafter) and price it in the plan's sizing and context cost.
  • A drafter that cannot be sized is planned without, because the load then skips it. This way auto offload never turns off because of a drafter.
  • The load's auto-offload plan callback passes the drafter while the load speculates (not on the mlx-lm fallback replan). _mlx_estimate_offload plans the same way, so the memory estimate keeps matching the load.

Auto mode (second commit): auto's drafter must cost the target nothing, but more offload is a real cost to plain decoding. mlx_resolve_drafter_offload now plans both with and without auto's first drafter. It takes the plan with the drafter only when both of these hold:

  • No offloadable part goes more than MLX_AUTO_DRAFTER_ROOM (4 percentage points) further onto disk.
  • The drafter then passes the costless fit.

Otherwise the load keeps the target-only plan, exactly as before.

The costless check now runs against the target-only plan (baseline) and means "fits at least the context the target-only plan fits". Exact equality only made sense while both fits ran on the same plan: on Flash-Next the drafter plan fits 10,240 tokens with the head, against 8,192 for the target alone. On a single plan the two definitions agree, because a drafter never adds context there.

Explicit offload fractions and a pinned context are untouched, as before.

Why 4 points

I measured auto against the plan with the drafter on three MoE checkpoints and two Gemma 4 checkpoints, with smaller Macs emulated through the Metal recommended working set. Workloads: code copy, prose, and sampled (temperature 1.0) as the low-acceptance case.

Model (working set) Experts on disk, target-only → with drafter Plain decode cost of the extra offload (copy / prose / sampled) Drafted vs today's auto
Qwen3.8-Flash-Next oQ4e (128 GB) 23.4% → 25.8% 0 / −6 / 0% +123 / +42 / +22%
Qwen3.6-35B-A3B 8bit (36 GB) 77.7% → 79.7% −2 / −7 / −3% +68 / +42 / +16%
Qwen3.6-35B-A3B oQ4e (21.5 GB) 87.1% → 90.6% −9 / −13 / −6% +39 / +19 / +3%
  • TTFT showed no penalty from the extra offload.
  • The Gemma 4 E4B (PLE already fully offloaded) and 26B-A4B (no offload planned) loads had no room for a drafter either way.
  • The worst case (sampled, 3.5 points) still gained, and extrapolates to break-even at about 5 points; hence 4.

Validation

  • Tests:
    • New test_an_auto_drafter_gets_offload_room_only_within_the_cap_where_it_then_fits: the cap per part, the exact bound, the plan where the fit is refused, and the plans the fit is asked on.
    • New test_an_auto_load_fits_its_drafter_against_the_target_only_plan: baseline wiring through the load, including a repeat plan call.
    • Extended test_a_drafter_attaches_where_its_priced_fit_holds_and_a_pin_fits_whole: more, less and unpriceable baseline.
    • Extended test_an_mlx_estimate_prices_the_offload_the_load_applies (estimate route) and test_an_auto_offload_plan_makes_room_for_a_modes_first_drafter.
    • Mutation-checked: 21 targeted mutants of the new logic each fail their test.
  • tests/test_mlx_speculative.py and tests/test_mlx_inference_backend.py pass in full. tests/test_memory_estimate.py passes except 16 tests (GGUF, quantized attention, real-checkpoint byte pricing) that fail identically on the base commit in this environment.
  • Real models, auto mode, with unsloth-zoo including the companion fix:
Model (working set) Before After Drafted vs plain (copy / prose / sampled)
Qwen3.8-Flash-Next oQ4e (128 GB) off, auto_context_cost mtp, 25.8% experts on disk +114 / +45 / +38%
Qwen3.6-35B-A3B 8bit (36 GB) off, auto_context_cost mtp, 79.7% experts on disk +38 / +23 / +21%
Qwen3.6-35B-A3B oQ4e (21.5 GB) off, auto_context_cost unchanged: the head would cost context n/a
Gemma 4 26B-A4B 8bit (21.5 GB) off, auto_context_cost unchanged: no room n/a
  • Explicit mtp on Flash-Next: ngram, drafter_no_memory → mtp; code copy 10-14 → 25-31 tok/s, prose 13-14 → 19-22 tok/s.
cd studio/backend
python -m pytest tests/test_mlx_speculative.py tests/test_mlx_inference_backend.py -q
python -m pytest tests/test_memory_estimate.py -k "offload or drafter or speculat" -q

Notes

  • Depends on fix(mlx): build native MTP heads of mixed-precision and oQ checkpoints unsloth-zoo#2097 for the MTP head of the Qwen3.8 / Qwen3.6 oQ checkpoints to build at all. This change is independent of it and applies to every drafter kind.
  • Known residual: if auto's drafter sizes when the plan is made but then fails to build against the loaded target, that one load keeps the extra offload (at most 4 points of a part) without a drafter. Closing it would need a reload, because the offload is applied while the weights load.

… auto offload plan

With PLE or expert offload on auto, the plan priced the target alone and the drafter was then checked against it, so on a memory-limited Mac an explicit MTP/DFlash request was refused with drafter_no_memory and fell back to n-gram copies. An explicit drafter mode now plans the offload with the drafter it tries first priced in; the memory estimate plans the same way. Auto speculation keeps its plan, since its drafter must cost the target nothing, and a drafter that cannot be sized is planned without, as the load then skips it.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 26, 2026 07:50
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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 ⚠️ Failed 2026-10-27T08:02:13.555598Z
We couldn’t complete this review. Comment @codex review to try again.
e91d1fc 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.

… when it costs little

Under auto speculation the offload plan was made for the target alone, so on a Mac that needs offload the drafter never fit for free and auto fell back to plain decoding. Auto now also plans with its first drafter and takes that plan when no offloadable part goes more than 4 points further onto disk and the drafter then fits at least the context the target-only plan fits. The costless check compares against the target-only plan for that reason, and the memory estimate follows the same rule.
@Lyxot Lyxot changed the title fix(studio): make room for an explicitly requested MLX drafter in the auto offload plan fix(studio): make room for the MLX drafter in the auto offload plan Oct 26, 2026
@Lyxot Lyxot added the MLX label Oct 26, 2026
@Lyxot

Lyxot commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator Author

CI and review check for head e91d1fc:

CI: upstream jobs were all stuck in queued, so the same head and base ran in a staging PR on the fork (Lyxot#196, now closed): 54 passed, 4 skipped, 1 failed. The failing job, Repo tests (CPU, rest), has 3 failures out of 14,971 tests, and none are in files this PR touches. All three come from the base commit:

Codex review: no review completed. The automatic run when the PR opened and four @codex review requests each ended with "Something went wrong ... An unknown error occurred" within about two minutes (latest: #15342 (comment)). Codex was reviewing other PRs in this repo normally at the same time, so this looks specific to the PR on Codex's side. There were no review threads or findings to address.

Changes during this check: none to the code (head unchanged at e91d1fc); only the MLX label was added.

@danielhanchen

Copy link
Copy Markdown
Member

Most of this PR's Repo tests (CPU, rest) and Repo tests (CPU, gloo) failures are not from this PR. trl-internal-testing/tiny-Phi3ForCausalLM and tiny-Qwen3_5ForConditionalGeneration were removed from the Hub (TRL now publishes versioned names), so every phi3 TP case and the Qwen3.5 decision-model cases fail with OSError: ... is not a valid model identifier. #15355 moves the tests to the renamed repos. The encoding-guard and test_yarn_reaches_the_model[lang-*] failures came from main and are fixed there by #15351; a merge of main or a re-run picks that up.

danielhanchen added a commit that referenced this pull request Oct 26, 2026
## Problem

`trl-internal-testing/tiny-Phi3ForCausalLM` and
`trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration` no longer
exist on the Hub. The model API returns 404 for both, even with a token.
TRL now publishes versioned names instead:

- `tiny-Phi3ForCausalLM-3` and `-3.5`
- `tiny-Qwen3_5ForConditionalGeneration-3.8`, `-NoThink` and `-Think`

Every test that loads one of the old ids fails with `OSError: ... is not
a valid model identifier`. This is red on every PR based on current
main, in both `Repo tests (CPU, rest)` and `Repo tests (CPU, gloo)`
(#15337, #15342):

- the `phi3` cases of `test_tp_native_oracle.py` and
`test_tp_native_gloo.py`
- the Qwen3.5 cases of `test_decision_model.py` and
`test_decision_from_lm.py`

Nothing in the repo changed; the upstream repos were renamed.

## Fix

Point the seven references at the closest renamed repo. I picked each
one by diffing its config against the old repo's config, which was still
in a local Hub cache:

| old | new | config differences |
|---|---|---|
| `tiny-Phi3ForCausalLM` | `tiny-Phi3ForCausalLM-3` | `vocab_size` 32011
to 32064, `sliding_window` None to 2047, `attention_bias` None to False
|
| `tiny-Qwen3_5ForConditionalGeneration` |
`tiny-Qwen3_5ForConditionalGeneration-NoThink` |
`text_config.full_attention_interval` 4 to 2; byte-identical
`chat_template.jinja` |

I rejected the other candidates:

- `tiny-Phi3ForCausalLM-3.5` adds `longrope` scaling and a 131k context.
- `tiny-Qwen3_5ForConditionalGeneration-3.8` changes the MLP size, the
value heads and the embedding tying, and ships a different chat
template.

`tiny-Qwen3_5ForConditionalGeneration-NoThink` was already used by one
test.

No other `trl-internal-testing/*` id referenced under `tests/`,
`studio/`, `unsloth/`, `scripts/` or `.github/` is missing from the
org's current model list.

## Verification

Every test id that failed in CI on #15337 and #15342 for this reason now
passes against the downloaded new repos:

- `test_tp_native_oracle.py`: `phi3` plan, simulated TP, fused-qkv GQA
layout and per-module local heads
- `test_tp_native_gloo.py`: `test_tp2_matches_one_process[phi3]`,
`test_sharded_loading_matches_full_load[phi3-2-None]`,
`test_tp2_x_fsdp2_dp2_matches_one_process[phi3-True-None]` and
`test_tp2_phi3_fused_qkv_under_a_packed_plan_matches_one_process`
- `test_decision_model.py`: the clef encoding, collator and
temperature-folding cases
- `test_decision_from_lm.py`: the train, save and reload case, and
`test_the_decision_notebook_runs_unchanged_on_a_plain_qwen3_5`

That is 45 + 1 passed. The wider selection over the seven touched files
passes as well: 187 passed, 12 skipped.
@Lyxot

Lyxot commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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 Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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-zoo-staging that referenced this pull request Oct 27, 2026
unslothai#2097)

## Summary

MTP speculative decoding never attached for mixed-precision MLX
checkpoints whose MTP head is quantized differently from the model
default, such as `Jundot/Qwen3.8-Flash-Next-oQ4e-mtp` (oQ4e: 4-bit/gs64
default, every `mtp.*` linear at 8-bit). Building the head failed, so
Studio's MTP and auto modes silently ran without a drafter and users saw
the same speed as with speculation disabled.

## Root cause

The checkpoint records its per-module overrides under checkpoint paths
(`mtp.fc_embedding`, `mtp.layers.0.self_attn.q_proj`,
`mtp.layers.0.mlp.shared_expert.down_proj` at gs128, ...). mlx-vlm's
`Qwen4ExpMTPDraftModel.sanitize` strips `mtp.` from the tensors, but
`Qwen4ExpMTPSplitter.quantization_from_source` passes the override keys
through unchanged (the Qwen3.5 splitter strips `mtp.` from them; the
Qwen4-Exp one does not). `native_mtp_drafter`'s class predicate looked
overrides up by draft-module path, missed every one, quantized the 8-bit
modules at the 4-bit default, and `load_weights(strict=True)` raised:

```text
ValueError: Expected shape (2560, 320) but received shape (2560, 640) for parameter fc_embedding.weight
```

## Change

In `native_mtp_drafter`, an exact per-module override still wins
(DeepSeek-V4's mixed MXFP4/MXFP8 heads are unchanged). Any other module
stored with `.scales` now takes its bit width and group size from the
stored tensors (MLX packs the last axis: `group_size = in_dims /
scales.shape[-1]`, `bits = packed.shape[-1] * 32 / in_dims`), with the
mode from the checkpoint default. This covers any splitter rename of
override keys (prefix strip, renumbered layers, split fused experts)
without encoding a drafter's naming rules. For every head that already
loaded the result is identical: a strict load only succeeded when the
default widths were exactly the widths the tensors imply.

## Validation

- New test
`test_a_head_whose_overrides_name_its_checkpoint_paths_is_built_at_its_stored_widths`
(qwen4_exp head with `mtp.`-keyed 8-bit/gs64 and 8-bit/gs128 overrides
over a 4-bit default); mutation-checked against the old fallback, group
size from the default, and bits from the default.
- Related native-MTP and qwen4 tests in
`tests/test_mlx_speculative_metal.py` pass.
- Real checkpoints, quantized widths of every head module identical
before and after: `mlx-community/Qwen3.8-Flash-Next-4bit-mtp`,
`Jundot/Qwen3.6-35B-A3B-oQ4e-mtp`, `Jundot/Qwen3.8-27B-oQ4e-mtp`,
`mlx-community/Qwen3.8-27B-MTP-bf16`.
- `Jundot/Qwen3.8-Flash-Next-oQ4e-mtp` real weights: main raises the
error above; with this change all 22 quantized head modules build at the
widths in the checkpoint config. End to end in Studio on a 128 GB M3 Max
(with the companion Studio change below, which lets the head fit): the
head attaches and accepts 80-88% of drafts on a code-copy prompt, decode
10-14 -> 25-31 tok/s; 13-14 -> 19-22 tok/s on prose.

```bash
python -m pytest tests/test_mlx_speculative_metal.py -k "stored_widths or per_module_quantization or native_mtp_head_is_built" -q
```

## oQ checkpoints whose MTP drafter is packed into the main checkpoint

Two more oQ "-mtp" layouts (Jundot / mlx-community) never found their
drafter, so `has_native_mtp_head` was false and Studio ran them without
speculation:

- **GLM-5.3-Flash oQ (7 repos)**: omlx stores the nextn layer already
converted, the decoder layer under `mtp.<i>.block.*` and its fusion
tensors under `mtp.<i>.{eh_proj,enorm,hnorm,norm}`. mlx-vlm's splitter
only selects `layers.<num_hidden_layers>.*`. The head lookup now maps
omlx's layout back to the splitter's own (`norm` to `shared_head.norm`),
so the splitter selects, transforms and builds it as usual; the block is
treated as an already-sanitized MLX source. This head also relies on the
stored-width fallback above for its renamed overrides.
- **Gemma 4 / Gemma 4 unified oQ (20 repos)**: omlx merges the companion
assistant into the target checkpoint, its tensors under
`language_model.mtp.*` and its config at
`text_config.mtp_assistant_config`, unquantized. It is now built from
that config and those tensors through the assistant module's own `Model`
/ `sanitize` and wrapped exactly as a companion assistant
(`AssistantDrafter`). Only `gemma4*_assistant` configs take this path.

Validation:

-
`test_a_nextn_head_omlx_stores_as_mtp_blocks_is_built_as_from_its_source_layout`
and
`test_an_assistant_merged_into_its_target_checkpoint_is_built_as_its_own_checkpoint_would_be`
(the merged assistant equals the companion build in keys, dtypes and
values); both mutation-checked.
- Header-faithful synthetic builds (real tensor names, shapes and
dtypes, real configs) of all 7 GLM and all 20 merged Gemma 4 oQ repos,
including two without a safetensors index: every head builds; on main
none is found.
- Real weights, `Jundot/Qwen3.8-27B-oQ4e-mtp` in Studio on a 128 GB M3
Max: MTP attaches; decode 22.6 -> 44.2 tok/s on a copy prompt, 22.6 ->
37.6 on prose, 22.2 -> 24.2 sampled.

```bash
python -m pytest tests/test_mlx_speculative_metal.py -k "omlx_stores_as_mtp_blocks or merged_into_its_target" -q
```

## Notes

- Companion Studio PR: unslothai/unsloth#15342 (auto offload makes room
for an explicitly requested drafter; on a 128 GB Mac this model's head
otherwise never fits).
- Out of scope: with the head drafting, greedy prose output on this
checkpoint can differ from plain decode at near-tied tokens; the drafter
only proposes tokens, so this points at multi-token verify exactness on
this checkpoint rather than this change.
- `Qwen4ExpMTPSplitter.quantization_from_source` not stripping `mtp.` is
an mlx-vlm inconsistency worth fixing upstream; this change does not
depend on it.

---------

Co-authored-by: Daniel Han <[email protected]>
@danielhanchen
danielhanchen merged commit 6322f7b into unslothai:main Oct 27, 2026
57 of 59 checks passed
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.

2 participants