Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
MTP: keep the trained head when saving a named PEFT adapter (#14912)
Daniel Hane49be2ad69e5
diff --git a/tests/test_save_mtp_head_stitch.py b/tests/test_save_mtp_head_stitch.pyindex 0d54b074179..65b92cf209a 100644--- a/tests/test_save_mtp_head_stitch.py+++ b/tests/test_save_mtp_head_stitch.py@@ -85,7 +85,6 @@ def _head(torch):def _wrapped(torch, head, registered):- """PeftModel -> LoraModel -> base model, with the head on the innermost model."""base = torch.nn.Module()base.config = Noneif registered:@@ -297,7 +296,6 @@ def test_nextn_head_round_trips_through_save_pretrained(save_module, tmp_path):reloaded = get_mtp_head(fresh, source = str(out))assert all(torch.equal(reloaded.mtp_state_dict()[k], v) for k, v in expected.items())- # Saving again over a checkpoint that now carries the head rewrites it in place.report = save_module._stitch_mtp_head(fresh, str(out))assert report["mode"] == "replaced"@@ -495,7 +493,6 @@ def test_mtp_push_keeps_the_datasets_metadata(save_module, monkeypatch):))assert len(calls) == 1 and calls[0][:2] == ("dev", True) and "org/data" in calls[0][2]- # A new repo still gets the hub path's model card, with the caller's tags.assert "unsloth" in calls[0][2] and "my-tag" in calls[0][2] and "org/base" in calls[0][2]@@ -632,3 +629,206 @@ def test_get_mtp_head_reads_the_loaded_commit(tmp_path):assert _loaded_revision(model, "org/m", None) == "abc123"assert _loaded_revision(model, "org/m", "dev") == "dev"assert _loaded_revision(model, str(tmp_path), None) is None++[email protected]("adapter_name", ["default", "task"])+def test_named_peft_adapter_save_keeps_the_head(save_module, tmp_path, adapter_name):+ """PEFT writes a non-default adapter under `<out>/<adapter_name>/`; the head goes beside it."""+ import torch+ from peft import LoraConfig, get_peft_model++ pytest.importorskip("unsloth_zoo.speculative.nextn")+ from unsloth.models.speculative import attach_saved_mtp_head, get_mtp_head++ model = get_peft_model(+ _tiny_glm(tmp_path, torch),+ LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj"]),+ adapter_name = adapter_name,+ )+ head = get_mtp_head(model, random_init = True)+ with torch.no_grad():+ for p in head.parameters():+ p.add_(0.01)+ expected = {k: v.detach().clone() for k, v in head.mtp_state_dict().items()}++ out = tmp_path / "saved"+ model.save_pretrained(str(out))+ folder = out if adapter_name == "default" else out / adapter_name+ assert (folder / "adapter_config.json").is_file()+ assert (folder / "mtp_head.safetensors").is_file()+ assert not list(out.glob("model*.safetensors"))++ reloaded = attach_saved_mtp_head(_tiny_glm(tmp_path, torch), str(folder))+ assert reloaded is not None+ assert all(torch.equal(reloaded.mtp_state_dict()[k], v) for k, v in expected.items())+++def test_every_saved_adapter_folder_gets_the_head(save_module, tmp_path, monkeypatch):+ """A save of several adapters writes the head beside each folder and pushes each one."""+ import torch+ from unsloth.models.speculative import _wrap_save_pretrained+ from unsloth_zoo.speculative.stitch import load_saved_mtp_head++ model = torch.nn.Module()+ object.__setattr__(model, "peft_config", {"default": None, "task": None})++ def transformers_save(+ save_directory,+ push_to_hub = False,+ **kwargs,+ ):+ for name in ("default", "task"):+ folder = Path(save_directory) / ("" if name == "default" else name)+ folder.mkdir(parents = True, exist_ok = True)+ (folder / "adapter_config.json").write_text("{}")++ object.__setattr__(model, "save_pretrained", transformers_save)+ object.__setattr__(model, "_unsloth_mtp_head", _head(torch))+ _wrap_save_pretrained(model)+ uploads = []++ class Api:+ def __init__(self, **kwargs):+ pass++ def upload_folder(self, **kwargs):+ uploads.append(kwargs)++ import huggingface_hub++ monkeypatch.setattr(huggingface_hub, "HfApi", Api)+ model.save_pretrained(str(tmp_path), push_to_hub = True, repo_id = "me/x")+ for folder in (tmp_path, tmp_path / "task"):+ loaded, _ = load_saved_mtp_head(folder)+ assert set(loaded) == {"fc.weight", "norm.weight"}+ assert len(uploads) == 1+ assert sorted(uploads[0]["allow_patterns"]) == [+ "mtp_head.safetensors",+ "task/mtp_head.safetensors",+ ]+++def _two_adapter_model(torch, active):+ """PEFT-shaped model: `selected_adapters` picks which folders a save writes."""+ from unsloth.models.speculative import _wrap_save_pretrained++ model = torch.nn.Module()+ object.__setattr__(model, "peft_config", {"default": None, "task": None})+ object.__setattr__(model, "active_adapter", active)++ def peft_save(+ save_directory,+ safe_serialization = True,+ selected_adapters = None,+ **kwargs,+ ):+ for name in ("default", "task") if selected_adapters is None else selected_adapters:+ folder = Path(save_directory) / ("" if name == "default" else name)+ folder.mkdir(parents = True, exist_ok = True)+ (folder / "adapter_config.json").write_text(json.dumps({"name": name}))++ object.__setattr__(model, "save_pretrained", peft_save)+ object.__setattr__(model, "_unsloth_mtp_head", _head(torch))+ _wrap_save_pretrained(model)+ return model++[email protected]("positional", [False, True])+def test_selected_adapters_save_leaves_other_folders_alone(save_module, tmp_path, positional):+ """`default` saved a moment earlier is not rewritten by a save of `task` only."""+ import torch++ model = _two_adapter_model(torch, active = "task")+ (tmp_path / "adapter_config.json").write_text("{}")+ if positional:+ model.save_pretrained(str(tmp_path), True, ["task"])+ else:+ model.save_pretrained(str(tmp_path), selected_adapters = ["task"])+ assert (tmp_path / "task" / "mtp_head.safetensors").is_file()+ assert not (tmp_path / "mtp_head.safetensors").exists()+++def test_head_is_written_only_beside_the_active_adapter(save_module, tmp_path):+ """The head was trained against the active adapter; an inactive one must not inherit it."""+ import torch++ model = _two_adapter_model(torch, active = "task")+ model.save_pretrained(str(tmp_path))+ assert (tmp_path / "task" / "mtp_head.safetensors").is_file()+ assert not (tmp_path / "mtp_head.safetensors").exists()+ out = tmp_path / "inactive"+ model.save_pretrained(str(out), selected_adapters = ["default"])+ assert (out / "adapter_config.json").is_file()+ assert not list(out.rglob("mtp_head.safetensors"))++[email protected]("adapter_name", ["default", "task"])+def test_transformers_native_adapter_head_goes_to_the_root(+ save_module, tmp_path, monkeypatch, adapter_name+):+ """`PreTrainedModel.add_adapter` saves the active adapter into `<out>/` whatever its name."""+ import torch+ from peft import LoraConfig++ pytest.importorskip("unsloth_zoo.speculative.nextn")+ import unsloth.save as save+ from unsloth.models.speculative import attach_saved_mtp_head, get_mtp_head++ model = _tiny_glm(tmp_path, torch)+ model.add_adapter(+ LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj"]),+ adapter_name = adapter_name,+ )+ model.set_adapter(adapter_name)+ head = get_mtp_head(model, random_init = True)+ with torch.no_grad():+ for p in head.parameters():+ p.add_(0.01)+ expected = {k: v.detach().clone() for k, v in head.mtp_state_dict().items()}++ out = tmp_path / "saved"+ monkeypatch.setattr(+ save, "_stitch_mtp_head", lambda *a, **k: pytest.fail("stitched an adapter save")+ )+ model.save_pretrained(str(out))+ assert (out / "adapter_config.json").is_file()+ assert (out / "mtp_head.safetensors").is_file()+ assert not (out / adapter_name).exists()++ reloaded = attach_saved_mtp_head(_tiny_glm(tmp_path, torch), str(out))+ assert reloaded is not None+ assert all(torch.equal(reloaded.mtp_state_dict()[k], v) for k, v in expected.items())+++def test_an_empty_adapter_selection_saves_no_head(save_module, tmp_path, monkeypatch):+ """`selected_adapters = []` saves nothing: no head, no `default` fallback, no checkpoint stitch."""+ import torch+ import unsloth.save as save++ model = _two_adapter_model(torch, active = "default")+ # Fresh `default` adapter config from a save a moment earlier, not part of this one.+ (tmp_path / "adapter_config.json").write_text("{}")+ monkeypatch.setattr(+ save, "_stitch_mtp_head", lambda *a, **k: pytest.fail("stitched an adapter save")+ )+ model.save_pretrained(str(tmp_path), selected_adapters = [])+ assert not list(tmp_path.rglob("mtp_head.safetensors"))+ assert not (tmp_path / "task").exists()+++def test_a_combined_adapter_head_is_not_split_into_sidecars(save_module, tmp_path, capsys):+ """Trained with several adapters active at once, the head belongs to none of them alone."""+ import torch++ model = _two_adapter_model(torch, active = ["default", "task"])+ # A head left in the folder by an earlier single-adapter save must not survive either.+ (tmp_path / "task").mkdir()+ (tmp_path / "task" / "mtp_head.safetensors").write_bytes(b"stale")+ model.save_pretrained(str(tmp_path))+ assert (tmp_path / "task" / "adapter_config.json").is_file()+ assert not list(tmp_path.rglob("mtp_head.safetensors"))+ assert "active together" in capsys.readouterr().out+ object.__setattr__(model, "active_adapter", "task")+ model.save_pretrained(str(tmp_path / "single"))+ assert (tmp_path / "single" / "task" / "mtp_head.safetensors").is_file()+ assert not (tmp_path / "single" / "mtp_head.safetensors").exists()diff --git a/unsloth/models/speculative.py b/unsloth/models/speculative.pyindex c1cc1d66c2d..5c01d91e876 100644--- a/unsloth/models/speculative.py+++ b/unsloth/models/speculative.py@@ -11,15 +11,8 @@# You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <https://www.gnu.org/licenses/>.-"""Fine-tune a model's native MTP head so its speculative drafts match the fine-tuned model.+"""Train a model's native MTP head so merged / GGUF exports carry a head matching the fine-tune."""-transformers drops `mtp.*` on load, and the merged export copies the stock head through-unchanged, so after fine-tuning the head drafts for the old model. `get_mtp_head` loads the-head from the checkpoint and attaches it; `UnslothMTPTrainer` trains it against the frozen-model; every merged / GGUF save then writes the trained head instead of the stock one.-"""--# The trainer names resolve lazily through __getattr__ (they need a recent unsloth_zoo).__all__ = ["get_mtp_head", "attach_saved_mtp_head"]import functools@@ -41,7 +34,6 @@ def _zoo_speculative():def _checkpoint_source(model):- """The repo id / folder the weights came from, looked up through PEFT wrappers."""holders, seen, stack = [], set(), [model]while stack:holder = stack.pop()@@ -55,8 +47,7 @@ def _checkpoint_source(model):)if child is not None:stack.append(child)- # ModelScope loads keep the repo id in the config and the downloaded weights on the inner- # model, under any PEFT wrapper: the snapshot wins over every holder's config.+ # ModelScope: the local snapshot wins over every holder's config repo id.for holder in holders:snapshot = holder.__dict__.get("_unsloth_modelscope_snapshot")if isinstance(snapshot, str) and os.path.isdir(snapshot):@@ -69,7 +60,6 @@ def _checkpoint_source(model):def _loaded_revision(model, source, revision):- """The commit the weights were loaded from, so a Hub lookup reads that head, not the default branch's."""if revision is not None or not isinstance(source, str) or os.path.isdir(source):return revisionreturn getattr(getattr(model, "config", None), "_commit_hash", None)@@ -84,13 +74,8 @@ def get_mtp_head():"""Load the model's native MTP head, attach it to `model`, and return it.- source: repo id or folder holding the original `mtp.*` tensors. Defaults to the- checkpoint the model was loaded from; pass the original repo when that checkpoint- was re-saved without its head.- random_init: start from random weights instead (for checkpoints without a head).- dtype: head parameter dtype, float32 by default (the head is small; the target stays as loaded).- Without `source` / `random_init`, a head already attached (e.g. re-attached from beside a- reloaded adapter) is returned as is.+ source: repo id / folder with the `mtp.*` tensors (default: the loaded checkpoint).+ random_init: random weights, for checkpoints without a head. dtype: default float32."""import torch@@ -117,7 +102,6 @@ def get_mtp_head({"prefix": "mtp." if family == "qwen3_5" else "", "num_layers": 1, "source": source},)elif isinstance(source, str) and os.path.isfile(os.path.join(source, "mtp_head.safetensors")):- # A head trained earlier and saved beside a LoRA adapter.from unsloth_zoo.speculative.stitch import load_saved_mtp_headstate_dict, info = load_saved_mtp_head(source)else:@@ -132,7 +116,6 @@ def get_mtp_head(device = parts["embed_tokens"].weight.deviceextra = {}if family != "qwen3_5":- # Head-serialized embedding / lm_head copies equal to the target's are not held twice.extra = dict(target_embed = parts["embed_tokens"].weight,target_lm_head = parts["lm_head"].weight,@@ -158,18 +141,86 @@ def get_mtp_head(return head-def _takes_push_to_hub(fn):- # Unsloth's loaders wrap save_pretrained as (self, *args, **kwargs); read the wrapped one.+def _inner_save_fn(fn):if getattr(fn, "__name__", "") == "unsloth_model_save_pretrained":fn = getattr(getattr(fn, "__self__", None), "original_model_save_pretrained", fn)+ return fn+++def _takes_push_to_hub(fn):+ try:+ return "push_to_hub" in inspect.signature(_inner_save_fn(fn)).parameters+ except (TypeError, ValueError):+ return False+++def _selected_adapters(fn, save_directory, args, kwargs):try:- return "push_to_hub" in inspect.signature(fn).parameters+ bound = inspect.signature(_inner_save_fn(fn)).bind_partial(save_directory, *args, **kwargs)except (TypeError, ValueError):+ return kwargs.get("selected_adapters")+ return bound.arguments.get("selected_adapters")+++def _active_adapters(model):+ try:+ names = model.active_adapters+ names = names() if callable(names) else names+ except Exception:+ names = None+ if not names:+ names = getattr(model, "active_adapter", None)+ if isinstance(names, str):+ names = [names]+ return set(names) if names else None+++def _is_transformers_native_peft(model):+ if not getattr(model, "_hf_peft_config_loaded", False):return False+ try:+ from peft import PeftModel+ except Exception:+ return True+ return not isinstance(model, PeftModel)+++def _fresh_adapter_dirs(+ model,+ save_directory,+ started,+ selected = None,+):+ """(name, folder) adapters this save wrote. PEFT: `default` in "", others in `<name>/`;+ transformers' `add_adapter`: only the active adapter, in ""."""+ config = getattr(model, "peft_config", None)+ if _is_transformers_native_peft(model):+ active = _active_adapters(model) or {"default"}+ adapter_config = os.path.join(save_directory, "adapter_config.json")+ if os.path.isfile(adapter_config) and os.path.getmtime(adapter_config) >= started - 1:+ return [(name, "") for name in sorted(active)]+ return []+ names = list(selected) if selected is not None else list(config or {})+ if not names:+ names = ["default"]+ out = []+ for name in names:+ folder = "" if name == "default" else name+ adapter_config = os.path.join(save_directory, folder, "adapter_config.json")+ if os.path.isfile(adapter_config) and os.path.getmtime(adapter_config) >= started - 1:+ out.append((name, folder))+ return out+++def _drop_stale_head(folder):+ from ..save import _is_main_rank++ stale = os.path.join(folder, "mtp_head.safetensors")+ if _is_main_rank() and os.path.isfile(stale):+ os.remove(stale)def _wrap_save_pretrained(model):- """Plain `save_pretrained` keeps the trained head too: beside a LoRA adapter, else in the checkpoint."""original = model.save_pretrainedif getattr(original, "_unsloth_saves_mtp_head", False):return@@ -189,11 +240,9 @@ def _wrap_save_pretrained(model):and kwargs.get("safe_serialization", True) is Falseand not hasattr(model, "peft_config")):- # The head is stitched into safetensors checkpoints only; refuse before writing.raise ValueError("Unsloth: a model with a trained MTP head saves as safetensors; drop `safe_serialization = False`.")- # 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)if not internal:_refuse_mtp_variant(model, kwargs.get("variant"))@@ -207,14 +256,29 @@ def _wrap_save_pretrained(model):result = original(save_directory, *args, **kwargs)if internal or not os.path.isdir(save_directory):return result- adapter_config = os.path.join(save_directory, "adapter_config.json")- # Written by this save, not left over from an adapter saved here before.- if os.path.isfile(adapter_config) and os.path.getmtime(adapter_config) >= started - 1:- files = (- ["mtp_head.safetensors"]- if _save_mtp_head_beside_adapter(model, save_directory)- else []- )+ selected = _selected_adapters(original, save_directory, args, kwargs)+ if selected is not None and not list(selected):+ return result+ adapter_dirs = _fresh_adapter_dirs(model, save_directory, started, selected)+ if adapter_dirs:+ files = []+ active = _active_adapters(model) if getattr(model, "peft_config", None) else None+ combined = active is not None and len(active) > 1+ if combined:+ print(+ f"Unsloth: adapters {sorted(active)} are active together, so the trained MTP head "+ "belongs to their combination and is not saved beside any single adapter."+ )+ for name, folder in adapter_dirs:+ if combined or (active is not None and name not in active):+ _drop_stale_head(os.path.join(save_directory, folder))+ continue+ if _save_mtp_head_beside_adapter(model, os.path.join(save_directory, folder)):+ files.append(+ "/".join(+ filter(None, (folder.replace(os.sep, "/"), "mtp_head.safetensors"))+ )+ )else:report = _stitch_mtp_head(model, save_directory)files = list(report["files_touched"]) if report else []@@ -235,7 +299,6 @@ def _wrap_save_pretrained(model):def attach_saved_mtp_head(model, directory):- """Re-attach a head saved beside an adapter folder; None when the folder has none."""if not isinstance(directory, str) or not os.path.isfile(os.path.join(directory, "mtp_head.safetensors")):