Skip to content

Route save_method="lora" to the adapter save instead of the merge - #11067

Merged
danielhanchen merged 12 commits into
mainfrom
pr/save-method-lora-routing
Sep 17, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
pr/save-method-lora-routing

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

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") and push_to_hub_merged(save_method = "lora") are
documented 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 that
already exists, and fixes two smaller things on the same path: safe_serialization = None, which our
own warning tells people to pass in order to force safetensors, wrote a pickle instead, and an
adapter push raised TypeError on transformers 5 because of two keywords that release removed.

Root cause

patch_saving_functions binds the generic entry points on every model, so both calls land in
unsloth_generic_save. That function sends everything except a full fine-tune to
merge_and_overwrite_lora, and merge_and_overwrite_lora has no "lora" branch, so the value
matched nothing and fell through to a plain 16bit merge. unsloth_save_model has always had the
correct 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.safetensors and no adapter_config.json, for a call that asked
for a 22.6 MB adapter.

safe_serialization = None is falsy to peft and to transformers, so every writer that forwarded it
verbatim selected the torch pickle writer and produced adapter_model.bin, which is the exact file
the advice exists to avoid. model.save_pretrained was the one call in this file that was not
wrapped, so the documented remedy for .bin files produced a .bin file.

transformers 5 rewrote PushToHubMixin.push_to_hub and dropped use_temp_dir and
safe_serialization from its signature. It always stages in a temporary directory and always writes
safetensors now, so passing them is both unnecessary and fatal.

Changes

unsloth/save.py only.

  • _is_adapter_save_method decides whether a save_method is the adapter-only save, spelled the way
    the other readers in this file spell it, so "LoRA" and " lora " mean what "lora" means. A
    non-string, which is what the Studio whisper path passes, is not an adapter save.
  • unsloth_generic_save routes an adapter save to unsloth_save_model instead of the merge, and
    forwards the canonical spelling, because unsloth_save_model normalises with
    .lower().replace(" ", "_") and then rejects anything that is not exactly "lora". Nothing is
    prewarmed from the Hub for it either, since the base weights are only needed to merge against.
    Every other save_method reaches the merge exactly as before.
  • _normalize_safe_serialization turns None into True at every save entry point in this file,
    including a new model.save_pretrained wrapper. True and False are unchanged, so an explicit
    safe_serialization = False still writes a pickle for anyone who wants one. The low-CPU downgrade
    further down still honours an explicit override, which is now tracked separately rather than
    inferred from the argument still being None.
  • _filter_push_to_hub_kwargs keeps only the keywords the installed push_to_hub accepts, probed
    from the signature rather than gated on a version, and a signature with **kwargs keeps
    everything. A dropped keyword is reported only when honouring it would have changed the upload, so
    use_temp_dir and a truthy safe_serialization are silent and an explicit
    safe_serialization = False is not.
  • The three docstrings that describe save_method = "lora" now say what it writes, and the warning
    that told people to pass None for 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. base is current main, branch is this change.

corner python torch transformers trl peft base branch
mA 3.10.19 2.6.0+cu124 4.57.6 0.22.2 0.18.0 fail (new tests absent) pass, repro skipped
mC 3.13.12 2.11.0+cu130 5.5.0 1.0.0 0.20.0 fail, repro REPRODUCED pass
mD 3.13.12 2.14.0+cu130 5.17.0 1.13.0 0.20.0 fail, repro REPRODUCED pass

mA is a CPU corner on the host that measured this: torch 2.6.0's PyPI wheel carries no sm_100
kernels, 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 individual
functions out of unsloth/save.py against stubs, so it needs no model, no GPU and no network. It
covers the routing decision for three spellings of "lora" and for four methods that must still
merge, the agreement between what the router forwards and what unsloth_save_model accepts, the
None normalisation at each entry point including the wrapper's idempotence and its refusal to touch
an explicit False, the signature-probed push filter including the **kwargs and unreadable-callable
cases, 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.py grew a stub for the new handover so its existing coverage of
the merge path still applies. 35 tests, passing on both sides.

The whole of tests/saving plus tests/test_merged_hub_destination.py and
tests/test_import_fixes_drift.py is 637 passed, 14 skipped on this branch, with no test that passes
on 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 = None writes adapter_model.bin. On this branch each writes
adapter_config.json plus adapter_model.safetensors and nothing else, while an explicit
safe_serialization = False still 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.safetensors with no adapter_config.json and no
config.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.

runner result tests run
ubuntu-latest success 71 passed
macos-15, Apple Silicon success 71 passed
windows-latest success 71 passed

Overlap

unslothai/unsloth#11042 also touches unsloth/save.py, in the GGUF export preflight rather than in
the 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 MLX
save_pretrained_merged already performed the adapter save for this value, so all three paths now
agree 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 promised adapter_config.json plus
adapter_model.safetensors "and nothing else", while the adapter branch of
unsloth_save_model calls tokenizer.save_pretrained whenever the documented tokenizer
argument 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
tokenizer writes that tokenizer's files exactly as the merge methods do. A test fails if the
old wording returns.

Pre-existing CI failures, named rather than fixed here

unslothai/unsloth main is itself red on Repo 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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T10:35:49.506907Z f5bf654 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
danielhanchen and others added 3 commits September 16, 2026 07:59
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen danielhanchen self-assigned this Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: f5bf654828

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

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
@danielhanchen

Copy link
Copy Markdown
Member Author

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.
@danielhanchen
danielhanchen merged commit f96d035 into main Sep 17, 2026
3 of 28 checks passed
@danielhanchen
danielhanchen deleted the pr/save-method-lora-routing branch September 17, 2026 13:24
danielhanchen added a commit that referenced this pull request Sep 17, 2026
…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]>
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Sep 17, 2026
* 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.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Failure!! Saving to safetensors, not bin format in Colab

1 participant