Sub topic 12
Saving, loading and merging adapters
This chapter assumes you have trained a LoRA adapter with PEFT and TRL, as in the previous chapters. You should know what a base model, a tokenizer and an adapter are, and be able to run transformers inference. Here you will learn what a saved adapter contains, how to load it again, when to merge it into the base weights, and what goes wrong in each step.
What an adapter checkpoint contains
A LoRA run does not change the base model. It only trains the small matrices A and B for each target layer. So when you call save_model or save_pretrained on a PEFT model, only those matrices and their configuration are written.
A typical adapter directory looks like this:
| File | Purpose |
|---|---|
| `adapter_config.json` | Rank, alpha, dropout, target modules, task type, and the name of the base model |
| `adapter_model.safetensors` | The trained A and B matrices |
| `README.md` | A model card stub that PEFT generates |
The adapter is small. For a 0.5B-parameter model with rank 16 on the attention projections, the weights are typically a few megabytes to a few tens of megabytes, compared with about 1 GB for the full model in 16-bit precision. This is the storage benefit of LoRA. You can keep dozens of adapters for one base model.
The adapter does not contain the base weights. It also does not contain the tokenizer unless you save it yourself. Two consequences follow:
- To use the adapter later, you need the same base model, at the same revision.
- If you changed the tokenizer during training (for example, you added special tokens), save the tokenizer next to the adapter.
Saving the adapter
The SFTTrainer example from the training chapter already saved the adapter with trainer.save_model("lora-out/adapter"). You can also save from a PEFT model directly, and you should save the tokenizer in the same place so that the directory is self-contained apart from the base model.
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(base_id)
model = AutoModelForCausalLM.from_pretrained(base_id)
model = get_peft_model(
model,
LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM"),
)
# ... training would happen here ...
model.save_pretrained("lora-out/adapter")
tokenizer.save_pretrained("lora-out/adapter")You can inspect the saved configuration to confirm which base model it points to:
import json
with open("lora-out/adapter/adapter_config.json") as f:
config = json.load(f)
print(config["base_model_name_or_path"])
print(config["r"], config["lora_alpha"], config["target_modules"])The field base_model_name_or_path is what AutoPeftModelForCausalLM uses to find the base model automatically.
Saving during training
SFTConfig inherits the checkpointing options of TrainingArguments. With save_strategy="steps" and save_steps=200, the trainer writes a checkpoint-200 folder every 200 steps. For a PEFT model, each checkpoint contains the adapter files plus optimizer and scheduler state, so you can resume. The optimizer state is larger than the adapter itself, so set save_total_limit to keep disk use bounded.
Loading an adapter
There are two common ways to load, and they differ in who loads the base model.
Option 1: load the base model, then the adapter
This gives you control over precision, device placement and quantization.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
base = AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.bfloat16)
model = PeftModel.from_pretrained(base, "lora-out/adapter")
tokenizer = AutoTokenizer.from_pretrained(base_id)
model.eval()
messages = [{"role": "user", "content": "Summarize: LoRA trains small low-rank matrices."}]
inputs = tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
)
output = model.generate(**inputs, max_new_tokens=60)
print(tokenizer.decode(output[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))PeftModel.from_pretrained loads the adapter as non-trainable by default. If you want to continue training, pass is_trainable=True. Without it, the A and B matrices have requires_grad=False, and an optimizer will find no parameters to update.
Option 2: let PEFT load both
AutoPeftModelForCausalLM reads base_model_name_or_path from the adapter config and loads the base model for you.
from peft import AutoPeftModelForCausalLM
model = AutoPeftModelForCausalLM.from_pretrained("lora-out/adapter")This is shorter, but it uses the default precision and device, so the model may load in 32-bit on the CPU. Pass torch_dtype and device_map when memory matters.
Merging an adapter into the base model
During inference with an unmerged adapter, each target layer computes the base output and then adds the LoRA term. That is two extra small matrix multiplications per layer. Merging removes them by folding the update into the weights:
W_merged = W + (alpha / r) · B · A
After merging, the layer is an ordinary linear layer. The model runs at the same speed as the base model, and it no longer depends on PEFT.
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
base = AutoModelForCausalLM.from_pretrained(base_id)
model = PeftModel.from_pretrained(base, "lora-out/adapter")
merged = model.merge_and_unload()
merged.save_pretrained("merged-model")
AutoTokenizer.from_pretrained(base_id).save_pretrained("merged-model")merge_and_unload() does two things. It adds the update into the base weights, and it removes the LoRA wrappers, returning a plain transformers model. Afterwards the PEFT model object should not be reused.
Verify the merge
Merging changes weights in floating point, so outputs can differ slightly. Check that the merged model agrees with the unmerged one before you ship it. This sketch compares logits on the same input.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(base_id)
inputs = tokenizer("LoRA adapts a model by", return_tensors="pt")
peft_model = PeftModel.from_pretrained(
AutoModelForCausalLM.from_pretrained(base_id), "lora-out/adapter"
).eval()
with torch.no_grad():
before = peft_model(**inputs).logits
merged = peft_model.merge_and_unload().eval()
with torch.no_grad():
after = merged(**inputs).logits
print("max abs difference:", (before - after).abs().max().item())In 32-bit the difference should be tiny, on the order of 1e-4 or less. Larger differences suggest a precision problem or a wrong adapter.
Merging into a quantized base
This is the most common source of trouble after QLoRA. The adapter was trained against a 4-bit base, but you cannot cleanly add a 16-bit update into 4-bit weights. Merging directly into quantized weights rounds the result again and loses information, and some PEFT versions refuse or warn.
The usual recipe is:
- Load the base model again in 16-bit (
bfloat16orfloat16), withoutquantization_config. - Load the adapter on top with
PeftModel.from_pretrained. - Call
merge_and_unload()and save.
The merged model is then a full 16-bit model. Its quality can differ slightly from what you evaluated during training, because training saw the quantized base. Evaluate the merged model again, not only the QLoRA version.
Merge or keep separate
| Criterion | Keep adapter separate | Merge into base |
|---|---|---|
| Disk per variant | Megabytes | Full model size |
| Inference speed | Slightly slower | Same as base |
| Runtime dependency | PEFT required | Plain `transformers` |
| Many variants on one base | Easy to swap | One full copy each |
| Reversible | Yes, base stays intact | Not without the original base |
| Quantized deployment | Awkward | Merge in 16-bit, then quantize |
Keep adapters separate when you serve several tasks from one base model, or when you are still iterating. Merge when you have one final model and want the simplest serving setup.
Working with several adapters
One PEFT model can hold more than one adapter. You load each under a name and switch between them without reloading the base model.
from transformers import AutoModelForCausalLM
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
model = PeftModel.from_pretrained(base, "lora-out/adapter", adapter_name="summarize")
model.load_adapter("lora-out/other-adapter", adapter_name="support")
model.set_adapter("summarize")
# generate with the summarize adapter
model.set_adapter("support")
# generate with the support adapterOnly one adapter is active at a time. Calling set_adapter changes which one is used for the next forward pass.
Common errors
- The model behaves like the base model after loading. The adapter may not be active, or the load printed a warning that adapter keys were missing. Check that
target_modulesin the config match the layer names of the loaded base model. - Size mismatch or missing keys. The base model differs from the one used in training, for example a different size or a different model family.
- Garbled output after merging. The merge may have been done in a different precision, or into a quantized base. Re-merge in 16-bit or 32-bit and rerun the logit comparison.
- Chat output has wrong formatting. The tokenizer or chat template was not saved with the merged model. Save the tokenizer into the same folder.
- Training does not resume or does not update. The adapter was loaded without
is_trainable=True. - Calling the PEFT model after
merge_and_unload(). The original wrapper is no longer valid. Use the returned object.
Exercise
You trained a QLoRA adapter on a 4-bit base and now need a 4-bit model for deployment. Describe the order of steps you would take and explain why you would not merge the adapter directly into the 4-bit weights.
Show answer
Load the base model again in 16-bit without quantization, load the adapter on it with PeftModel.frompretrained, call mergeand_unload, evaluate the merged model, save it with its tokenizer, and only then quantize the merged model to 4-bit with your serving tool. Merging directly into 4-bit weights adds a 16-bit update to values that were already rounded to 4 bits, so the result is rounded again and loses information. Merging first and quantizing once keeps the error lower.
Exercise
After loading an adapter with PeftModel.from_pretrained, you start a new training run, but the loss does not change and the trainer reports no trainable parameters. What is the likely cause and the fix?
Show answer
PeftModel.frompretrained loads adapters as frozen by default, so the LoRA matrices have requiresgrad set to False. Pass is_trainable=True when loading to continue training.