Repository navigation
Keep an exported config's MTP declaration in agreement with the weights - #11042
Conversation
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e0ba5f88b5
ℹ️ 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".
| # reads what was really written (tied weights dropped, shards split); | ||
| # a push has no local folder, so there the config is fixed for the | ||
| # duration of the write instead. | ||
| _mtp_tensor_names = list(state_dict.keys()) if state_dict is not None else None |
There was a problem hiding this comment.
Inspect resident weights before guarding Hub pushes
When a non-PEFT model is pushed without an explicit state_dict using a method that does not contain "16bit"—for example, save_method="lora" or "merged_4bit_forced"—this assigns None, so _mtp_config_matching_tensors deliberately does nothing even though model.push_to_hub subsequently serializes the resident state dict. A full-finetuned text-only MTP model whose head was dropped on load will therefore still upload the stale declaration this change is intended to remove; derive the tensor names from the model for this branch as is already done for merged_16bit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 021a179. Reproduced against the real zoo primitives rather than by reading: with a config declaring mtp_num_hidden_layers and a resident state dict carrying no mtp.* tensors, mtp_head_is_present says the head is absent, and the guard fired for the 16bit branch but not for the state_dict is None branch.
16bit (state_dict built) guard fires BEFORE=True AFTER=True
lora / merged_4bit (state_dict None) guard fires BEFORE=False AFTER=True
The push branch now falls back to model.state_dict().keys(), which is the same call the 16bit branch already makes and returns tensor references rather than copies, so it costs no extra memory. It is wrapped so a model that cannot report its own tensors falls back to the previous behaviour instead of failing a save, which is the rule the guard itself follows. merged_4bit_forced is normalised to merged_4bit earlier, so it takes the same path.
Nothing that already stripped correctly changes: when mtp.* really is resident, mtp_head_is_present is true and the declaration is left alone.
5723af9 to
f4104d5
Compare
A full finetune of Qwen3.5 saved with save_pretrained_merged writes 473 tensors, none of them mtp.*, beside a config.json that still declares text_config.mtp_num_hidden_layers = 1. transformers has no MTP module for qwen3_5 and lists ^mtp.* in _keys_to_ignore_on_load_unexpected, so the 15 mtp.* tensors are dropped at load and no export can put them back. The result is a checkpoint that disagrees with itself, which is what a serving runtime trips over. The GGUF converter and the MLX writer already reconciled this key; the safetensors writer did not. All three writers behind save_pretrained_merged now agree, on one shared rule from unsloth_zoo.saving_utils rather than three local copies of it. unsloth_save_model strips the declaration from the config dict it is about to write when the tensors carry no MTP head, unsloth_generic_save repairs the folder it just wrote, and the push path is guarded around the upload since there is no local folder to repair afterwards. The live config is always restored, so an export never changes the model the caller goes on using, and a checkpoint that stores its head as extra layers.N blocks past its declared layer count is left alone. A checkpoint whose weights cannot be read reads as unknown, never as "no MTP head", so an unreadable folder can never license editing the config. Every unsloth_zoo import is guarded: the two packages are released and upgraded independently, so an older unsloth_zoo must leave the save working, and the new tests skip rather than fail against one. Also add a regression test for the exported tokenizer_class. That key is the other half of the report, but it was measured as correct on every save path reachable today, written by transformers itself from the live class name, so there is nothing to repair and this pins the invariant instead. It is the test that would have caught the earlier regression where a wrapper prefix leaked into processor_class, and it covers the Processor case, since for a vision model the object handed to save is a Processor rather than a tokenizer.
516c862 to
2be8bda
Compare
unsloth and unsloth_zoo are installed and upgraded separately, and the import of the shared rule sat inside the same try as the repair itself, so an unsloth updated ahead of its zoo reported the missing name through the failure warning on every merged save, of every model, including ones whose config never declared an MTP head. Catch the ImportError on its own and do nothing, which is what main does, and keep the warning for a real failure.
|
Verification pass over this branch. It found one real problem, fixed in
What else was checked, against the configs Qwen actually publishes rather than only the fixture:
Cross-platform staging CI, rebuilt on this head with the paired zoo branch installed, counts read from each leg's log: ubuntu-latest 24 passed 1 skipped, macos-15 7 passed 18 skipped, windows-latest 4 passed 21 skipped. The macOS and Windows skips are the pre-existing reasons the body already records, so Linux remains the only full gate for the behavioural half. |
Only the 16bit and Qwen3.5 VLM branches build a state_dict, so save_method=lora and merged_4bit reached push_to_hub with None and disarmed the guard, while push_to_hub serialized the resident state dict regardless. A full-finetuned MTP model therefore still pushed the stale declaration.
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 021a1797ff
ℹ️ 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".
| # original afterwards, so the MTP declaration is dropped here rather than by a | ||
| # second pass over the folder. The merged state dict is what gets written, so | ||
| # its keys are the authority on whether an MTP head is present. | ||
| _strip_absent_mtp_declaration(new_config, state_dict.keys()) |
There was a problem hiding this comment.
Restore the MTP declaration when the save fails
When this manual merge path reaches internal_model.save_pretrained or the subsequent Hub upload and that operation raises (for example, because of a full disk or an upload failure), the model and its nested wrappers have already been assigned the scrubbed new_config, while the restoration below is skipped. For an MTP model this newly leaves the caller's live model permanently missing mtp_num_hidden_layers, so a retry or continued use observes a mutated configuration; place the config swap and write in a try/finally, as the new push guard does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 016957d. Correct, and it is this PR that makes it bite: the swap/restore around the write predates the change, but adding _strip_absent_mtp_declaration to the scrub means the config left behind on a failure is now also missing mtp_num_hidden_layers, not just quantization_config.
Both arms are inside the try -- the organization path's save_pretrained plus upload_folder, and the ordinary save_pretrained -- and the restore walks the nested wrappers in the finally, so a full disk or a failed upload hands the caller back the config they started with. Same shape as _mtp_config_matching_tensors, which already did this, and the commit says so.
A structural test asserts the write is inside a try whose finally restores old_config, rather than just that the names appear, so moving the restore back out of the finally fails here.
The scrubbed config is swapped onto the caller's model for the duration of the write and restored only on the success path, so a full disk or a failed upload left the model permanently missing quantization_config and, now that this PR strips it here too, mtp_num_hidden_layers.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d7af91c494
ℹ️ 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".
| else: | ||
| # push_to_hub serialises the resident state dict, so None disarms the guard. | ||
| try: | ||
| _mtp_tensor_names = list(model.state_dict().keys()) |
There was a problem hiding this comment.
Avoid collecting resident weights during local saves
For a local non-PEFT save using save_method="lora" or "merged_4bit_forced" with no supplied state_dict, this branch still calls model.state_dict() even though _mtp_tensor_names is only consumed by the Hub-push guard and the local branch reconciles the written folder instead. save_pretrained then collects the state dict again; on large, offloaded, or distributed models where state_dict() gathers or materializes weights, this duplicates an expensive full-model operation and can exhaust memory or stall collectives. Derive these resident tensor names only inside the push_to_hub branch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. This PR had already merged when the review landed, so the fix is #11159 instead of a commit here.
The names are the push guard's only: a push has no local folder to repair afterwards, while a local save reconciles the folder it just wrote. So for a local lora or merged_4bit_forced save with no caller-supplied state dict, the branch collected model.state_dict() for a list nothing read, and save_pretrained collected it again straight after -- two full materialisations on an offloaded or sharded model, and under FSDP or DeepSpeed a collective the other ranks are not making. The collection moves inside if push_to_hub:, derived exactly as before.
Tested by driving unsloth_generic_save with a counting fake model: a local lora and merged_4bit_forced save never calls state_dict(), a merged_16bit one still does because that dict is what gets written, and a structural check keeps the assignment inside the push branch.
…ts (unslothai#11042) * Keep an exported config's MTP declaration in agreement with the weights A full finetune of Qwen3.5 saved with save_pretrained_merged writes 473 tensors, none of them mtp.*, beside a config.json that still declares text_config.mtp_num_hidden_layers = 1. transformers has no MTP module for qwen3_5 and lists ^mtp.* in _keys_to_ignore_on_load_unexpected, so the 15 mtp.* tensors are dropped at load and no export can put them back. The result is a checkpoint that disagrees with itself, which is what a serving runtime trips over. The GGUF converter and the MLX writer already reconciled this key; the safetensors writer did not. All three writers behind save_pretrained_merged now agree, on one shared rule from unsloth_zoo.saving_utils rather than three local copies of it. unsloth_save_model strips the declaration from the config dict it is about to write when the tensors carry no MTP head, unsloth_generic_save repairs the folder it just wrote, and the push path is guarded around the upload since there is no local folder to repair afterwards. The live config is always restored, so an export never changes the model the caller goes on using, and a checkpoint that stores its head as extra layers.N blocks past its declared layer count is left alone. A checkpoint whose weights cannot be read reads as unknown, never as "no MTP head", so an unreadable folder can never license editing the config. Every unsloth_zoo import is guarded: the two packages are released and upgraded independently, so an older unsloth_zoo must leave the save working, and the new tests skip rather than fail against one. Also add a regression test for the exported tokenizer_class. That key is the other half of the report, but it was measured as correct on every save path reachable today, written by transformers itself from the live class name, so there is nothing to repair and this pins the invariant instead. It is the test that would have caught the earlier regression where a wrapper prefix leaked into processor_class, and it covers the Processor case, since for a vision model the object handed to save is a Processor rather than a tokenizer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the MTP repair quiet on an older unsloth_zoo unsloth and unsloth_zoo are installed and upgraded separately, and the import of the shared rule sat inside the same try as the repair itself, so an unsloth updated ahead of its zoo reported the missing name through the failure warning on every merged save, of every model, including ones whose config never declared an MTP head. Catch the ImportError on its own and do nothing, which is what main does, and keep the warning for a real failure. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Derive the MTP push guard tensor names from the resident model Only the 16bit and Qwen3.5 VLM branches build a state_dict, so save_method=lora and merged_4bit reached push_to_hub with None and disarmed the guard, while push_to_hub serialized the resident state dict regardless. A full-finetuned MTP model therefore still pushed the stale declaration. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Restore the live config when the merged save fails The scrubbed config is swapped onto the caller's model for the duration of the write and restored only on the success path, so a full disk or a failed upload left the model permanently missing quantization_config and, now that this PR strips it here too, mtp_num_hidden_layers. * Reduce comment volume in the GGUF export preflight paths and their tests --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
A full finetune of Qwen3.5 saved with
save_pretrained_mergedproduces a checkpoint that disagrees with itself: 473 tensors, none of themmtp.*, beside aconfig.jsonthat still declarestext_config.mtp_num_hidden_layers = 1. A serving runtime reads the declaration, looks for the multi token prediction head, and does not find it.This makes the exported config agree with the tensors that were actually written, across all three writers behind
save_pretrained_merged, using one shared rule fromunsloth_zoo.saving_utilsrather than three local copies of it. The GGUF converter and the MLX writer already reconciled this key; the safetensors writer did not.Root cause
transformers has no MTP module for
qwen3_5and lists^mtp.*in_keys_to_ignore_on_load_unexpected(transformers/models/qwen3_5/modeling_qwen3_5.py), so the 15mtp.*tensors are dropped at load time and no export can put them back. Plain transformers behaves the same way, so this is upstream behaviour that Unsloth was propagating into the artifact unchanged.Measured on
Qwen/Qwen3.5-0.8B, before and after the identical run:Re-injecting the base checkpoint's
mtp.*weights was considered and rejected.mtp.fcandmtp.pre_fc_norm_*consume backbone hidden states that the finetune has just changed, so a stale head is silently miscalibrated speculative decoding rather than an honest absence. The invariant to enforce is that the config and the weights agree, which is exactly the invariantconvert_to_ggufalready enforces for the GGUF path.Changes
unsloth/save.pygains three private helpers and three wiring points, all built onmtp_head_is_presentandreconcile_mtp_configfromunsloth_zoo.saving_utils:unsloth_save_modelstrips the declaration from the config dict it is about to write, when the tensors being written carry no MTP head.unsloth_generic_saverepairs the folder it just wrote, after the localmodel.save_pretrained, so the decision is made against what really landed on disk rather than against what was intended.push_to_hubbranch is guarded around the upload instead, because there is no local folder to repair afterwards.The live config is always restored on exit, including when the save raises, so an export never changes the model the caller goes on using. The restore path carries pre captured
(holder, key, value)triples and imports nothing, so an exception there can never replace what the save itself did or raised.Two distinctions the repair turns on. A checkpoint whose weights cannot be read reads as unknown, never as "no MTP head", so an unreadable or corrupt folder can never license editing the config. And a head stored as extra
layers.Nblocks past the declared layer count, which is the DeepSeek and GLM spelling declared withnum_nextn_predict_layers, reads as present, so the declaration is not stripped from one of those.Every
unsloth_zooimport is guarded. The two packages are released and upgraded independently, so an olderunsloth_zooleaves the save working exactly as it does today, and the new tests skip rather than fail against one.Two behaviour notes worth stating. After this repair
convert_to_ggufsees a config with nomtp_num_hidden_layers, so_mtp_declaredis False there and--no-mtpis no longer added to the converter command. The end state is the same: with no declaration the converter never looks for the MTP block, and if it infers one anyway_converter_needs_no_mtpstill self heals and retries. An export repaired here therefore arrives at the GGUF and MLX writers already consistent instead of being reconciled in flight. Second, this is deliberately narrower than the MLX writer, which reconciles three spellings and corrects the declared count to the real one. The safetensors path handles themtp_num_hidden_layersspelling and only removes it, never rewrites it, so a checkpoint that declares its head withnum_nextn_predict_layersis left to the writers that already understand that form.merge_and_overwrite_lorais deliberately not modified. It copies the base checkpoint's shards and merges in place, so it keeps themtp.*tensors and its config and weights already agree, and itsconfig.jsonis uploaded before the shards are final, so a post write repair there would not reach the Hub anyway.On
tokenizer_classThe report also names
tokenizer_class. It was measured on six save paths, the plain tokenizer, the plain processor, the Unsloth tokenizer, an Unsloth LoRA save, an Unslothmerged_16bitsave, and the Qwen3.5 full finetune merge, and every one recorded a correct, resolvable value:Qwen2Tokenizerfor the Qwen3.5 merge,GemmaTokenizerelsewhere.PreTrainedTokenizerBase.save_pretrainedwrites it from the live class name, and Unsloth no longer renames tokenizer or processor classes, so there is nothing to repair.Rather than add a repair for a defect that does not reproduce, this adds the regression test that was missing. It pins that an Unsloth save records a
tokenizer_classwhichtokenizer_class_from_nameresolves, and covers the Processor case, since for a vision model the object handed to save is a Processor rather than a tokenizer andtype(obj).__name__is the wrong source. That is the test that would have caught the earlier regression where a wrapper prefix leaked intoprocessor_class, whose read side workarounds are still live inunsloth_zoo/hf_utils.pyandunsloth/models/vision.py. It passes onmain, which is correct for a test pinning a currently true invariant.Compatibility
Run through the version matrix on the cpu lane. Corners named by resolved versions, all cells measured.
The same step against
mainfails as it should, the two new test files being absent. mA is the oldest supported corner and CPU only on this host, since torch 2.6.0's PyPI wheel carries nosm_100kernel.Cross repository, since the two packages ship separately:
unsloth_zooPRtests/saving, the two new files, drift and collection gates, save entrypoint testsunsloth_zoo(main)mainwithmainEither package can be upgraded first. With an older
unsloth_zoo, every helper here short circuits and the net effect is exactly today's behaviour.Studio needs no change. Its export path goes through
save_pretrained_mergedandpush_to_hub_merged(studio/backend/core/export/export.py), so it inherits the repair, and it imports none of the new names. Nothing in the Studio backend or frontend readsmtp_num_hidden_layers. Studio's transformers 5 detection atstudio/backend/utils/transformers_version.pydoes readtokenizer_class, which is one of the reasons the speculative repair for that key was dropped rather than shipped.Tests
unsloth_zoomaintests/test_save_mtp_policy.pytests/test_save_tokenizer_class.pyThree of those tests came from a verification pass. The shared rule is imported from
unsloth_zoo, and that import sat inside the sametryas the repair itself, so anunslothupdated ahead of itsunsloth_zooreported the missing name through the failure warning on every merged save, of every model, including ones whose config never declared an MTP head. TheImportErroris now caught on its own and does nothing, which is whatmaindoes; the warning is kept for a real failure. The new tests stand an older zoo up as a module without those names and assert silence, and they fail on the code as it was.Both are CPU only, need no network, and use the locally cached
unsloth/gemma-3-270m-it. Every path that cannot run skips with a reason, so neither file can pass having asserted nothing.Cross platform, through staging CI on all three runners: Linux 21 passed 1 skipped, which is the full
gate; macOS 7 passed 15 skipped and Windows 4 passed 18 skipped, where the behavioural half skips for
reasons that predate this change. Windows has no
tritonwheel, and on macOS a coldimport unsloth.savehits a circular import that is entirely in existing code (save.py:64tomodels/__init__.py:12tollama.py:106tovision.py:59, which imports back into a partiallyinitialised
unsloth.save). The fixture reports that as one skip with a reason rather than fourteensetup errors; the circular import itself is worth a separate look and is not touched here.
They cover: the declaration stripped when the tensors carry no head and kept when they do; an extra
layers.Nhead recognised as present; a checkpoint within its declared layer count still stripped; an unreadable checkpoint and a corrupt shard index both reading as unknown with the config untouched; the live config restored when the write raises; the guard being re entrant; thepush_to_hubbranch; and five AST tests pinning the wiring, which all fail when run againstmain'sunsloth/save.py.The full end to end check still holds: the fixed export reloads cleanly through
AutoConfigwith no MTP attribute,AutoProcessor, andAutoModelForImageTextToTextmatching all 473 weights with no missing or unexpected keys.Evidence
The before and after measurement above is from an identical
save_pretrained_mergedrun onQwen/Qwen3.5-0.8B, a full finetune, the model named in the report. The plain transformers baseline was measured too, and drops the same 15mtp.*tensors, which is how the cause was attributed upstream rather than to Unsloth's remap.Fixes #7681
What this costs a save
The repair runs once per merged save, after the weights are on disk, and it reads
config.jsonand the exported tensor names. Measured directly, median of 7 repeats:mtp.*weights, so nothing is rewrittenLinear in the tensor count and under 5 ms at a tensor count larger than any real checkpoint, against a merged save that writes gigabytes. A checkpoint that declares no MTP head at all returns before reading anything and leaves the file byte identical.
The export path cost that is worth knowing about lives in the paired zoo PR, unslothai/unsloth-zoo#1236, which adds the converter preflight and the post conversion read-back: those are 0.70 s and about 8.9 s respectively on a 543 MB export, the read-back being
gguf.GGUFReaderparsing the vocabulary, bounded by the tokenizer rather than growing with the model. That PR's body carries the measurements and the reasoning for running it unconditionally. Nothing in this PR is on that path.Note for review
This is the
unslothhalf. The shared rule and thereconcile_mtp_configimplementation are in the pairedunsloth-zooPR, which also carries the GGUF export preflight and verification work for #3581. This PR is safe to merge in either order: every import of a newunsloth_zooname is guarded, and the tests skip rather than fail against a releasedunsloth_zoo.Merge order
unslothai/unsloth-zoo#1236 has to merge and release before this PR's MTP guard does anything on CI.
_mtp_config_matching_tensorsimportsMTP_CONFIG_KEYandmtp_head_is_presentfromunsloth_zoo.saving_utils, and those names exist only on that branch; they are not on zoomainand not in any release. The import is guarded, so an older zoo is a quiet no-op rather than a failure, which is the right behaviour for a user who upgrades one package and not the other. But it does mean Backend CI, which installsunsloth_zoofrom PyPI, exercises the no-op arm until that release lands.Verified against the paired branch rather than assumed, with a config declaring
mtp_num_hidden_layersand a resident state dict carrying nomtp.*tensors: