Repository navigation
Fine-tune and export native MTP heads and DSpark drafters - #13719
Conversation
FastModel.get_mtp_head loads a Qwen3.5/3.6 checkpoint's native MTP head (transformers drops mtp.* on load) and attaches it; UnslothMTPTrainer / UnslothDSparkTrainer train drafters against the frozen model. Every merged, GGUF, Hub and LoRA save path then writes the trained head instead of copying the stock one through.
# Conflicts: # unsloth/models/loader.py
|
These are public re-exports, and |
|
One more red here, Main passes this file (45 passed). (The |
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. |
…oks in the save routing harnesses
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df4fc3e5ec
ℹ️ 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".
| def _is_main_rank(): | ||
| """Only one process writes the head when several save the same folder.""" | ||
| try: | ||
| import torch.distributed as dist | ||
| return not (dist.is_available() and dist.is_initialized()) or dist.get_rank() == 0 | ||
| except Exception: |
There was a problem hiding this comment.
Honor is_main_process when writing the head
The new head writers gate only on torch.distributed, so when a caller passes is_main_process=False without an initialized process group, _is_main_rank() returns true even though model.save_pretrained correctly skips its own write. The unconditional calls after that save can therefore create a sidecar-only directory or race with the designated writer; the explicit is_main_process value must gate stitching and adapter-sidecar writes as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: is_main_process without an initialised process group is single process, and the sidecar write path matches every other Unsloth saver.
…on save_pretrained push, re-attach heads beside Hub adapters, read ModelScope snapshots, drop stale sidecars
…ard the adapter cache, keep datasets metadata, flag torchao exports, return an attached head
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c546e5e4d8
ℹ️ 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".
| HfApi(token = kwargs.get("token")).upload_folder( | ||
| repo_id = kwargs.get("repo_id") | ||
| or str(save_directory).rstrip(os.sep).split(os.sep)[-1], | ||
| folder_path = save_directory, | ||
| allow_patterns = files, |
There was a problem hiding this comment.
Upload the stitched head to the requested revision
When model.save_pretrained(..., push_to_hub=True, revision="dev") is used, the original Transformers upload writes the checkpoint to dev, but this follow-up upload_folder omits revision, so the trained head files are uploaded to the default branch instead. The requested revision therefore retains the stock or missing head, while the default branch may receive incompatible standalone MTP files; forward the same revision used by the original save.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: transformers' save_pretrained push has no revision argument (it forwards extra kwargs to HfApi.create_repo, which takes none), so a push to a branch does not get this far.
| raise ValueError( | ||
| "Unsloth: pass `source=` (the repo id or folder that holds the `mtp.*` tensors)." | ||
| ) | ||
| state_dict, info = load_mtp_state_dict(source, revision = revision, config = parts["config"]) |
There was a problem hiding this comment.
Preserve load credentials and cache settings for head lookup
When the target was loaded from a private repository using a per-call token, or from a custom cache with local_files_only=True, the documented no-argument get_mtp_head(model) path retains only the repository ID and calls the head loader without the token, cache directory, or offline setting. The model load can therefore succeed while this lookup retries anonymously or against the default cache and fails to obtain the same checkpoint's head. The adapter reattachment path now forwards this provenance, but the primary head-loading path still needs equivalent parameters or load-time metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: that case fails loudly on the download, and source= takes the local snapshot folder; the default path uses the logged-in or HF_TOKEN credentials like every other Hub read in Unsloth.
…s on safetensors, see through Unsloth's save_pretrained wrapper
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5b339e83cf
ℹ️ 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".
|
|
||
| internal = _INTERNAL_MTP_SAVE.get() | ||
| # PEFT's save_pretrained has no push_to_hub (its push_to_hub saves into a folder, then uploads it). | ||
| push = bool(kwargs.get("push_to_hub")) and _takes_push_to_hub(original) |
There was a problem hiding this comment.
Bind positional push_to_hub before uploading the head
When Transformers' supported positional form supplies push_to_hub=True, the value is present in args, so this expression evaluates to false even though original receives the value and uploads the checkpoint before the head is stitched. The follow-up upload is consequently skipped and the Hub checkpoint silently lacks the trained head. Fresh evidence beyond the earlier erased-signature fix is that this wrapper forwards *args unchanged but still derives push exclusively from kwargs; bind the call against the original signature before deciding whether to upload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: push_to_hub is the sixth positional parameter of save_pretrained; real callers pass it by keyword, as the transformers and Unsloth docs do.
…ckle saves in the plain wrapper, prefer a ModelScope snapshot under PEFT
|
@codex review |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a0e60f1f1d
ℹ️ 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".
| raise ValueError( | ||
| "Unsloth: pass `source=` (the repo id or folder that holds the `mtp.*` tensors)." | ||
| ) | ||
| state_dict, info = load_mtp_state_dict(source, revision = revision, config = parts["config"]) |
There was a problem hiding this comment.
Preserve the loaded checkpoint revision for head lookup
When a model is loaded with FastModel.from_pretrained(..., revision="dev") and get_mtp_head(model) is called without repeating that revision, _checkpoint_source retains only the repository ID and this call forwards revision=None. If the default branch also contains MTP tensors, the lookup succeeds but silently attaches that branch's head instead of the head belonging to the loaded weights. Unlike the earlier credential concern, the fresh evidence here is a successful lookup against the wrong revision rather than a loud download failure; default the lookup to the model config's resolved commit/revision.
Useful? React with 👍 / 👎.
| api.upload_folder( | ||
| folder_path = directory, | ||
| path_in_repo = ".", | ||
| repo_id = repo_id, | ||
| repo_type = "model", | ||
| commit_message = save_kwargs["commit_message"] or "Trained with Unsloth", | ||
| revision = save_kwargs["revision"], | ||
| create_pr = save_kwargs["create_pr"], |
There was a problem hiding this comment.
Forward the requested commit description on MTP pushes
When an attached head reroutes unsloth_save_model(..., push_to_hub=True, commit_description=...) through this upload, commit_description is silently discarded because the upload_folder call forwards only the message, revision, and PR flag. The same argument is honored by the ordinary merged-push path, so attaching a head unexpectedly changes the resulting Hub commit metadata; pass save_kwargs["commit_description"] here as well.
Useful? React with 👍 / 👎.
| if ( | ||
| _stitch_mtp_head(model, save_directory) is not None | ||
| and _written_tensor_names is not None |
There was a problem hiding this comment.
Refuse pickle saves in the full-model generic path
For a non-PEFT full-finetuned model with an attached head, save_pretrained_merged(..., safe_serialization=False) reaches this branch, writes a PyTorch .bin checkpoint, and then invokes _stitch_mtp_head, even though the new stitching implementation is explicitly limited to safetensors. The equivalent legacy and plain-save paths reject this combination before writing, but this path can fail only after the main checkpoint has been written or leave incompatible mixed-format files; perform the same attached-head/safe-serialization check before model.save_pretrained here.
Useful? React with 👍 / 👎.
| if _attached_mtp_head(model) is not None: | ||
| # The reload below drops native MTP tensors (the reason the head is stitched at all). | ||
| print( | ||
| f"Unsloth: torchao {kind} exports do not carry the trained MTP head; use merged_16bit or " | ||
| "GGUF to keep it." |
There was a problem hiding this comment.
Warn when compressed Qwen3.5 exports drop the trained head
The analogous attached-head warning is added only to the torchao exporter. For fp8, mxfp4, nvfp4, or mxfp8, the trained head is stitched into the staging checkpoint, but _compressed_quantize.py reloads the model through Transformers and omits those tensors from the final compressed save; its fallback warning also misses Qwen3.5 because _has_mtp neither checks mtp_num_hidden_layers nor nested text_config. Consequently a Qwen3.5 compressed export silently loses the newly trained head, so the compressed-tensors route should preserve it or issue the same attached-head warning before starting the expensive export.
Useful? React with 👍 / 👎.
| HfApi(token = kwargs.get("token")).upload_folder( | ||
| repo_id = kwargs.get("repo_id") | ||
| or str(save_directory).rstrip(os.sep).split(os.sep)[-1], | ||
| folder_path = save_directory, | ||
| allow_patterns = files, | ||
| commit_message = "Add the trained MTP head", | ||
| ) |
There was a problem hiding this comment.
Delete superseded weight files in the follow-up push
When the original pushed checkpoint is a single model.safetensors, append-mode stitching has to replace that layout with an index and additional shard files. This follow-up upload_folder only adds the paths reported as touched and never deletes the single-file checkpoint uploaded by the first commit, so the Hub repository retains model.safetensors; Transformers can resolve that canonical file instead of the new index and load a checkpoint without the trained head. Include the superseded filenames as deletions or stage and upload the final folder in one commit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: append mode keeps model.safetensors unchanged on disk and adds a part plus an index, so the Hub upload matches the local save exactly; llama.cpp's converter reads every part and vLLM uses the index, which is what the stitched head is for (transformers drops native MTP tensors either way).
| if os.path.isfile(os.path.join(save_directory, "adapter_config.json")): | ||
| files = ( | ||
| ["mtp_head.safetensors"] | ||
| if _save_mtp_head_beside_adapter(model, save_directory) | ||
| else [] | ||
| ) | ||
| else: | ||
| report = _stitch_mtp_head(model, save_directory) |
There was a problem hiding this comment.
Classify adapter saves from the model rather than stale files
If a full model is saved into a directory previously used for an adapter, Transformers does not remove the old adapter_config.json, so this post-save file check misclassifies the new full checkpoint as another adapter save. It writes only mtp_head.safetensors beside the output instead of stitching the tensors into the full checkpoint, and normal full-model loading ignores that sidecar. Use the model's PEFT state (for example peft_config) to choose the save mode, or remove stale adapter metadata before checking.
Useful? React with 👍 / 👎.
…sh adapter_config, refuse pickle merged saves, keep commit descriptions, flag compressed exports
# Conflicts: # tests/saving/test_save_method_lora_routing.py # tests/test_merged_hub_destination.py # unsloth/save.py
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ 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". |
…nslothai#1748) Adds `unsloth_zoo.speculative`: train speculative-decoding drafters against a frozen (optionally 4-bit) target in one process, then write them where llama.cpp and Unsloth Studio pick them up. ## Why Qwen3.5 / 3.6, GLM-4.5 / 4.7 / 5, Qwen3-Next, Nemotron-3, Step-3.5 / 3.7, Hy3 and DeepSeek-V3 ship native MTP (NextN) heads; llama.cpp drafts with them via `--spec-type draft-mtp` (Studio turns it on for Qwen3.5 / 3.6). transformers drops `mtp.*` on load, and the merged export copies the original shards through, so every fine-tuned export today carries the stock head, which was trained for the base model, not the fine-tune. Its drafts get accepted less often and decoding is slower than it could be. The same holds for separate DSpark drafters (DeepSpec / vLLM speculators) paired with a fine-tuned Qwen3. ## What - `capture.py`: one `no_grad` pass of the frozen target per batch, hooks on the final norm (post-norm hidden, what llama.cpp feeds MTP) and any decoder layers; works through PEFT / LoRA and Unsloth's fast forwards. No vLLM, no on-disk hidden-state cache. - `mtp.py`: `Qwen35MTPHead`, the native head for `qwen3_5_text` and `qwen3_5_moe_text` (packed experts, router, shared expert), state_dict names identical to the checkpoint's `mtp.*` tensors. `load_mtp_state_dict` reads only the shards that hold the head. Teacher-forced recursive training forward that mirrors llama.cpp's `graph_mtp` and `draft-mtp` driver: chain p starts from (h after the final norm at p-1, x_p) at position p and predicts x_{p+1}; recursive steps feed back the head's normed output and attend to target-derived MTP KV plus their own chain only. - `losses.py`: `ce`, `kl_div`, `tv`, `lk_hybrid` over the full vocabulary, chunked and checkpointed so 248k-vocab logits are never materialised (chunk size also capped by a 256 MB logits budget); FastMTP step weights. - `trainer.py`: `UnslothMTPTrainer` / `MTPTrainingArguments` / `MTPDataCollator` on top of `transformers.Trainer`. Only the head trains; loss is normalised by the accumulated batch's supervised tokens (gradient accumulation matches one big batch); evaluate, resume and DDP work. - `dspark.py`: `Qwen3DSparkDrafter` and `UnslothDSparkTrainer`, a port of DeepSpec's Qwen3 DSpark (anchored blocks, vanilla Markov head, confidence head, DeepSpec's loss) that saves the `Qwen3DSparkModel` schema llama.cpp converts. - `mtp_families.py` + `nextn.py`: every other native MTP / NextN head (DeepSeek-V3 style: `eh_proj(cat[enorm(embed(x)), hnorm(h)])`, the target's own decoder block, head norm, shared lm_head). `NextNHead` builds its block(s) from the target family's stock transformers decoder layer at layer index `N + i`, so attention variants (GQA, MLA, gated, sliding window, DSA) and MoE routers come from transformers itself. A family is data: checkpoint naming, which target hidden is fed in and fed back (post or pre final norm), block layout, chained heads (step k runs head k and rebuilds its own KV, like llama.cpp's driver). Experts are packed / unpacked to the checkpoint's per-expert layout, `_keep_in_fp32_modules` (MoE routing biases) stay fp32, head-serialized `embed_tokens` / `shared_head.head` copies are used when they differ from the target's and never written back. - `stitch.py`: `write_mtp_tensors` rewrites only the shard bytes of `mtp.*` (every other byte identical, atomic replace, Windows-safe), or appends `model-mtp.safetensors` + index + `mtp_num_hidden_layers` when the checkpoint has no head; `save_mtp_head` / `load_saved_mtp_head` for a head saved beside a LoRA adapter. Everything is opt-in; nothing outside `unsloth_zoo/speculative/` changes, and the package imports transformers' Qwen3.5 classes lazily (imports fine on transformers 4.57.6). Companion PR unslothai/unsloth#13719 wires `FastModel.get_mtp_head` and the save paths. ## Supported families | model_type | Example checkpoints | llama.cpp check (tiny random model, our drafts vs `draft-mtp`) | Real weights | |---|---|---|---| | qwen3_5_text / qwen3_5_moe_text | Qwen3.5, Qwen3.6 | earlier: 102/102, 85/85, 50/50 on Qwen3.5-0.8B; generic engine bit-equal to `Qwen35MTPHead` | stock-head top-1 0.728 / 0.617 | | glm4_moe | GLM-4.5 / 4.6, GLM-4.5-Air | 66/66, 66/66, 64/64 | GLM-4.5-Air (4-bit target): 0.827 / 0.622 / 0.483 | | glm4_moe_lite (MLA) | GLM-4.7-Flash | 65/65, 63/63, 62/62 | 0.841 / 0.535 / 0.272; llama.cpp Q8_0 GGUF drafts vs ours: 391/399, 373/391, 320/373 | | glm_moe_dsa | GLM-5.x | 66/66, 64/66, 60/62 (mismatches are near-ties) | not run (744B) | | hy_v3 | Hy3 | 64/64, 64/64, 63/63 | not run (295B) | | nemotron_h | Nemotron-3-Super | 64/65, 63/64, 61/62 (near-ties) | not run (4-bit target does not fit: packed experts stay bf16) | | step3p5 (3 chained heads) | Step-3.5-Flash, Step-3.7-Flash | 64/65, 60/62, 59/60 (near-ties); reversed head order, post-norm feedback and swapped concat each break it | not run (199B) | | qwen3_next | Qwen3-Next-80B-A3B | step 0 32/33; steps 1-2 27/31, 26/27 (swaps within llama's top 3; llama.cpp runs qwen3next speculation one draft per round) | 4-bit target: 0.846 / 0.716 / 0.625 | | deepseek_v3, deepseek_v32, exaone_moe | DeepSeek-V3.x, K-EXAONE | trainable; llama.cpp's converter drops the DeepSeek-V3 head, has no EXAONE MTP graph, and the V3.2 tiny model did not convert | not run | "Real weights" = stock-head teacher-forced top-1 per draft step on the target's own greedy answers under llama.cpp's contract; for every model the contract beat the ablations (other norm side for h, current-token embedding, swapped concat). Tiny checks: random tiny target + random head, written under the family's checkpoint names, converted with `convert_hf_to_gguf.py` (f32), drafted by `llama-server --spec-type draft-mtp`, compared round by round with `NextNHead.draft_greedy` from the same committed prefix (counts = matching drafts at steps 0 / 1 / 2). ## Results Fine-tuned targets (LoRA SFT on python_code_instructions_18k), drafter trained on 3000 answers the fine-tuned model regenerated, scored on 200 held-out prompts (100 for DSpark), greedy. Timing on a Colab A100 40GB with the unslothai/llama.cpp prebuilt `b11541-mix-2500203` (the build Studio ships), arms interleaved on one card (no draft, A, B, B, A, no draft), repeat spread under 1.3%. | Target | Drafter | Draft acceptance | Decode tok/s (median) | vs no draft | |---|---|---|---|---| | Qwen3.5-0.8B (code SFT), MTP | none | - | 233.6 | 1.00x | | | stock head | 0.682 | 288.4 | 1.24x | | | trained head | 0.743 | 307.6 | 1.32x | | Qwen3-4B (code SFT), DSpark | none | - | 116.2 | 1.00x | | | deepseek-ai/dspark_qwen3_4b_block7 | 0.554 | 273.0 | 2.35x | | | trained (warm start, 1 epoch) | 0.637 | 312.5 | 2.69x | - Trained vs stock MTP head: +6.9% decode speed (bootstrap 95% CI +4.6% to +8.7%); acceptance +6.0 points (CI +3.8 to +8.4). - Trained vs reference DSpark drafter: +14.4% (CI +9.9% to +18.3%); acceptance +8.4 points (CI +6.8 to +10.2). - Outputs were identical with every drafter on all prompts (speculation is lossless). - The two GGUFs in each MTP pair differ only in the 15 `blk.24.*` MTP tensors. GLM-4.7-Flash (MoE, MLA, `glm4_moe_lite`), same recipe: LoRA code SFT in bf16, head trained on 3000 regenerated answers (1 epoch, 3 draft steps), 200 held-out prompts, Q8_0 GGUFs from `convert_hf_to_gguf.py`, `llama-server --spec-type draft-mtp --spec-draft-n-max 3`, on one B200 held exclusively (arms interleaved as above, repeat spread under 1.3%; the host was busy, so read the ratios rather than the absolute speeds). | Drafter | Draft acceptance | Decode tok/s (median) | vs no draft | |---|---|---|---| | none | - | 160.1 | 1.00x | | stock head | 0.546 | 205.4 | 1.28x | | trained head | 0.777 | 253.2 | 1.58x | - Trained vs stock: +23.9% decode speed (bootstrap 95% CI +22.2% to +25.7%); acceptance +23.1 points on the aggregate rate (per-prompt mean difference +24.7 points, CI +23.1 to +26.3). - The trained GGUF is the fine-tuned checkpoint with the trained head stitched in (replace mode): it differs from the stock one only in 22 of the 24 `blk.47.*` tensors (the two frozen embedding / lm_head copies are unchanged), checked tensor by tensor. - Both heads gave the same output on all 200 prompts; each matched the no-draft output on 136 of 200, diverging on the same prompts (llama.cpp's batched verification flips near-tied greedy tokens; it is not head dependent). Correctness checks: - Our head's greedy drafts match llama.cpp's actual `draft-mtp` drafts on the same GGUF: 102/102 (step 0), 85/85 (step 1), 50/50 (step 2). - Stock-head teacher-forced top-1 under the llama.cpp alignment vs wrong variants (Qwen3.5-0.8B): 0.728 vs 0.630 (pre-norm h), 0.666 (current-token embedding), 0.001 (concat order swapped). Qwen3.6-35B-A3B MoE: 0.847 / 0.750 for steps 0 / 1. - DSpark port vs DeepSpec's own modeling code in fp32: logits max diff 1.2e-4, argmax agreement 100%, loss equal to 1e-6; a re-saved reference checkpoint converts to a byte-identical GGUF. - Training smokes: Qwen3.5-0.8B bf16 5.3 GB peak; Qwen3.6-27B 4-bit target 27.4 GB (425M-param head); Qwen3.6-35B-A3B 4-bit about 40 GB (845M-param head); DSpark on Qwen3-4B 35 GB. In each the target is bit-unchanged and only the drafter moves. ## Tests `tests/test_speculative_{capture,losses,mtp,stitch,trainer,dspark,nextn}.py`, 98 tests: losses vs closed form and unchunked fp64 gradients, capture vs HF reference hidden states (incl. LoRA), head vs an independent hand-written transcription of llama.cpp's dense and MoE MTP graphs, sentinel alignment, causality, full-sequence vs incremental drafting, stitch byte-identity / atomicity / prefix detection / append, trainer only moving the head, gradient-accumulation equivalence on unequal lengths (fails without the token normalisation), evaluate + resume, DSpark mask leakage / alignment / converter round trip; NextN engine equal to `Qwen35MTPHead`, checkpoint naming round trips for every family, packed expert round trip, training forward equal to incremental drafting (single and chained heads), sliding-window masks, stitch replace + append (owned embedding / lm_head copies written back when the checkpoint lacks the MTP layer), pre-norm families training on the last layer's output. Also run: two-process CPU DDP (weights in sync across ranks) and a tiny MoE checkpoint stitched and converted with llama.cpp's converter (all expert, router and shared-expert MTP tensors present). ## Limits - FP8 checkpoints (DeepSeek-V3.2, MiMo-V2) are not dequantized on load; MiMo-V2, DeepSeek-V4, Qwen4-exp and Gemma 4 assistant drafters are not registered. - Head-serialized embedding / lm_head copies are not refreshed on export when the fine-tune changed the target's embedding or lm_head. - DSpark: dense Qwen3 targets, vanilla Markov head, full draft vocabulary. - llama-server acceptance was measured for Qwen3.5-0.8B and GLM-4.7-Flash; the other families are covered by the tiny llama.cpp draft checks and the real-weight alignment gates above. Fixes unslothai/unsloth#6361
…rt it for llama.cpp and vLLM (unslothai#13806) Lets Unsloth Studio and Unsloth Desktop train a speculative decoding drafter together with a fine-tune, and ships it with merged and GGUF exports so the fine-tuned model decodes faster in llama.cpp and vLLM. Builds on unslothai#13719 (merged) and unslothai/unsloth-zoo#1748 / #1762 (merged). ## What users see Train tab, advanced mode: a new collapsed section "Speculative Decoding Drafter" with one checkbox, "Train a speculative decoding drafter". What it does depends on the selected model: - Model has a native MTP head (Qwen3.5 / 3.6, GLM-4.5 / 4.7, Qwen3-Next, ...): "Retrains this model's MTP head". - Model has no MTP head (Llama, Qwen3, Gemma 4, gpt-oss, ...): "Trains an EAGLE-3 drafter (this model has no MTP head)". - Neither engine can run a drafter for it (Gemma 3, Mistral 3): disabled, with the reason. Expanded: data source (dataset answers, or the model's own answers: slower, closer to what the model generates), number of examples, epochs, learning rate, draft tokens. With the box unticked nothing changes: the training request is byte-identical to today's. After the fine-tune finishes, a "Training drafter" phase trains the drafter against the fine-tuned model (frozen, adapter active). A drafter failure is reported as a warning and the fine-tune is kept; stopping during this phase discards only the drafter. The export page then says "Includes trained drafter (MTP | EAGLE-3)" and shows the `vllm serve` command. ## How it works Backend: - `TrainingStartRequest.drafter` (optional) -> route -> worker config -> `core/training/drafter.py`, run in the worker after the fine-tune is saved: frees the SFT optimizer and data, builds examples (SFT rows with the same prompt masking, or greedy regeneration), then `FastModel.get_mtp_head` + `UnslothMTPTrainer` (native head, saved as `mtp_head.safetensors` beside the adapter) or the zoo EAGLE-3 trainer (saved to `eagle3/`). Writes `drafter.json` (strategy, layers, metrics). Progress has its own step counter and does not touch the fine-tune's loss history. - `GET /api/train/drafter-capability?model_name=...`: native head detected from the checkpoint's tensor index (not the config alone), otherwise EAGLE-3 support for the architecture. - Export: the native head is re-attached when export reloads the adapter and stitched into merged and GGUF outputs (unslothai#13719). EAGLE-3 is copied to `<export>/eagle3` (verifier = the Hub repo on push, else the base model) and converted to `eagle3-<name>-F16.gguf` next to GGUF exports; `drafter.json` carries the `vllm serve ... --speculative-config` command. - Inference: llama-server gets `--model-draft <eagle3 gguf> --spec-type draft-eagle3` when an export's drafter sits beside the GGUF and the binary supports it; a GGUF whose `drafter.json` says its MTP head was trained turns MTP on in auto even under the 3B size floor and the MLA default-off (the user trained it to be used). GGUFs without that file route exactly as before. The managed vLLM engine adds `--speculative-config` when the model folder has a `drafter.json`. - Fix: after an export reload, an outer save wrapper hid the MTP save wrapper, so the head was stitched twice per save. Internal savers now set a context flag the wrapper honours wherever it sits in the chain. Frontend: `drafter-section.tsx`, store / types / defaults / persistence (v23, old state migrates to off) / YAML / payload mapping (sent only when ticked, supported for the selected model, and not CPT / embedding / decision / MLX), `training_drafter` phase label, export banner; strings in all 14 locales. ## Tests - Backend: `test_drafter_training.py`, `test_drafter_launch_flags.py`, the managed engine, admission and phase sync suites: 439 passed. - Frontend: `training-start-payload-drafter.test.ts` (off payload unchanged in every gated case, on payload = off payload plus exactly the drafter block, bounds, persistence migration, YAML round trip) and persistence: 24 passed; `npm run typecheck`, `npm run i18n:check:strict`, `npm run build` pass. Regression A/B (Studio journeys auth / settings / crawl / inference settings / parallel / train_responses_only / export_reload / diffusion train, plus the core regression smoke, `jobs/sft.py`, `jobs/inference_smoke.py`), base vs head on Colab A100 / L4 and Kaggle T4x2: no functional regression (63 steps identical, 10 DOM-only, 1 failing on both sides: `export_reload/export_merged`). The visual diffs that reproduced are the Train form (the new section) and a chat title in a parallel-streams journey whose order depends on which stream finishes first. ## End-to-end results Driven only through Studio's HTTP API on Colab (train with the drafter, merged 16-bit + GGUF Q8_0 export, then serve), 60 held-out prompts, 192 new tokens, greedy, arms interleaved on one GPU, 95% paired bootstrap CIs over prompts. Qwen3.5-2B, native MTP head retrained on 600 of the model's own answers (L4, bf16): | Engine | Arm | Acceptance | Speedup vs no draft | |---|---|---|---| | llama.cpp | stock head | 0.740 | 1.51x [1.48, 1.55] | | llama.cpp | trained head | 0.757 | 1.53x [1.49, 1.57] | | vLLM 0.31.0 | stock head | 0.747 | 1.55x [1.51, 1.59] | | vLLM 0.31.0 | trained head | 0.766 | 1.57x [1.53, 1.61] | Trained vs stock is a tie on this small model (llama.cpp 1.013x [0.996, 1.032], vLLM 1.015x [0.999, 1.031]; an A100 run gave 1.035x [1.018, 1.052]). The default learning rate for the MTP head is 2e-5: at 1e-4 the retrained head drafted worse than stock (acceptance 0.53 vs 0.70). Qwen3-1.7B, new EAGLE-3 drafter from 6,000 dataset rows, 2 epochs (T4, fp16): llama.cpp acceptance 0.449, 1.28x [1.21, 1.35] vs no draft, 60/60 outputs identical; vLLM acceptance 0.463, about 2.2x (the T4 no-draft baseline was noisy). ## Limits - A drafter learns the prompt format it was trained on: trained on Alpaca-formatted rows, it drafts worse on chat-template prompts (the EAGLE-3 drafter above was slower than no draft there, 0.81x), so train it on rows formatted the way the model will be served. - "Model's own answers" regenerates every example (600 prompts took about 35 minutes on an A100). - EAGLE-3 was not run on a bf16 GPU end to end. - The trained-MTP marker lives in `drafter.json` beside the GGUF, not in GGUF metadata; a GGUF downloaded on its own keeps Studio's default MTP policy. - LoRA-only exports keep the MTP head beside the adapter but do not carry the EAGLE-3 folder. - No drafter training on Mac (MLX) yet. ## Screenshots Before (base) on the left, after (this PR) on the right. Train tab, advanced view: the new collapsed "Speculative Decoding Drafter" section under the training hyperparameters.  Qwen3.5-2B (native MTP head): "Retrains this model's MTP head".  Qwen3-1.7B (no MTP head): "Trains an EAGLE-3 drafter (this model has no MTP head)".  Gemma 3 1B: no drafter either engine can run, so the checkbox is disabled with the reason. 
Lets users retrain their model's speculative-decoding drafter after fine-tuning, and makes every export carry the trained one. Needs unslothai/unsloth-zoo#1748 (the
unsloth_zoo.speculativepackage).Why
Models with a native MTP / NextN head (Qwen3.5 / 3.6, GLM-4.5 / 4.7 / 5, Qwen3-Next, Nemotron-3, Step-3.5 / 3.7, Hy3, DeepSeek-V3) drive llama.cpp's
draft-mtpspeculative decoding with it (on by default in Studio for Qwen3.5 / 3.6). transformers drops these tensors on load and Unsloth's merge copies the original shards through, so a fine-tuned export today ships the stock head, which drafts for the base model rather than the fine-tune. Retraining it on the fine-tuned model's own outputs makes decoding faster with identical outputs (numbers below).Usage
UnslothDSparkTrainer/DSparkTrainingArguments/Qwen3DSparkDrafterdo the same for DSpark drafters on Qwen3 targets (the saved drafter converts with llama.cpp and Studio pairs it from adspark/folder).What changes
unsloth/models/speculative.py(new):get_mtp_head(alsoFastModel.get_mtp_head/FastLanguageModel.get_mtp_head) picks the model's MTP family from the zoo registry and loads its head tensors (mtp.*,model.layers.{N}.*, ...) straight from the checkpoint the model came from (or a head saved beside a LoRA adapter) and attaches the head withobject.__setattr__, so it stays out ofmodel.state_dict(), PEFT and the target's optimizer. Plainmodel.save_pretrainedthen also keeps the head. Trainer classes resolve lazily and only need a recent unsloth_zoo when used.unsloth/save.py: when a head is attached, merged 16-bit (replace mode on the original shards), merged 4-bit (head survivesmerge_and_unload), non-PEFT saves (append mode), GGUF (stitched before conversion; the loaded-checkpoint reuse shortcut is skipped), LoRA saves (mtp_head.safetensorsbeside the adapter) and Hub pushes (local temp save, stitch, upload; revision branch created) all write the trained head under the family's own tensor names; the family's layer-count key (mtp_num_hidden_layers,num_nextn_predict_layers) is kept in sync. Only rank 0 writes.variant=with a head attached is refused with a clear error.unsloth/models/loader.py: loading a LoRA folder that hasmtp_head.safetensorsre-attaches it, so a later merge keeps the trained head.No behaviour change without an attached head: every new hook returns before doing anything, nothing new is imported on those paths (about 13 ms added to
import unsloth).Results
Same setup as the zoo PR: LoRA code SFT, drafter trained on 3000 self-regenerated answers, 200 held-out prompts (100 for DSpark), greedy, Colab A100 40GB, unslothai/llama.cpp prebuilt
b11541-mix-2500203, arms interleaved on one card.Trained vs stock: +6.9% (95% CI +4.6% to +8.7%) for Qwen3.5 MTP, +23.9% (CI +22.2% to +25.7%) for GLM-4.7-Flash MTP, +14.4% (CI +9.9% to +18.3%) for DSpark; the Qwen3.5 and DSpark outputs were identical on every prompt; the two GLM heads gave the same output as each other on all 200 prompts.
Supported families and their llama.cpp / real-weight checks are listed in the zoo PR.
Tests
tests/test_save_mtp_head_stitch.py: every save path is wired, head found through PEFT wrappers, no-op without a head, append + config declaration, adapter sidecar, GGUF reuse rule, plainsave_pretrainedkeeps the head, reload hook present, and a GLM-style head (model.layers.{N}.*) appended on a plain save, reloaded identically and then replaced in place, and one save writes the head once. Withtests/test_save_mtp_policy.py: 29 passed; existing save / GGUF suites unchanged.unsloth/Qwen3.5-0.8Bwith a LoRA adapter: merged 16-bit with a head equals a merged save without one in all 473 non-MTP tensors (sha256), and the 15mtp.*tensors equal the trained head.Fixes #6361