Skip to content

MTP: keep the trained head when saving a named PEFT adapter - #14912

Merged
danielhanchen merged 9 commits into
mainfrom
dh/s3-mtp-named-adapter-save
Oct 23, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
dh/s3-mtp-named-adapter-save

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

PEFT saves every adapter other than default into <save_directory>/<adapter_name>/. The plain save_pretrained wrapper added for a trained MTP head only looked for adapter_config.json in the root, so it treated a named adapter save as a full checkpoint save. The head stitch then raised FileNotFoundError: no safetensors checkpoint ... to write an MTP head into, after the adapter itself had been written and without saving the head.

The wrapper now finds the adapter folders the save actually wrote: the root for default (and for transformers-native adapters), and <save_directory>/<name>/ for each other adapter, limited to the ones written by this save and to selected_adapters when it is passed. The trained MTP head is written as mtp_head.safetensors beside the adapter that is active when save_pretrained runs. When pushing, the head file is uploaded at that folder's path. A save of only the default adapter is unchanged.

Rules:

  • No head is written beside an adapter that is not active at save time.
  • An empty selected_adapters saves no head.
  • When several adapters are active together, no head is written beside any single one.
  • A folder written without a head has any stale local mtp_head.safetensors removed.

Limits: the saved head is tied to the adapter active when save_pretrained runs, not to the adapter it was trained alongside. If you train with one adapter and then call set_adapter on another, switch back to the training adapter before saving. Pushing to a Hub repo that already holds mtp_head.safetensors from an earlier push keeps that remote file even when the new adapter has no head, because uploads never delete files. Delete it from the repo, or push to a fresh repo, when reusing a folder.

Tests: tests/test_save_mtp_head_stitch.py and tests/test_save_mtp_policy.py (55 passed with a GPU visible against unsloth-zoo main).

PEFT writes a non-default adapter into <save_directory>/<adapter_name>/, so the
plain save_pretrained wrapper did not see an adapter_config.json in the root and
tried to stitch the head into a full checkpoint that does not exist, raising
FileNotFoundError. Write mtp_head.safetensors beside every adapter folder this
save produced, and upload each of them on push.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-10-23T11:06:23.345531Z 9c2bd0d 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 96e60300f0

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

Comment thread unsloth/models/speculative.py Outdated
`save_directory/<adapter_name>/`.
"""
names = list(getattr(model, "peft_config", None) or {})
candidates = [""] + [name for name in names if name != "default"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict sidecars to adapters selected by this save

When a reused directory is saved with selected_adapters, this enumerates every adapter in peft_config and relies on the one-second mtime tolerance to infer which were selected. For example, if default was saved less than a second before save_pretrained(..., selected_adapters=["task"]), its unchanged config still passes the timestamp check, so the loop rewrites default/mtp_head.safetensors with the current task's head even though PEFT did not rewrite the default adapter. This silently leaves that adapter paired with the wrong head; derive candidates from the bound selected_adapters argument (defaulting to all) before applying the freshness check.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 273b032: the candidate folders now come from the selected_adapters this save was called with (bound against the real save_pretrained signature, so keyword and positional both work). Only when it is None does it fall back to every adapter in peft_config, which is what PEFT itself does. A default adapter saved a moment earlier is no longer rewritten by save_pretrained(..., selected_adapters=["task"]). The mtime check stays only as a guard that the folder was written by this save. Test: test_selected_adapters_save_leaves_other_folders_alone[kw, positional].

Comment thread unsloth/models/speculative.py Outdated
Comment on lines +230 to +231
for folder in adapter_dirs:
if _save_mtp_head_beside_adapter(model, os.path.join(save_directory, folder)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid copying an active adapter's head to inactive adapters

When a PEFT model contains multiple adapters, the MTP head is trained against the model's active adapter configuration, but save_pretrained defaults to saving every adapter. This loop writes that single head beside every saved adapter, including inactive ones; subsequently loading one of those inactive adapter folders causes _reattach_saved_mtp_head to attach a drafter trained against a different target model. Track which adapter configuration the head was trained with and only emit the sidecar for a matching saved adapter rather than duplicating it into every fresh folder.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 273b032: the head is written only beside saved adapters that are in the model's active adapters (active_adapters / active_adapter), so an inactive adapter folder never gets a head trained against a different adapter. Saving only inactive adapters writes no head and does not fall back to the full-checkpoint stitch. Test: test_head_is_written_only_beside_the_active_adapter.

pre-commit-ci Bot and others added 2 commits October 23, 2026 06:05
…are active

Read selected_adapters from the save call instead of inferring from mtimes, so a
default adapter saved a moment earlier is not rewritten by a save of another one.
The head trained against the active adapter, so inactive adapters do not get it.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 273b03249d

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

Comment on lines +206 to +208
names = list(selected) if selected is not None else list(config or {})
if not names:
names = ["default"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor an explicitly empty adapter selection

When a PEFT caller passes selected_adapters=[], PEFT intentionally saves no adapters, as exercised by tests/utils/test_lora_ga_save_conversion.py. This fallback instead treats the empty list as default; in a fresh output directory no adapter config is found, so control reaches _stitch_mtp_head and attempts to stitch the attached head into a nonexistent full checkpoint, raising after an otherwise valid no-op save. Preserve the distinction between None (all adapters) and an explicitly empty list.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 76941f6. PEFT treats only None as all adapters, and an empty list saves nothing. The wrapper now returns as soon as the selection is empty, so it neither falls back to default nor reaches _stitch_mtp_head. New test test_an_empty_adapter_selection_saves_no_head fails on the previous head and passes now.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1f45502 and kept in the current head: an explicitly empty selected_adapters saves no MTP head, covered by the stitch policy tests.

Comment on lines +264 to +268
active = _active_adapters(model) if getattr(model, "peft_config", None) else None
for name, folder in adapter_dirs:
if active is not None and name not in active:
continue
if _save_mtp_head_beside_adapter(model, os.path.join(save_directory, folder)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid splitting a combined-adapter head into individual sidecars

When multiple adapters are simultaneously active, which the repository supports via set_adapter(["a", "b"]), the MTP head is trained against their combined effect. Although inactive adapters are now skipped, the current loop still writes that same combined head beside both a and b; loading either adapter folder alone then reattaches a drafter trained against a different target configuration. Only emit an adapter sidecar when the active configuration consists of that single adapter, or persist enough metadata to require and restore the full combination.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 76941f6. A head trained with several adapters active belongs to their combination, not to any one of them. The save now writes a sidecar only when exactly one adapter is active and it is among those saved; with a combined set it writes none, says so in one line, and clears a leftover head from a reused folder so a later load cannot attach it. New test test_a_combined_adapter_head_is_not_split_into_sidecars fails on the previous head and passes now; the MTP save tests give 53 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 76941f69e2

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

names = ["default"]
out = []
for name in names:
folder = "" if name == "default" else name

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep Transformers-native named adapters at the root

When the head is attached to a PreTrainedModel using Transformers' native add_adapter(..., adapter_name="task") integration, save_pretrained writes the active adapter's adapter_config.json and adapter_model.safetensors directly into save_directory, even for a non-default name. This mapping instead looks only under <save_directory>/task, so _fresh_adapter_dirs returns empty and the wrapper calls _stitch_mtp_head; because an adapter save has no model.safetensors, that raises FileNotFoundError after the adapter has already been written. Distinguish native Transformers adapter saves from PeftModel.save_pretrained before choosing the named subdirectory layout.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 1f45502. With transformers' own PEFT integration, save_pretrained writes only the active adapter, and it writes it into save_directory itself even when the adapter has a non-default name (transformers v5.17.0 modeling_utils.py 3370-3395, v4.57.6 3932-3957). The wrapper looked under the adapter-named subfolder, found nothing, and stitched the head into a checkpoint that does not exist. A model whose adapters came from add_adapter, and that is not a PeftModel, now has its active adapter mapped to the save root, so the head is written beside that adapter and nothing is stitched. New test test_transformers_native_adapter_head_goes_to_the_root (tiny GLM with add_adapter, names default and task) fails on the previous head for task and passes now; the MTP save tests give 55 passed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1f45502 and kept in the current head: transformers-native adapters are written at the save root, so the head goes beside them there, covered by the stitch policy tests.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1f4550211a

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

if adapter_dirs:
files = []
# The head trained against the active adapter; an inactive one must not inherit it.
active = _active_adapters(model) if getattr(model, "peft_config", None) else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bind the saved head to its training adapter

If the MTP head is trained while adapter task is active and the caller subsequently switches to default before saving, this reads only the model's current active adapter and writes the already-trained head beside default; reloading then pairs a drafter trained against task with the wrong target adapter. The fresh post-fix code still does not record which adapter configuration was active during head training, so adapter switching between training and saving silently mis-associates the sidecar.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in ed3c877. The save used the adapter active at save time, so switching adapters after training moved the head. The head now records which adapters were active whenever it runs with gradients (a forward pre-hook installed by get_mtp_head; eval and inference forwards do not count), and the sidecar is written only beside that adapter. If this save does not include it, no head is written, a stale head in the saved folder is removed, and one line says why; a head trained under more than one adapter set is treated like a combined set and gets no sidecar. The record lives in the process, so a fresh process falls back to the active adapter as before. New test test_head_stays_bound_to_the_adapter_it_trained_with fails on the previous head and passes now; the MTP save tests give 56 passed.

danielhanchen and others added 2 commits October 23, 2026 02:55
A forward pre-hook on the head records the active adapter set whenever the head
runs with gradients; the sidecar save uses that set rather than whichever adapter
is active at save time, and says so when the saved selection does not include it.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d734265358

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

Comment on lines +270 to +272
for name in names:
folder = "" if name == "default" else name
adapter_config = os.path.join(save_directory, folder, "adapter_config.json")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate named adapter subfolders when reattaching heads

For a non-default adapter this places both the adapter and its head under <repo>/<adapter_name>/, including when PeftModel.push_to_hub uploads the whole save directory. The automatic reload path in unsloth/models/loader.py::_reattach_saved_mtp_head only requests mtp_head.safetensors from the repository root and accepts no subfolder, while the surrounding PEFT probes likewise do not forward subfolder; consequently a pushed named adapter cannot automatically recover this newly saved head. Pass the selected adapter subfolder through detection, PEFT loading, and head download, or flatten single-adapter Hub saves.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the reload path and this is not a bug. unsloth/models/loader.py only ever loads the adapter at the root of model_name: PeftConfig detection reads os.path.join(model_name, "adapter_config.json"), PeftModel.from_pretrained(model, old_model_name, ...) passes no adapter_name and no subfolder, and _reattach_saved_mtp_head(model, old_model_name, ...) looks for mtp_head.safetensors in that same root. So the head it attaches always belongs to the adapter that was just loaded. A named adapter saved in <dir>/<name>/ is reloaded by passing <dir>/<name> as the model path, and its head sits right there. Also searching <repo>/<adapter_name>/ would attach a different adapter's head to the root adapter, which is the cross-adapter leak this PR prevents.

This reverts commit ed3c877. The head is saved
beside the single active adapter this save writes; switch back to the training
adapter before saving.

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 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. Hooray!

Reviewed commit: 9c2bd0d602

ℹ️ 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
danielhanchen merged commit e49be2a into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the dh/s3-mtp-named-adapter-save branch October 23, 2026 15:56
danielhanchen added a commit that referenced this pull request Oct 23, 2026
`pre-commit.ci - pr` is failing on new PRs (for example #14954 and
#14955, both queued after the last format fix) because
`unsloth/models/speculative.py` on `main` is not formatted. #14912 left
a blank line after the function-local import in `_drop_stale_head`, and
the pinned `ruff-format-with-kwargs` hook (ruff 0.6.9) removes it. The
hook runs over every file, so every PR inherits the failure.

This is format only:
- the AST is identical before and after;
- re-running `scripts/run_ruff_format.py` over every Python file changed
on `main` since the last format fix leaves nothing else to change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant