Repository navigation
fix(studio): make room for the MLX drafter in the auto offload plan - #15342
Conversation
… 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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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.
|
CI and review check for head 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 Changes during this check: none to the code (head unchanged at |
|
Most of this PR's |
## 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.
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
[skip ci]
… its room plan [skip ci]
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]>
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_typemtp / dflash / dspark / eagle3) loggedMLX speculative decoding: ngram (mode mtp, reason drafter_no_memory), and the default auto mode loggedoff (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_offloadplanned the auto offload for the target alone, as the least offload that fits.mlx_drafter_fitthen 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-mtpon 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 isno_fiton that plan at any context.Change
Explicit modes (first commit):
mlx_offload_planandmlx_resolve_offloadtake an optionaldrafter(the first sourceresolve_speculationreturns, viamlx_speculative.offload_drafter) and price it in the plan's sizing and context cost._mlx_estimate_offloadplans 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_offloadnow plans both with and without auto's first drafter. It takes the plan with the drafter only when both of these hold:MLX_AUTO_DRAFTER_ROOM(4 percentage points) further onto disk.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.
Validation
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.test_an_auto_load_fits_its_drafter_against_the_target_only_plan: baseline wiring through the load, including a repeat plan call.test_a_drafter_attaches_where_its_priced_fit_holds_and_a_pin_fits_whole: more, less and unpriceable baseline.test_an_mlx_estimate_prices_the_offload_the_load_applies(estimate route) andtest_an_auto_offload_plan_makes_room_for_a_modes_first_drafter.tests/test_mlx_speculative.pyandtests/test_mlx_inference_backend.pypass in full.tests/test_memory_estimate.pypasses except 16 tests (GGUF, quantized attention, real-checkpoint byte pricing) that fail identically on the base commit in this environment.off, auto_context_costmtp, 25.8% experts on diskoff, auto_context_costmtp, 79.7% experts on diskoff, auto_context_costoff, auto_context_costmtpon Flash-Next:ngram, drafter_no_memory→mtp; code copy 10-14 → 25-31 tok/s, prose 13-14 → 19-22 tok/s.Notes