Skip to content

Fix push_to_hub_merged for full fine-tunes on transformers 5 - #11482

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
NilayYadav:push-merged-full-ft-transformers5
Sep 22, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
NilayYadav:push-merged-full-ft-transformers5

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

On transformers 5, pushing a full fine-tune with push_to_hub_merged crashes with "unexpected keyword argument 'safe_serialization'". Pushing to the Hub from the Studio Export page fails the same way.

The model is now saved to a temporary folder first and uploaded in one commit, which is how pushes to a branch or a PR already work. The upload has the 16-bit weights, tokenizer and model card. This also removes the old push-only config fix, since the saved folder is now fixed before upload. Tested on transformers 5.5.0 and 4.57.6 with a notebook and with the Export page: main failed, this branch uploaded one commit with bf16 weights.

@NilayYadav

NilayYadav commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Reproduced on a real GPU and real Hugging Face Hub pushes (Modal, NVIDIA L4, torch 2.8.0+cu128). Setup: unsloth/SmolLM2-135M-Instruct loaded with full_finetuning = True, one optimizer step, then push_to_hub_merged(repo, tokenizer, save_method = "merged_16bit", private = True, datasets = [...]) to fresh private repos. BEFORE is fresh main 1d8a60840e; AFTER is this PR (c0e5075df) merged onto that main.

transformers Before (main) After (this PR)
5.5.0 TypeError: unsloth_push_to_hub() got an unexpected keyword argument 'safe_serialization', nothing uploaded pushed: 1 commit (Trained with Unsloth), weights BF16 only, config + tokenizer + README.md (datasets and base_model set)
4.57.6 pushed, but as 4 commits (model, tokenizer, README, metadata); weights BF16 + F32 pushed: 1 commit, weights BF16 only, same file set as before

In every run the tokenizer padding_side and the in-memory parameter dtype were unchanged after the push.

  • Tests: tests/test_merged_hub_destination.py + tests/test_save_mtp_policy.py (this PR's versions), run in the same GPU containers where unsloth imports, so the real-transformers test runs instead of skipping. Main: 2 failed / 49 passed (test_default_full_finetune_push_stages_one_commit, test_default_full_finetune_push_uploads_16bit_safetensors). This PR: 51 passed. Both transformers versions give the same result.
  • Codex review (staging PR):
    • Round 1 raised one P1, "unborn default branch before the README download". I rejected it after probing the real Hub: create_repo always creates an initial commit with .gitattributes, and the README download raises RemoteEntryNotFoundError, a subclass of the caught EntryNotFoundError.
    • Round 2 on the same head: "Didn't find any major issues."
  • Independent review found no P1/P2. Two P3 items were declined:
    • A local full-FT folder gets base_model = <repo> in a new card. This matches the existing PEFT and Studio fallbacks.
    • The real-transformers test only skips on ImportError. This is test-only.
  • Staging CI on the merged head: Lint, Workflow trigger lint, Wheel, Version Compat, Notebooks and Kaggle T4 pass. Backend CI fails only in Shell installer tests (_amd_prefer_discrete_gfx: command not found, AMD GPU selection), which is unrelated to this change and fails identically on upstream main (run 35614994800). Core: HF=latest and HF=4.57.6 pass; Core zoo (HF=default) has 3 failures (6870 passed), all GGUF tree-provenance tests (test_gguf_converter_child_env, test_gguf_readback_tree_provenance), which fail identically on upstream main (run 35609595934). The remaining Core cells are still running.

Studio Export page: I ran the real Export page (Local Model → full fine-tune folder → Merged Model → 16-bit → Push to Hub, private). Studio ran on transformers 5.5.0 with each side's save.py verified by sha256.

Both sides succeed and behave identically. With a save folder, which the page always sends, Studio saves to exports/…-merged and uploads that folder with upload_folder. It never calls push_to_hub_merged. So on current main the Export page is not affected by this bug, before or after this PR. The description's line about the Export page failing the same way does not reproduce on current main.

Studio Export push before and after

Full facts

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits unsloth/save.py where a full fine-tune push still calls model.push_to_hub with safe_serialization, which transformers 5 no longer accepts, and routing it through the staged single-commit path looks right; could you confirm the extra temp-folder staging is fine for very large full fine-tunes on small local disks before I review?

@danielhanchen danielhanchen self-assigned this Sep 22, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
…names we wrote

Two follow-ups to the staged full fine-tune push.

The output no longer names the repository. `push_to_hub_merged("me/model")` printed only the
temporary staging folder, and the last line claimed success against a directory deleted a moment
later. The destination is printed around the commit again, as the adapter path already does.

`reconcile_mtp_config` now receives the tensor names the save just wrote. Reading them back off
disk fails for an unindexed `pytorch_model.bin`, which `_checkpoint_tensor_names` declines to
unpickle, so a `safe_serialization = False` export reconciled against "unknown" and kept an
`mtp_num_hidden_layers` the weights do not carry. Reproduced on transformers 4.57.6: before this
commit the uploaded config kept `mtp_num_hidden_layers: 1`, on main it was stripped. Free,
because that state dict is already built for the 16-bit cast; a save that builds none still
passes `None`, so unknown stays unknown.

Both regressions now have a test that fails without the fix.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
A branch upload is not on the default branch, and a fresh pull request leaves the repository
page with no model files at all, so linking it after either one sends the user to the wrong
place. The Hub returns the pull request's own address in `CommitInfo.pr_url`; that is preferred,
and where it is absent the destination is built from what was asked for: the discussions list
for a new pull request, `/discussions/<n>` for an existing `refs/pr/<n>`, and `/tree/<branch>`
for a branch. A plain push to the default branch still prints the repository URL.

`create_pr` is checked before `revision` because with both set the files are in the pull
request, and the revision is only the branch it was opened against.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
…request that cannot be met

Two things found on the staged full fine-tune path.

transformers 5 pops each tensor out of a supplied state dict as it writes the shard holding it
("remove it from state_dict to avoid keeping the ref", modeling_utils), so reading the keys
after save_pretrained reported an export carrying no tensors at all. A model that really has a
multi-token-prediction head then had mtp_num_hidden_layers stripped from the config it shipped
with, and loaders ignore the head that is there. Reproduced on transformers 5.17.0 with an mtp
module present: the uploaded config lost the declaration, and keeps it now. The names are read
before the write instead; the fixture in the test consumes the dict the way transformers does,
so the ordering cannot drift back.

safe_serialization = False now says so when it cannot be honoured. transformers 5 removed the
parameter and always writes safetensors, so an explicit request for a pickle was absorbed by
**kwargs and the export silently came back in the other format. _honours_safe_serialization
probes the signature, the same way _filter_push_to_hub_kwargs already does for the adapter path,
and the default True is never reported.
`patch_saving_functions` replaces `save_pretrained` with a `(*args, **kwargs)` passthrough and
keeps the real method on `original_model_save_pretrained`, so probing the bound attribute saw a
signature that says nothing. On transformers 4, where the pickle IS written, every patched model
therefore got a warning claiming the opposite. Measured on 4.57.6: the probe answered False for
the wrapper and True for the original.

The original is probed now, and the probe answers True whenever it cannot tell, including a
varargs-only signature, since a wrong warning is worse than none. transformers 4.57.6 is silent
again and transformers 5.17.0 still reports, both verified against real patched models.
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #11482, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#58.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1 — reviewed mirror 3ab282528 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on unsloth/save.py (on the mirror)

@@ -5472,7 +5415,7 @@ def unsloth_generic_save(
     # this function's own keywords.
     safe_serialization = _normalize_safe_serialization(safe_serialization)
 
-    if push_to_hub and (create_pr or revision is not None):
+    if push_to_hub and (create_pr or revision is not None or not isinstance(model, PeftModel)):
         return _push_merged_to_hub_revision(dict(locals()))

P2 Badge Honor use_temp_dir for staged full-model pushes

When a non-PEFT model is pushed, this new condition always routes it through _push_merged_to_hub_revision, whose TemporaryDirectory ignores the public use_temp_dir argument. Thus callers using use_temp_dir=False to stage a large checkpoint outside a space-constrained system temp directory now write the entire model to /tmp anyway and can fail with ENOSPC; preserve the caller-selected staging behavior when taking this path.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from shimmyshimmer:

Checked this against the base arm and the premise does not hold: use_temp_dir never reached this path before the change, so no caller could have used it to steer staging.

On base the non-PEFT push arm builds _save_kwargs = dict(safe_serialization, max_shard_size, variant) and calls model.push_to_hub(repo_id, token, private, commit_message, create_pr, revision, commit_description, tags, **_save_kwargs). use_temp_dir is not in that call, so the value the caller passed was dropped and transformers computed its own default, use_temp_dir = not os.path.isdir(working_dir) with working_dir = repo_id.split("/")[-1] (4.57.6 utils/hub.py).

Measured on transformers 4.57.6, base, push_to_hub_merged(..., use_temp_dir = False):

  • with no ./model directory in the CWD: staged into $TMPDIR/tmplu8waw6w, i.e. the flag was ignored and it used a temp dir anyway.
  • with a ./model directory already present: staged into ./model, which is transformers' own isdir default firing, not the caller's flag.

So the only way base avoided the system temp dir was the accident of a CWD folder sharing the repository name. That is worth knowing, and it is in the PR notes, but it is not a caller-selected behaviour this change took away.

It is also not restorable on transformers 5, which removed the argument outright: "removed use_temp_dir argument from push_to_hub. We now use a tmp dir in all cases" (transformers MIGRATION_GUIDE_V5.md). A full checkpoint is written to a temporary directory there whichever path is taken.

Measured staging cost is unchanged: unsloth/SmolLM2-135M-Instruct stages 329,215,255 bytes before the single commit, which is the one checkpoint copy transformers was already writing.

Round 2 — reviewed mirror e396a13c4 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on unsloth/save.py (on the mirror)

@@ -5472,7 +5430,7 @@ def unsloth_generic_save(
     # this function's own keywords.
     safe_serialization = _normalize_safe_serialization(safe_serialization)
 
-    if push_to_hub and (create_pr or revision is not None):
+    if push_to_hub and (create_pr or revision is not None or not isinstance(model, PeftModel)):
         return _push_merged_to_hub_revision(dict(locals()))

P1 Badge Avoid assigning Apache-2.0 to every full-model push

For a default push of any non-PEFT model to a repository without a README, this new condition routes through _push_merged_to_hub_revision, which creates MODEL_CARD with license: apache-2.0 hardcoded at unsloth/save.py:2474. Models derived from gated or differently licensed checkpoints will therefore be published with false licensing metadata, whereas this default path previously called model.push_to_hub without synthesizing that card; derive the license from valid model metadata or omit it when unknown.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

The premise that this path previously published no card does not hold: base publishes the same hardcoded license here.

On base the default full fine-tune push goes through the generated unsloth_push_to_hub, which calls upload_to_huggingface(model, save_directory, token, "finetuned", "trl", ...). That builds ModelCard(MODEL_CARD.format(...)) and pushes it, and MODEL_CARD carries license: apache-2.0 in the YAML block and "License: apache-2.0" in the body.

Captured from a real push on transformers 4.57.6, the README that base uploads on this path:

tags: [text-generation-inference, transformers, unsloth, llama, trl]
license: apache-2.0
language: [en]

and the one this branch uploads:

tags: [text-generation-inference, transformers, unsloth, llama]
license: apache-2.0
language: [en]

Same license, and on this branch it arrives in the single staged commit instead of a separate card push.

The one behavioural difference runs the other way. Base guards the card with create_repo(..., exist_ok = False) inside a try, so it writes a card only when the repository did not exist; this branch writes one only when the README download raises EntryNotFoundError, and otherwise preserves whatever card is already there. So a repository whose owner had hand-written a license keeps it here and did not before.

That leaves exactly one case where this branch adds a card base did not: an existing repository that has no README at all. That is the pre-existing behaviour of _push_merged_to_hub_revision, which has done this for every branch and pull-request push and every PEFT merged push since #10760; this change only routes more traffic to it.

Worth saying plainly: hardcoding apache-2.0 in MODEL_CARD is a real problem. It is also repo-wide, reached by the adapter path, the GGUF path and the Studio fallbacks, and deriving the license from the base model's metadata is a change with its own blast radius. It belongs in its own PR, not smuggled into a transformers 5 fix.

Round 3 — reviewed mirror 6817c2f14a (this PR's 8ae96267a)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 6817c2f14a

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 6817c2f14a (this PR's 8ae96267a).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen

Copy link
Copy Markdown
Member

On transformers 5, pushing a full fine-tune with push_to_hub_merged crashes with TypeError: unsloth_push_to_hub() got an unexpected keyword argument 'safe_serialization' and nothing is uploaded. transformers 5 removed safe_serialization from push_to_hub and dropped its **kwargs, and Unsloth generates its patched push_to_hub by copying that signature, so the first extra keyword raises.

On transformers 4 the same call did not crash but was quietly wrong: state_dict and variant fell into **deprecated_kwargs and were dropped, so the 16-bit cast built just above never reached the upload. A merged_16bit push landed as float32 weights across three separate Hub write operations.

The model is now saved to a temporary folder first and uploaded in one commit, which is how pushes to a branch or a pull request already work. The upload carries the 16-bit weights, the tokenizer and the model card. The old push-only config guard goes with it, since the saved folder is reconciled before the upload.

Measured across the declared transformers range, same model, Hub calls intercepted:

transformers before after
4.51.3 (floor) 3 Hub write ops, weights float32 1 commit, weights bfloat16
4.57.6 3 Hub write ops, weights float32 1 commit, weights bfloat16
5.5.0 (ceiling) TypeError, nothing uploaded 1 commit, weights bfloat16
5.17.0 TypeError, nothing uploaded 1 commit, weights bfloat16

The resident model dtype and the tokenizer's padding_side are unchanged by the push, and a LoRA user, a local save, and a push that already specified a branch or a pull request all take the same code path as before: of 240 enumerated routing cells, 232 are identical and the 8 that move are exactly push_to_hub with a non-PEFT model and no branch or pull request requested.

Also here, each with a test that fails without it:

  • The output names the destination again. The staged save printed only its temporary folder, and the last line claimed success against a directory deleted moments later. A branch or pull-request upload reports where the files actually landed, preferring the pull request's own URL from CommitInfo.pr_url.
  • reconcile_mtp_config receives the tensor names the save just wrote, read before save_pretrained because transformers 5 pops each tensor out of the supplied state dict as it writes the shard holding it. Reading them afterwards reported an export with no tensors and stripped an mtp_num_hidden_layers the weights really do back; reading them off disk cannot see an unindexed pytorch_model.bin at all.
  • safe_serialization = False is reported when this transformers cannot honour it, instead of silently uploading safetensors.

Note on staging cost: the temporary folder is not new. PushToHubMixin.push_to_hub already wrote the whole checkpoint to a temporary directory before uploading, unconditionally on transformers 5 and by default on 4, so the peak disk requirement is unchanged. Measured on unsloth/SmolLM2-135M-Instruct: 329,215,255 bytes staged before the single commit.

The Studio Export page is not affected either way. It always sends a save directory, so the backend uploads that folder with upload_folder and never reaches push_to_hub_merged.


Posted as a comment because the description could not be edited from here (the REST route refuses the token and gh pr edit fails on the deprecated projectCards GraphQL field). The description's line about the Studio Export page failing the same way does not hold, as @NilayYadav already noted above; the corrected account is the one in this comment, and it is what the squash commit will carry.

Verification on the final head, base b37bddb43:

  • 240 enumerated routing cells, 232 identical, 8 moved, 0 violations; the 8 are exactly push_to_hub with a non-PEFT model, no branch and no pull request. Same result under peft 0.18.0, 0.20.0 and 0.21.0.
  • MTP reconciliation across transformers 4.57.6 and 5.17.0, safetensors and pickle, head present and head absent: kept where the weights back it, stripped where they do not, all six cells.
  • Local suites: 107 passed, 2 skipped. The two skips are the GPU + Hub saving scripts behind UNSLOTH_RUN_SAVING_SCRIPTS.
  • Cross-platform: windows-latest and macos-15 both 40 passed on the pure-Python gate. Three torch-dependent tests cannot run on those runners, which ship no torch, and fail identically on base.

@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 76b06af into unslothai:main Sep 22, 2026
6 of 27 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…ai#11482)

On transformers 5, pushing a full fine-tune with `push_to_hub_merged` crashed with
`TypeError: unsloth_push_to_hub() got an unexpected keyword argument 'safe_serialization'`
and nothing was uploaded: transformers 5 removed `safe_serialization` from `push_to_hub` and
dropped its `**kwargs`, and Unsloth generates its patched `push_to_hub` by copying that
signature. On transformers 4 the same call did not crash but was quietly wrong, since
`state_dict` and `variant` fell into `**deprecated_kwargs`, so a `merged_16bit` push landed as
float32 weights across three separate Hub write operations.

The model is now saved to a temporary folder and uploaded in one commit, the way pushes to a
branch or a pull request already worked, carrying the 16-bit weights, the tokenizer and the
model card. The old push-only config guard goes with it, since the staged folder is reconciled
before upload.

Measured across the declared transformers range, same model, Hub calls intercepted:

    4.51.3   3 Hub write ops, float32  ->  1 commit, bfloat16
    4.57.6   3 Hub write ops, float32  ->  1 commit, bfloat16
    5.5.0    TypeError, nothing sent   ->  1 commit, bfloat16
    5.17.0   TypeError, nothing sent   ->  1 commit, bfloat16

Of 240 enumerated routing cells, 232 are identical and the 8 that move are exactly
`push_to_hub` with a non-PEFT model and no branch or pull request requested; unchanged under
peft 0.18.0, 0.20.0 and 0.21.0. The resident dtype and the tokenizer's `padding_side` are
untouched by a push.

Also here, each with a test that fails without it:

- The output names the destination again, preferring the pull request's own URL from
  `CommitInfo.pr_url`, since a branch or pull-request upload is not on the repository page.
- `reconcile_mtp_config` receives the tensor names the save just wrote, read before
  `save_pretrained` because transformers 5 pops each tensor out of the supplied state dict as
  it writes the shard holding it. Reading them afterwards stripped an `mtp_num_hidden_layers`
  the weights really do back; reading them off disk cannot see an unindexed `pytorch_model.bin`.
- `safe_serialization = False` is reported when this transformers cannot honour it, probed
  against the real save method rather than the `(*args, **kwargs)` wrapper
  `patch_saving_functions` installs.

The temporary folder is not new disk cost: `PushToHubMixin.push_to_hub` already staged the whole
checkpoint before uploading, unconditionally on transformers 5 and by default on 4.
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.

2 participants