Skip to content

Attach save_lora without a vLLM engine - #8127

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
danielhanchen:fix/save-lora-without-vllm
Aug 8, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
danielhanchen:fix/save-lora-without-vllm

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The bug

LFM2.5_(1.2B)-GRPO dies at its final save:

AttributeError: 'Lfm2ForCausalLM' object has no attribute 'save_lora'

The notebook loads with fast_inference = False and ends with
model.save_lora("grpo_saved_lora"). patch_peft_fast_inference attaches
save_lora only inside if vllm_engine is not None, so with no engine the
attribute is never set and the call raises. The message names neither vLLM nor
the flag that caused it, so there is nothing in the traceback to act on.

Found by running the 21 base notebooks that no sweep had ever executed.

Why the gate was wrong

save_lora in unsloth_zoo does not use the engine at all:

def save_lora(model, save_directory, *args, **kwargs):
    state_dict = model.state_dict()
    dtype = model.get_input_embeddings().weight.dtype
    state_dict = {k: v.to(dtype) for k, v in state_dict.items()
                  if ".lora_A." in k or ".lora_B." in k}
    kwargs["state_dict"] = state_dict
    model.save_pretrained(save_directory = save_directory, *args, **kwargs)

It is save_pretrained over the LoRA keys of the state dict. Nothing there
needs vLLM, so gating it behind the engine bought nothing and cost every
non-vLLM PEFT model the method.

load_lora stays behind the gate, and that is deliberate: it copies tensors
into vLLM's own adapter buffers, so with no engine there is nothing to load
into.

Compatibility

Additive. Models that previously had save_lora still have it, with the same
implementation.

  • Set only when absent, so anything that already carries a save_lora keeps it.
  • The import is guarded, so an older unsloth_zoo without the helper still loads
    rather than raising during from_pretrained.
  • vllm_engine, fast_generate and fast_generate_batches are untouched
    behind the engine gate, and a test pins that so they are not loosened by
    accident later.

Tests

tests/test_save_lora_without_vllm.py, 6 cases. Three fail against main and
all six pass with the change; the other three pin behaviour that must not move.

Wider run: 1239 passed, 24 skipped across tests/*.py plus
tests/saving/test_export_dispatch.py. One unrelated failure,
test_model_registry.py::test_model_registration[qwen], reproduces identically
on clean main.

Not fixed here

This restores the method. Whether LFM2.5_(1.2B)-GRPO should be running with
fast_inference = False at all is a separate question for the notebooks repo:
its own comment on that line reads "Enable vllm fast inference", which no longer
matches the value.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: b59422c687

ℹ️ 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 and others added 3 commits August 8, 2026 03:21
`patch_peft_fast_inference` set `save_lora` only inside
`if vllm_engine is not None`, so a GRPO run with `fast_inference = False`
reached `model.save_lora(...)` and got

  AttributeError: 'Lfm2ForCausalLM' object has no attribute 'save_lora'

which names neither vLLM nor the flag that caused it. Found running
LFM2.5_(1.2B)-GRPO, which loads with fast_inference = False and saves at the end.

unsloth_zoo's save_lora is save_pretrained over the lora_A/lora_B keys of the
state dict and never touches the engine, so the gate was not buying anything.
load_lora stays behind it: that one copies tensors into vLLM's own adapter
buffers, so without an engine there is nothing to load into.

Set only when absent, and the import is guarded, so an older unsloth_zoo without
the helper still loads.
Comments and docstrings only. AST gate with --strip-docstrings passes on both
files; without it both report CODE CHANGED, which is expected since a docstring
is an AST node. Docstrings touched: the module docstring of
tests/test_save_lora_without_vllm.py and three of its test docstrings.
@danielhanchen
danielhanchen force-pushed the fix/save-lora-without-vllm branch from b59422c to 0b12caa Compare August 8, 2026 03:21

@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: 0b12caa095

ℹ️ 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/_utils.py Outdated
except Exception:
save_lora = None
if save_lora is not None:
model.save_lora = functools.partial(save_lora, model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve non-matrix adapter weights when saving

For non-vLLM fine-tuning with modules_to_save, this newly attached method delegates to a helper that prefilters the state dict to only .lora_A. and .lora_B. keys. This repository automatically adds embed_tokens and lm_head to modules_to_save when new tokens are trained (unsloth/models/llama.py:3325-3350), so PEFT receives none of those module weights and can raise a KeyError during the final save; DoRA checkpoints similarly omit their trained magnitude vectors. Use the normal PEFT adapter-state selection, or extend the helper to preserve every trainable adapter component, before exposing it to all non-vLLM models.

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.

Correct, and worse than the KeyError alone. Reproduced against peft 0.20.0 on a tiny Llama: modules_to_save = ["embed_tokens", "lm_head"] raises KeyError: 'modules_to_save.default.weight', and use_dora = True saves silently while losing all four lora_magnitude_vector tensors. The mechanism is in peft's own get_peft_model_state_dict: it builds each AuxiliaryTrainingWrapper's module-relative dict out of the state dict it was given, so a dict pre-filtered to .lora_A./.lora_B. has nothing for it to look up. And you are right that it is reachable with no vLLM in sight, since get_peft_model appends embed_tokens/lm_head to modules_to_save on its own once new tokens are trained.

Fixed in 77ce195 by letting peft do the selection: the whole state dict is handed over and only the adapter tensors are cast to the embedding dtype, which is the one thing the helper adds over save_pretrained. Non-adapter entries pass through by reference, so nothing is copied that peft is going to drop. Saved key sets now equal what peft.save_pretrained writes on all four shapes (plain, modules_to_save, DoRA, DoRA + modules_to_save), the adapter loads back through PeftModel.from_pretrained, and plain LoRA is unchanged. A model that has a vLLM engine keeps the Zoo helper it has always had, since vLLM reads that file back through its own LoRA loader.

The Zoo helper filters the state dict to .lora_A./.lora_B. before PEFT makes
its own selection, so PEFT then looks up modules_to_save.<adapter>.weight in
what it was handed and raises KeyError, and a DoRA run loses its
lora_magnitude_vector without saying so. Both are reachable with no engine in
sight: get_peft_model adds embed_tokens and lm_head to modules_to_save by
itself once new tokens are trained.

Hand PEFT the whole state dict and cast only the adapter tensors, so its
selection finds the keys it looks up. A model that has a vLLM engine keeps the
Zoo helper unchanged, since vLLM reads the saved adapter back through its own
LoRA loader.

Verified against peft 0.20.0 on plain LoRA, modules_to_save, DoRA and both
together: the saved key set now equals what peft save_pretrained writes in all
four, the adapter loads back, and plain LoRA is byte-for-byte what it was.
@danielhanchen

Copy link
Copy Markdown
Member Author

Where this stands

1. Before the PR. patch_peft_fast_inference attached save_lora only inside if vllm_engine is not None. LFM2.5_(1.2B)-GRPO loads with fast_inference = False and ends on model.save_lora("grpo_saved_lora"), so with no engine the attribute was never set and the run died at its final save:

AttributeError: 'Lfm2ForCausalLM' object has no attribute 'save_lora'

The message named neither vLLM nor the flag that caused it, so there was nothing in the traceback to act on. The gate was wrong on its own terms: unsloth_zoo's save_lora is save_pretrained over the LoRA keys of the state dict and never touches the engine.

2. After the PR. Every PEFT model gets a save_lora, set only when absent so anything already carrying one keeps it. load_lora stays behind the engine gate, deliberately: it copies tensors into vLLM's own adapter buffers, so with no engine there is nothing to load into.

3. Real or theoretical. Real, and found by running the notebook rather than by reading the code. The AttributeError reproduces on any fast_inference = False PEFT model.

The review round on it was also real, and turned out to be the more serious half. The Zoo helper filters the state dict to .lora_A./.lora_B. before PEFT makes its own selection, and PEFT's get_peft_model_state_dict builds each AuxiliaryTrainingWrapper's module-relative dict from the state dict it was handed. Against peft 0.20.0 on a tiny Llama:

adapter zoo save_lora peft.save_pretrained
plain LoRA 8 keys 8 keys
modules_to_save = ["embed_tokens", "lm_head"] KeyError: 'modules_to_save.default.weight' 10 keys
use_dora = True 8 keys, 4 lora_magnitude_vector silently lost 12 keys
DoRA + modules_to_save same KeyError 13 keys

Both are reachable with no vLLM in sight, because get_peft_model appends embed_tokens and lm_head to modules_to_save by itself once new tokens are trained (unsloth/models/llama.py). So broadening the attribute would have broadened a crash and a silent data loss with it. Fixed in 77ce195: PEFT does the selection, the whole state dict is handed over and only the adapter tensors are cast to the embedding dtype, which is the one thing the helper adds over save_pretrained. The saved key set now equals peft.save_pretrained's on all four shapes, the file loads back through PeftModel.from_pretrained, and the dtype cast is preserved.

4. What merging could break.

No new hardware path and no new branch on any existing one. The engine branch is untouched, asserted by test rather than by inspection: vllm_engine, fast_generate, fast_generate_batches and load_lora must all still be assigned inside if vllm_engine is not None, and a model that has an engine keeps the Zoo helper byte for byte, because vLLM reads the saved adapter back through its own LoRA loader and what that file may carry is its call, not one to change here.

Old installs. The engineless attach no longer imports from unsloth_zoo at all, which is a test in its own right: an unsloth_zoo predating save_lora can now only ever cost a vLLM run its save_lora, never a plain one. Where it does import, the import stays guarded. Nothing in Unsloth Studio is touched; studio/ has its own save_lora_adapters export path and does not call this.

Models that already have the attribute keep it, hasattr-gated.

Simulations

Theorised first, then tested against the theory: (a) modules_to_save weights dropped, (b) DoRA magnitudes dropped, (c) plain LoRA must be unchanged, (d) an old zoo must not break loading, (e) an existing save_lora must survive.

Executed on Linux, CUDA_VISIBLE_DEVICES=0, torch 2.9.1+cu128, transformers 5.14.1, peft 0.20.0, real get_peft_model models saved to disk and the safetensors read back: 5 adapter shapes (plain, modules_to_save, DoRA, DoRA + modules_to_save, rslora + bias="all") against three savers each, keyed on equality with what PEFT itself writes. All 5 match. Round-trip load through PeftModel.from_pretrained on the hardest shape. 14 tests in tests/test_save_lora_without_vllm.py, of which the 4 new parametrised ones fail on the previous head.

Not executed, reasoned from source: the vLLM engine branch, since it needs a live engine. It is unchanged, and pinned by two AST tests so it cannot be loosened by accident later. macOS and Windows were not executed either; the change is functools.partial over a dict comprehension with no path or platform handling in it.

@danielhanchen

Copy link
Copy Markdown
Member Author

Review notes: what this does, and what it cannot break

Before the PR

LFM2.5_(1.2B)-GRPO loads with fast_inference = False and ends with model.save_lora("grpo_saved_lora"). That died:

AttributeError: 'Lfm2ForCausalLM' object has no attribute 'save_lora'

patch_peft_fast_inference attached save_lora only inside if vllm_engine is not None, so with no engine the attribute was never set. The traceback named neither vLLM nor the flag that caused it, so there was nothing in it to act on. Confirmed by driving the real function: before the patch, hasattr(model, "save_lora") is False on an engine-less model.

After the PR

save_lora is attached whether or not there is an engine. It needs none: it is save_pretrained over the adapter. load_lora stays behind the gate on purpose, because it copies tensors into vLLM's own adapter buffers, so with no engine there is nothing to load into. Verified: with no engine, save_lora is present and load_lora is not.

Real or theoretical

Real. It came out of running the 21 base notebooks that no sweep had ever executed, and it is the last call in one of them, so the failure destroys the output of a completed GRPO run.

If merged, what could it break

I drove patch_peft_fast_inference and save_lora_adapter directly over a fake PEFT model carrying DoRA magnitudes, modules_to_save for embed_tokens and lm_head, and a frozen base layer. 22 checks, all passing:

  • The engine path is byte-for-byte the old behaviour. With an engine, vllm_engine, fast_generate and fast_generate_batches are still forwarded, load_lora is still the Zoo helper, and save_lora is still the Zoo save_lora, not the new local one. vLLM reads the saved adapter back through its own LoRA loader, so what that file may contain stays vLLM's call.
  • Additive only. A model that already carries a save_lora keeps its own; the new attribute is set only when absent.
  • An old unsloth_zoo still imports. With a vllm_utils that has load_lora but no save_lora, the patch does not raise and falls back to the local saver, which then writes correctly. So an older unsloth_zoo, and any existing Unsloth Studio install pinned to one, keeps working.
  • The dtype cast follows the embedding, checked for fp16, fp32 and bf16 separately.

One thing worth calling out, because it is the reason this does not simply reuse the Zoo helper. That helper filters the state dict down to .lora_A./.lora_B. before handing it to save_pretrained. On the models reachable here without vLLM that silently loses data: my run shows the .lora_A./.lora_B. filter dropping lora_magnitude_vector (a DoRA run) and both modules_to_save entries, and get_peft_model adds embed_tokens and lm_head to modules_to_save on its own once new tokens are trained. PEFT then also raises KeyError looking up modules_to_save.<adapter>.weight in what it was given. So the new saver hands PEFT the whole state dict and casts only the adapter tensors, letting PEFT's own selection decide what an adapter contains. Non-adapter entries are passed through by reference, so nothing is copied that PEFT is going to drop.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1fe4544a1a

ℹ️ 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 21f8efd into unslothai:main Aug 8, 2026
46 of 50 checks passed
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