Repository navigation
Route save_method="lora" to the adapter save instead of the merge - #11067
Conversation
save_pretrained_merged(save_method="lora") and push_to_hub_merged(save_method="lora")
are documented as "save the LoRA adapters with no merging", and both did the opposite.
patch_saving_functions binds the generic entry points on every model, so these calls
land in unsloth_generic_save, which sends everything that is not a full fine-tune to
merge_and_overwrite_lora. That function has no "lora" branch, so the value matched
nothing and fell through to a plain 16bit merge: asking for an adapter produced a
full-size checkpoint with no adapter_config.json, measured at 2.47 GB for a 1B base.
unsloth_save_model has always had the correct adapter branch; it was simply unreachable
from these two entry points. Route back to it, and forward the canonical spelling,
since unsloth_save_model normalises with .lower().replace(" ", "_") and then rejects
anything that is not exactly "lora".
Also stop safe_serialization = None from writing a pickle. Unsloth's own warning and the
troubleshooting docs tell a caller to pass None to force safetensors, but None is falsy
to peft and to transformers, so forwarding it verbatim wrote adapter_model.bin, the exact
file the advice exists to avoid. Normalise it at every save entry point, including
model.save_pretrained, which was the one call that was not wrapped. True and False are
unchanged, so an explicit False still writes a pickle.
Finally, drop push_to_hub keywords the installed transformers cannot take. transformers 5
rewrote PushToHubMixin.push_to_hub and removed use_temp_dir and safe_serialization from
it, so an adapter push raised TypeError. Probed from the signature rather than gated on a
version, and a dropped keyword is reported only when honouring it would have changed the
upload.
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. |
…reter unsloth_save_model does `from peft import PeftModelForCausalLM` inside its body, for one isinstance check that every stand-in model in this file answers False to. Stubbing it, the way every other dependency in this file is already stubbed, keeps the whole file runnable with no third-party package installed, which is what lets it gate runners that ship no peft.
save_pretrained_merged builds a loadable SentenceTransformer directory, and an adapter-only save has no base weights to build one from. The modules branch of the wrapper forwarded save_method straight through: self.save_pretrained writes the scaffolding and, for a PEFT auto_model, an adapter; the wrapper then deletes that adapter and hands the transformer module to save_pretrained_merged, which for this method writes the adapter back and nothing else. The directory ends up with modules.json and adapter_config.json but no config.json and no weights, SentenceTransformer cannot load it, and _push_to_hub_merged uploads exactly that directory. Until the previous commit routed it, "lora" reached merge_and_overwrite_lora, matched no branch there and fell through to a plain 16-bit merge, so this path happened to write something loadable. That accident is what the routing change removes. Both sibling branches in this file already refuse the method for this reason, one of them saying so in as many words; this makes the third agree, and the error names the two calls that do what the caller wanted. The predicate is imported from save.py rather than spelled again, so the two files cannot drift on which spellings are adapter saves. Tests pin the guard and the shared predicate, and both fail on the previous commit. Failure sets on tests/saving are identical on the merge base and here: the ten test_prewarm_base_model_hub_cache failures are pre-existing and offline related, red on both sides.
|
@codex security review |
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
|
Confirmed on main that save_method = "lora" falls through unsloth_generic_save into the merge and writes a full checkpoint with no adapter_config.json, and that safe_serialization = None still produces a .bin, so this covers #1792 as well. Will get this reviewed. |
1 similar comment
|
Confirmed on main that save_method = "lora" falls through unsloth_generic_save into the merge and writes a full checkpoint with no adapter_config.json, and that safe_serialization = None still produces a .bin, so this covers #1792 as well. Will get this reviewed. |
One conflict, in unsloth/models/sentence_transformer.py. This branch added _is_adapter_save_method to the module-scope `from ..save import (...)` block, while main replaced that block entirely with deferred shims because a module-scope bind out of unsloth.save closes an import cycle (tests/test_cold_import_order.py). Resolved by taking main's deferred shims whole and importing _is_adapter_save_method at its single call site instead, so the shared definition of what save_method = "lora" means is still used without reopening the cycle.
…tted (#11207) #11025, #10533 and #11067 each landed today with a blank line the ruff-format-with-kwargs hook removes or adds, so `pre-commit run --all-files` is red on main. Every open PR inherits that: pre-commit.ci evaluates the PR merged with main, finds files to rewrite that the PR never touched, and pushes them onto the PR branch, which is how unrelated files end up in a diff. On a branch too far behind main to apply, it fails outright instead. Output of the repo's own hook, with the pinned ruff 0.6.9. Blank lines only. Co-authored-by: danielhanchen <[email protected]>
* Repair the three checks that went red on main today All three reproduce on a clean origin/main (1d5210d) and none needs a product behaviour change, but they do not share a cause, so each is attributed here. install.ps1, studio/setup.ps1: unslothai#10533 added a comment naming an antivirus vendor to Get-SecuritySoftwareNote. The ban on vendor names in shipped scripts landed two days earlier in unslothai#10978, and it is not a style rule: PowerShell hands the entire top-level script block to the scanner at compile time, so comments are classifier input, and VirusTotal's analysis of install.ps1 quoted one of our own comments back as grounds for suspicion. The knowledge is moved rather than deleted, into AV_SHAPES_RECORD, which is where the guard's failure message says it belongs and which now records what each suite calls its protected-folders feature. The function never hard-coded a product name; it reads what SecurityCenter2 registered, and that is now said where the list used to be. tests/test_apply_qkv_fallback.py, tests/test_lora_dropout_patch_summary.py: unslothai#11038 added two skip guards reading torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py patches True process-wide and never puts back. A skipif is evaluated at import, so either file sharing a session with tests/version_compat or tests/vllm_compat un-skips on a CPU-only box and dies inside torch. They go through tests/_shared/real_accelerator.py instead, which records the answer before any spoof can run. test_apply_qkv_fallback_end_to_end allocates on "cuda" by name, so it takes has_real_cuda rather than the broad probe, which is also true on an XPU-only or Ascend NPU-only host. tests/python/test_docker_hub_readme.py: here the test was wrong, not the README. It took the first "#### Docker" heading and read to the next "####". The README grew a second Docker heading above the one carrying the run command, so the pins read a one-line pointer that was never meant to hold a docker run. It now picks the section by content and requires exactly one section to carry a run command, in both directions: zero is the regression it was written for, and more than one means two places tell the user how to start the image while only one is pinned. The stale-token check widened from that one section to every Docker section. * Let the save-signature probe resolve the import unslothai#11067 deferred Fourth check red on main today, in the (CPU, rest) shard: five failures in tests/test_st_save_merged_signature.py, all KeyError: "'__name__' not in globals". unslothai#11067 put `from ..save import _is_adapter_save_method` inside _save_pretrained_merged, deferred on purpose because a module-scope bind out of unsloth.save closes an import cycle. This file reads the two closures out of the source and execs them so the assertions run without importing unsloth, and a bare globals dict has no __name__ or __package__ for a relative import to resolve against, so every test that calls the body died on the import rather than on what it was checking. Satisfying it by importing unsloth would give up what the file is for, so the harness now stands up a package of its own holding the REAL helper, pulled from unsloth/save.py by source the way _normalize_save_method already is. The import executes and binds the shipped function, so its spelling rules still reach these tests; neutering that function fails three of them, which is how I checked the resolution is not cosmetic. That unmasked a second mismatch the import error was hiding. test_the_forwarding_path_still_accepts_lora asserted that "lora" is accepted when modules.json is present. unslothai#11067 deliberately retired that premise: save_pretrained_merged writes a loadable SentenceTransformer and an adapter-only save has no base weights for one, where previously "lora" matched no branch in merge_and_overwrite_lora and fell through to a 16bit merge that happened to write something loadable for a request that asked for adapters. Taking the product as correct, the test now pins the new refusal. The invariant it was really protecting survives and is what is checked: the no_modules refusal must not leak into the branch that has modules.json. Both paths raise now, so a bare pytest.raises would no longer notice one borrowing the other's reason; the messages are pinned apart, and a second test holds the pair distinct, which neither can see on its own. * Drop the torch import the skip-guard fix left unused Source lint caught it: tests/test_lora_dropout_patch_summary.py imported torch only for the torch.cuda.is_available() in the guard this PR replaced, so the import was left bound and unused. The sibling file still uses torch eleven times and keeps its import. * Let the rope carry drift tests run on a transformers that has no rope_parameters Fifth check red on main, in Core (HF=4.57.6 + TRL<1). Both tests from unslothai#11192 assume transformers 5's config.rope_parameters and fail on the 4.x job: test_rope_carry_keeps_every_nested_base_on_every_real_config AssertionError: no config with a nested rope dict was found to check test_rope_carry_leaves_the_zoo_gemma_local_base_alone_on_a_real_config AttributeError: 'Gemma2Config' object has no attribute 'rope_parameters' Both reproduce locally on transformers 4.57.6, the same pin that job resolves. The second is a one word fix. It already treats rope_parameters as optional, via an isinstance check, but read it with attribute access, and 4.x raises rather than returning None, so the tolerance was unreachable. getattr with a default. The first swept for nested rope dicts and asserted it found at least one. On 4.x there is no rope_parameters at all, so the sweep is empty and the assert fires. The two cases are now told apart: no rope_parameters anywhere is 4.x, where this carry does not exist and there is nothing to damage, and skips with that reason; the attribute present but no nested config is still drift and still fails. Collapsing them would either red the 4.x job forever or silently stop testing 5.x. Checked in both directions rather than assumed. On 4.57.6 the skip fires and the Gemma test passes. On 5.17.0 the skip does not fire and the sweep finds 16 nested configs, including the four the docstring names: deepseek_v4, laguna, mellum and zaya. Also stopped the sweep being ended by an unrelated optional dependency. CONFIG_MAPPING is lazy, so .items() imports every config module to hand back the classes, and one model whose module needs something missing takes the whole sweep down before the loop body runs. Seen with transformers.models.gemma3n, which imports timm.data.ImageNetInfo and raises on a timm that does not export it. Iterating keys and resolving inside the existing try skips that model, which is right: a config that cannot be built here cannot be the one that regressed. * Stop one test's account fence deciding another test's assertions tests/multi_account/test_routing_invariance.py::test_owner_routing_facts_and_shared_queue failed in Repo tests (CPU, rest) on assert active_generations._FENCED == set() carrying an account id it never created. It passed when run alone, passed on some pull requests and failed on others, which is the shape that eventually gets a real test deleted for being flaky. state.active_generations keeps _ACTIVE and _FENCED on the module, so they are process-global and outlive the test that wrote them. Retiring or deactivating an account fences it, and staying fenced is the CORRECT end state for those tests, so none of them is at fault. What was missing is isolation, the same way a tmp dir is isolated rather than every test being asked to clean up after itself. Measured rather than guessed: a report-only probe over the backend suite names 15 leakers, in test_job_accounts.py, test_account_storage.py, test_account_integration_wiring.py and test_account_retired_workspace_recreated.py. Whichever of them landed in an xdist worker ahead of the routing test decided its assertion. So the reset goes in conftest as an autouse fixture, before and after each test, using the reset_for_tests() the module already ships for exactly this. Before AND after: clearing only on the way in leaves the last test of a worker holding a fence, and clearing only on the way out trusts every other plugin to have left it alone. The files that already reset around themselves keep doing so; resetting twice costs nothing and the local call documents the intent at its own site. Reproduced before fixing, and confirmed by differential. Running the four leaker files together with the routing test: pristine main 3 failed, incl. test_owner_routing_facts_and_shared_queue with this fix 2 failed, that one gone The remaining two are an unrelated rag_db pair that fails identically on main in this environment. test_generation_state_isolation.py guards the repair. The structural check reads conftest rather than exercising ordering, because observing a leak functionally would require assuming test ORDER and this suite runs under pytest-randomly, where a test may not assume it. Dropping autouse from the fixture fails that check, which is how I confirmed it is not decorative.
…slothai#11067) * Route save_method="lora" to the adapter save instead of the merge save_pretrained_merged(save_method="lora") and push_to_hub_merged(save_method="lora") are documented as "save the LoRA adapters with no merging", and both did the opposite. patch_saving_functions binds the generic entry points on every model, so these calls land in unsloth_generic_save, which sends everything that is not a full fine-tune to merge_and_overwrite_lora. That function has no "lora" branch, so the value matched nothing and fell through to a plain 16bit merge: asking for an adapter produced a full-size checkpoint with no adapter_config.json, measured at 2.47 GB for a 1B base. unsloth_save_model has always had the correct adapter branch; it was simply unreachable from these two entry points. Route back to it, and forward the canonical spelling, since unsloth_save_model normalises with .lower().replace(" ", "_") and then rejects anything that is not exactly "lora". Also stop safe_serialization = None from writing a pickle. Unsloth's own warning and the troubleshooting docs tell a caller to pass None to force safetensors, but None is falsy to peft and to transformers, so forwarding it verbatim wrote adapter_model.bin, the exact file the advice exists to avoid. Normalise it at every save entry point, including model.save_pretrained, which was the one call that was not wrapped. True and False are unchanged, so an explicit False still writes a pickle. Finally, drop push_to_hub keywords the installed transformers cannot take. transformers 5 rewrote PushToHubMixin.push_to_hub and removed use_temp_dir and safe_serialization from it, so an adapter push raised TypeError. Probed from the signature rather than gated on a version, and a dropped keyword is reported only when honouring it would have changed the upload. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Stub peft in the adapter save tests so the file runs on a bare interpreter unsloth_save_model does `from peft import PeftModelForCausalLM` inside its body, for one isinstance check that every stand-in model in this file answers False to. Stubbing it, the way every other dependency in this file is already stubbed, keeps the whole file runnable with no third-party package installed, which is what lets it gate runners that ship no peft. * Refuse the adapter save method on the SentenceTransformer merge save_pretrained_merged builds a loadable SentenceTransformer directory, and an adapter-only save has no base weights to build one from. The modules branch of the wrapper forwarded save_method straight through: self.save_pretrained writes the scaffolding and, for a PEFT auto_model, an adapter; the wrapper then deletes that adapter and hands the transformer module to save_pretrained_merged, which for this method writes the adapter back and nothing else. The directory ends up with modules.json and adapter_config.json but no config.json and no weights, SentenceTransformer cannot load it, and _push_to_hub_merged uploads exactly that directory. Until the previous commit routed it, "lora" reached merge_and_overwrite_lora, matched no branch there and fell through to a plain 16-bit merge, so this path happened to write something loadable. That accident is what the routing change removes. Both sibling branches in this file already refuse the method for this reason, one of them saying so in as many words; this makes the third agree, and the error names the two calls that do what the caller wanted. The predicate is imported from save.py rather than spelled again, so the two files cannot drift on which spellings are adapter saves. Tests pin the guard and the shared predicate, and both fail on the previous commit. Failure sets on tests/saving are identical on the merge base and here: the ten test_prewarm_base_model_hub_cache failures are pre-existing and offline related, red on both sides. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Qualify what a save_method=lora directory contains when a tokenizer is passed * Strip a save_method before folding spaces, and name the pickle adapter filename * Describe None as the safetensors request that survives the low-CPU fallback * Normalize a positional safe_serialization against the original signature * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Shorten the save routing comments --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…tted (unslothai#11207) unslothai#11025, unslothai#10533 and unslothai#11067 each landed today with a blank line the ruff-format-with-kwargs hook removes or adds, so `pre-commit run --all-files` is red on main. Every open PR inherits that: pre-commit.ci evaluates the PR merged with main, finds files to rewrite that the PR never touched, and pushes them onto the PR branch, which is how unrelated files end up in a diff. On a branch too far behind main to apply, it fails outright instead. Output of the repo's own hook, with the pinned ruff 0.6.9. Blank lines only. Co-authored-by: danielhanchen <[email protected]>
* Repair the three checks that went red on main today All three reproduce on a clean origin/main (1d5210d) and none needs a product behaviour change, but they do not share a cause, so each is attributed here. install.ps1, studio/setup.ps1: unslothai#10533 added a comment naming an antivirus vendor to Get-SecuritySoftwareNote. The ban on vendor names in shipped scripts landed two days earlier in unslothai#10978, and it is not a style rule: PowerShell hands the entire top-level script block to the scanner at compile time, so comments are classifier input, and VirusTotal's analysis of install.ps1 quoted one of our own comments back as grounds for suspicion. The knowledge is moved rather than deleted, into AV_SHAPES_RECORD, which is where the guard's failure message says it belongs and which now records what each suite calls its protected-folders feature. The function never hard-coded a product name; it reads what SecurityCenter2 registered, and that is now said where the list used to be. tests/test_apply_qkv_fallback.py, tests/test_lora_dropout_patch_summary.py: unslothai#11038 added two skip guards reading torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py patches True process-wide and never puts back. A skipif is evaluated at import, so either file sharing a session with tests/version_compat or tests/vllm_compat un-skips on a CPU-only box and dies inside torch. They go through tests/_shared/real_accelerator.py instead, which records the answer before any spoof can run. test_apply_qkv_fallback_end_to_end allocates on "cuda" by name, so it takes has_real_cuda rather than the broad probe, which is also true on an XPU-only or Ascend NPU-only host. tests/python/test_docker_hub_readme.py: here the test was wrong, not the README. It took the first "#### Docker" heading and read to the next "####". The README grew a second Docker heading above the one carrying the run command, so the pins read a one-line pointer that was never meant to hold a docker run. It now picks the section by content and requires exactly one section to carry a run command, in both directions: zero is the regression it was written for, and more than one means two places tell the user how to start the image while only one is pinned. The stale-token check widened from that one section to every Docker section. * Let the save-signature probe resolve the import unslothai#11067 deferred Fourth check red on main today, in the (CPU, rest) shard: five failures in tests/test_st_save_merged_signature.py, all KeyError: "'__name__' not in globals". unslothai#11067 put `from ..save import _is_adapter_save_method` inside _save_pretrained_merged, deferred on purpose because a module-scope bind out of unsloth.save closes an import cycle. This file reads the two closures out of the source and execs them so the assertions run without importing unsloth, and a bare globals dict has no __name__ or __package__ for a relative import to resolve against, so every test that calls the body died on the import rather than on what it was checking. Satisfying it by importing unsloth would give up what the file is for, so the harness now stands up a package of its own holding the REAL helper, pulled from unsloth/save.py by source the way _normalize_save_method already is. The import executes and binds the shipped function, so its spelling rules still reach these tests; neutering that function fails three of them, which is how I checked the resolution is not cosmetic. That unmasked a second mismatch the import error was hiding. test_the_forwarding_path_still_accepts_lora asserted that "lora" is accepted when modules.json is present. unslothai#11067 deliberately retired that premise: save_pretrained_merged writes a loadable SentenceTransformer and an adapter-only save has no base weights for one, where previously "lora" matched no branch in merge_and_overwrite_lora and fell through to a 16bit merge that happened to write something loadable for a request that asked for adapters. Taking the product as correct, the test now pins the new refusal. The invariant it was really protecting survives and is what is checked: the no_modules refusal must not leak into the branch that has modules.json. Both paths raise now, so a bare pytest.raises would no longer notice one borrowing the other's reason; the messages are pinned apart, and a second test holds the pair distinct, which neither can see on its own. * Drop the torch import the skip-guard fix left unused Source lint caught it: tests/test_lora_dropout_patch_summary.py imported torch only for the torch.cuda.is_available() in the guard this PR replaced, so the import was left bound and unused. The sibling file still uses torch eleven times and keeps its import. * Let the rope carry drift tests run on a transformers that has no rope_parameters Fifth check red on main, in Core (HF=4.57.6 + TRL<1). Both tests from unslothai#11192 assume transformers 5's config.rope_parameters and fail on the 4.x job: test_rope_carry_keeps_every_nested_base_on_every_real_config AssertionError: no config with a nested rope dict was found to check test_rope_carry_leaves_the_zoo_gemma_local_base_alone_on_a_real_config AttributeError: 'Gemma2Config' object has no attribute 'rope_parameters' Both reproduce locally on transformers 4.57.6, the same pin that job resolves. The second is a one word fix. It already treats rope_parameters as optional, via an isinstance check, but read it with attribute access, and 4.x raises rather than returning None, so the tolerance was unreachable. getattr with a default. The first swept for nested rope dicts and asserted it found at least one. On 4.x there is no rope_parameters at all, so the sweep is empty and the assert fires. The two cases are now told apart: no rope_parameters anywhere is 4.x, where this carry does not exist and there is nothing to damage, and skips with that reason; the attribute present but no nested config is still drift and still fails. Collapsing them would either red the 4.x job forever or silently stop testing 5.x. Checked in both directions rather than assumed. On 4.57.6 the skip fires and the Gemma test passes. On 5.17.0 the skip does not fire and the sweep finds 16 nested configs, including the four the docstring names: deepseek_v4, laguna, mellum and zaya. Also stopped the sweep being ended by an unrelated optional dependency. CONFIG_MAPPING is lazy, so .items() imports every config module to hand back the classes, and one model whose module needs something missing takes the whole sweep down before the loop body runs. Seen with transformers.models.gemma3n, which imports timm.data.ImageNetInfo and raises on a timm that does not export it. Iterating keys and resolving inside the existing try skips that model, which is right: a config that cannot be built here cannot be the one that regressed. * Stop one test's account fence deciding another test's assertions tests/multi_account/test_routing_invariance.py::test_owner_routing_facts_and_shared_queue failed in Repo tests (CPU, rest) on assert active_generations._FENCED == set() carrying an account id it never created. It passed when run alone, passed on some pull requests and failed on others, which is the shape that eventually gets a real test deleted for being flaky. state.active_generations keeps _ACTIVE and _FENCED on the module, so they are process-global and outlive the test that wrote them. Retiring or deactivating an account fences it, and staying fenced is the CORRECT end state for those tests, so none of them is at fault. What was missing is isolation, the same way a tmp dir is isolated rather than every test being asked to clean up after itself. Measured rather than guessed: a report-only probe over the backend suite names 15 leakers, in test_job_accounts.py, test_account_storage.py, test_account_integration_wiring.py and test_account_retired_workspace_recreated.py. Whichever of them landed in an xdist worker ahead of the routing test decided its assertion. So the reset goes in conftest as an autouse fixture, before and after each test, using the reset_for_tests() the module already ships for exactly this. Before AND after: clearing only on the way in leaves the last test of a worker holding a fence, and clearing only on the way out trusts every other plugin to have left it alone. The files that already reset around themselves keep doing so; resetting twice costs nothing and the local call documents the intent at its own site. Reproduced before fixing, and confirmed by differential. Running the four leaker files together with the routing test: pristine main 3 failed, incl. test_owner_routing_facts_and_shared_queue with this fix 2 failed, that one gone The remaining two are an unrelated rag_db pair that fails identically on main in this environment. test_generation_state_isolation.py guards the repair. The structural check reads conftest rather than exercising ordering, because observing a leak functionally would require assuming test ORDER and this suite runs under pytest-randomly, where a test may not assume it. Dropping autouse from the fixture fails that check, which is how I confirmed it is not decorative.
Summary
This pairs with unslothai/unsloth-zoo#1239, which carries the zoo half of the same work; that PR has converged.
save_pretrained_merged(save_method = "lora")andpush_to_hub_merged(save_method = "lora")aredocumented as "save the LoRA adapters with no merging", and both did the opposite: they produced a
full merged checkpoint with no
adapter_config.json. This routes that value to the adapter save thatalready exists, and fixes two smaller things on the same path:
safe_serialization = None, which ourown warning tells people to pass in order to force safetensors, wrote a pickle instead, and an
adapter push raised
TypeErroron transformers 5 because of two keywords that release removed.Root cause
patch_saving_functionsbinds the generic entry points on every model, so both calls land inunsloth_generic_save. That function sends everything except a full fine-tune tomerge_and_overwrite_lora, andmerge_and_overwrite_lorahas no"lora"branch, so the valuematched nothing and fell through to a plain 16bit merge.
unsloth_save_modelhas always had thecorrect adapter branch; it was simply unreachable from these two entry points. On a Llama-3.2-1B
LoRA the result was a 2.47 GB
model.safetensorsand noadapter_config.json, for a call that askedfor a 22.6 MB adapter.
safe_serialization = Noneis falsy to peft and to transformers, so every writer that forwarded itverbatim selected the torch pickle writer and produced
adapter_model.bin, which is the exact filethe advice exists to avoid.
model.save_pretrainedwas the one call in this file that was notwrapped, so the documented remedy for
.binfiles produced a.binfile.transformers 5 rewrote
PushToHubMixin.push_to_huband droppeduse_temp_dirandsafe_serializationfrom its signature. It always stages in a temporary directory and always writessafetensors now, so passing them is both unnecessary and fatal.
Changes
unsloth/save.pyonly._is_adapter_save_methoddecides whether asave_methodis the adapter-only save, spelled the waythe other readers in this file spell it, so
"LoRA"and" lora "mean what"lora"means. Anon-string, which is what the Studio whisper path passes, is not an adapter save.
unsloth_generic_saveroutes an adapter save tounsloth_save_modelinstead of the merge, andforwards the canonical spelling, because
unsloth_save_modelnormalises with.lower().replace(" ", "_")and then rejects anything that is not exactly"lora". Nothing isprewarmed from the Hub for it either, since the base weights are only needed to merge against.
Every other
save_methodreaches the merge exactly as before._normalize_safe_serializationturnsNoneintoTrueat every save entry point in this file,including a new
model.save_pretrainedwrapper.TrueandFalseare unchanged, so an explicitsafe_serialization = Falsestill writes a pickle for anyone who wants one. The low-CPU downgradefurther down still honours an explicit override, which is now tracked separately rather than
inferred from the argument still being
None._filter_push_to_hub_kwargskeeps only the keywords the installedpush_to_hubaccepts, probedfrom the signature rather than gated on a version, and a signature with
**kwargskeepseverything. A dropped keyword is reported only when honouring it would have changed the upload, so
use_temp_dirand a truthysafe_serializationare silent and an explicitsafe_serialization = Falseis not.save_method = "lora"now say what it writes, and the warningthat told people to pass
Nonefor a pickle no longer says that.Compatibility
Every corner below ran the three CPU test files, and the corners with a usable GPU also ran the
end-to-end repro.
baseis current main,branchis this change.mA is a CPU corner on the host that measured this: torch 2.6.0's PyPI wheel carries no
sm_100kernels, so the one GPU step skips there with that error recorded rather than silently passing. The
three test files are stdlib-only and do not import unsloth, which is why they run on the py3.10 floor
unchanged.
Tests
tests/saving/test_save_method_lora_routing.py, 36 tests, new. It parses and executes the individualfunctions out of
unsloth/save.pyagainst stubs, so it needs no model, no GPU and no network. Itcovers the routing decision for three spellings of
"lora"and for four methods that must stillmerge, the agreement between what the router forwards and what
unsloth_save_modelaccepts, theNonenormalisation at each entry point including the wrapper's idempotence and its refusal to touchan explicit
False, the signature-probed push filter including the**kwargsand unreadable-callablecases, and a drift gate on the warning text so the advice and the behaviour cannot part company
again. All 36 fail on main and pass here.
tests/test_merged_hub_destination.pygrew a stub for the new handover so its existing coverage ofthe merge path still applies. 35 tests, passing on both sides.
The whole of
tests/savingplustests/test_merged_hub_destination.pyandtests/test_import_fixes_drift.pyis 637 passed, 14 skipped on this branch, with no test that passeson main failing here.
Evidence
The end-to-end check builds a tiny Llama from a config in-process, attaches a LoRA, and reads back
what each call actually wrote. On main all three spellings of the adapter save reach the merge, and
safe_serialization = Nonewritesadapter_model.bin. On this branch each writesadapter_config.jsonplusadapter_model.safetensorsand nothing else, while an explicitsafe_serialization = Falsestill writes the pickle. Earlier, on a real two-step Llama-3.2-1B LoRA,the same call on main wrote a 2.47 GB
model.safetensorswith noadapter_config.jsonand noconfig.json, against 22.6 MB of adapter here.Cross-platform coverage
The new tests are stdlib-only, so they were run on all three runner families to show the change is
not Linux-shaped. Counts read out of each leg's log rather than taken from the green tick: 71 is the
36 routing tests plus the 35 in
test_merged_hub_destination.py, so no leg is vacuously green.Overlap
unslothai/unsloth#11042also touchesunsloth/save.py, in the GGUF export preflight rather than inthe local save routing or the push keywords. There is no textual overlap with this change.
Known limitations
The GGUF path is untouched.
save_pretrained_gguf(save_method = "lora")has always had its own"lora"branch, which exports the adapter as a GGUF LoRA, and it keeps it. The MLXsave_pretrained_mergedalready performed the adapter save for this value, so all three paths nowagree on what
save_method = "lora"writes, but they still reach it by three different routes.Fixes #1792
Refs #470, where the merge-instead-of-adapter behaviour was recorded as an aside on an otherwise
unrelated, and correctly closed, thread.
Review round: the adapter-only promise was not true with a tokenizer
Codex raised that the
save_method="lora"docstring promisedadapter_config.jsonplusadapter_model.safetensors"and nothing else", while the adapter branch ofunsloth_save_modelcallstokenizer.save_pretrainedwhenever the documentedtokenizerargument is supplied. Correct, and it is a normal supported call rather than a corner.
All four copies of that list now say no base-model weights are written, and that passing
tokenizerwrites that tokenizer's files exactly as the merge methods do. A test fails if theold wording returns.
Pre-existing CI failures, named rather than fixed here
unslothai/unslothmainis itself red onRepo tests (CPU, studio)and(Python 3.13, rest)(run 35060623218). The same two jobs fail on this PR and on several unrelated ones in the same
batch, with the same tests:
tests/multi_account/test_chat_shared_resident.py(3 tests,{"detail":"Failed to get status"})and
tests/studio/test_chat_preset_load_config.py::test_preset_sheet_reacts_to_a_reasoning_budget_change.Neither touches anything this PR changes, so they are recorded here and left to their owner
rather than fixed inside an unrelated PR.