Sub topic 13
Serving adapters and merged models
This chapter assumes you have trained and saved a LoRA adapter, as in the earlier chapters. It also assumes you can run a Hugging Face model for inference. Here you decide how to deploy that adapter, either merged into the base weights or kept separate, and you learn the errors that come with each choice.
Two ways to deploy
A trained adapter is a small directory. It holds adapter_config.json and adapter_model.safetensors, and it is useless without the base model it was trained on. You can deploy it in two ways.
- Merged model. You add the low-rank update into the base weights, so each adapted weight becomes
W' = W + (alpha/r) * B @ A. The result is an ordinary model with no PEFT dependency, and inference costs the same as the base model. - Adapter on base. You keep the base weights frozen and apply the adapter at run time. Each adapted layer does extra small matrix multiplications. In exchange, one base model in memory can serve many adapters.
| Concern | Merged model | Adapter on base |
|---|---|---|
| Inference latency | Same as base | Slightly higher per adapted layer |
| Disk per variant | Full model size | Tens of megabytes |
| Many tasks or customers | One full copy each | One base plus one small adapter each |
| Dependencies at serve time | transformers only | PEFT or a server with LoRA support |
| Rolling back a change | Replace the whole model | Swap or unload one adapter |
| Quantized deployment | Needs care (see below) | Works directly on a quantized base |
Running an adapter with PEFT
PeftModel.from_pretrained loads the adapter onto a base model. You can attach several adapters under different names and switch between them. The disable_adapter() context manager gives you the base model's behavior without reloading anything, which is handy for comparisons.
The script below assumes two adapters exist, lora-out/adapter from the training chapter and a second one in lora-out/adapter-v2. Replace the paths with your own.
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)
base = AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.bfloat16)
model = PeftModel.from_pretrained(base, "lora-out/adapter", adapter_name="v1")
model.load_adapter("lora-out/adapter-v2", adapter_name="v2")
model.eval()
def ask(prompt: str) -> str:
messages = [{"role": "user", "content": prompt}]
inputs = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
return_dict=True,
)
with torch.no_grad():
out = model.generate(**inputs, max_new_tokens=64, do_sample=False)
new_tokens = out[0][inputs["input_ids"].shape[1]:]
return tokenizer.decode(new_tokens, skip_special_tokens=True)
prompt = "Summarize: LoRA trains small low-rank matrices."
model.set_adapter("v1")
print("v1:", ask(prompt))
model.set_adapter("v2")
print("v2:", ask(prompt))
with model.disable_adapter():
print("base:", ask(prompt))Greedy decoding (do_sample=False) makes the three outputs comparable, because any difference comes from the weights and not from sampling noise.
What happens inside
For an adapted layer, the forward pass computes base(x) + scale * (x @ A.T @ B.T), as in the LoRALinear class from earlier. The second term costs two skinny matrix multiplications of width r. The cost is small in FLOPs, but it adds extra kernel launches per layer. At small batch sizes that overhead can be visible in latency.
Merging for a standalone model
Merging folds (alpha/r) * B @ A into each target weight. After that the adapter modules are removed, and the model is a plain transformers model.
The adapter was trained against specific base weights. Merge it into the same base checkpoint, and into a full-precision copy of it. The script below merges, saves, and then checks that the merged model matches the unmerged one. It runs in float32 so that the comparison is not hidden by half-precision rounding.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
adapter_dir = "lora-out/adapter"
tokenizer = AutoTokenizer.from_pretrained(base_id)
# Two separate base copies: merge_and_unload modifies its model in place.
unmerged = PeftModel.from_pretrained(
AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.float32),
adapter_dir,
).eval()
merged = PeftModel.from_pretrained(
AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.float32),
adapter_dir,
).merge_and_unload().eval()
batch = tokenizer("Summarize: LoRA trains small low-rank matrices.", return_tensors="pt")
with torch.no_grad():
diff = (unmerged(**batch).logits - merged(**batch).logits).abs().max()
print("max logit difference:", diff.item())
merged.save_pretrained("merged-model")
tokenizer.save_pretrained("merged-model")The printed difference should be tiny, on the order of floating-point noise. A large value means the two paths are not computing the same function, and you should not ship the merged model until you find out why.
Keep these points in mind when you merge:
merge_and_unload()is one-way for that object. If you want to switch back, callmerge_adapter()andunmerge_adapter()instead. Those keep the adapter modules in place. Unmerging in half precision can leave small rounding residue.- Save the tokenizer next to the merged weights. Loading the merged directory without a tokenizer, or with a different chat template, is a common cause of broken output.
- Merging several adapters at once is a different operation. PEFT offers
add_weighted_adapterfor it, and the result is not guaranteed to keep the behavior of either adapter.
Merging after QLoRA
If you trained with QLoRA, the base was stored in 4-bit. Do not merge the adapter into that 4-bit base. The merged weights would have to be rounded back into 4-bit, which adds error on top of the quantization error the adapter was trained to work around.
The usual route is to reload the base in bf16 or fp16, load the adapter onto it, and merge there. The merged model will behave slightly differently from the QLoRA model you evaluated, because the adapter now sits on the unquantized weights. Run your evaluation set again on the merged model before you ship it. If you want a small deployed model, quantize the merged model afterwards with a method designed for inference, such as GPTQ or AWQ, and evaluate it once more.
Serving many adapters with vLLM
For multi-tenant serving you want one copy of the base weights and many adapters selected per request. vLLM supports this directly.
vllm serve Qwen/Qwen2.5-0.5B-Instruct \
--enable-lora \
--lora-modules summarize=/models/lora-out/adapter support=/models/lora-out/adapter-v2 \
--max-lora-rank 16Each name in --lora-modules becomes a model name in the OpenAI-compatible API. A client picks an adapter through the model field.
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "summarize",
"messages": [{"role": "user", "content": "Summarize: LoRA trains small low-rank matrices."}],
"max_tokens": 64
}'Requests for different adapters can be batched together, so the server stays busy. Sending "model": "Qwen/Qwen2.5-0.5B-Instruct" returns the plain base model.
A merged model needs no special flags. You serve the merged-model directory like any other checkpoint, with vLLM, Text Generation Inference, or plain transformers.
Common errors
- Rank limit. The server refuses to load an adapter whose rank is larger than its configured maximum. Set
--max-lora-rankto at least the highest rank you trained. - Unsupported target modules. Some servers support LoRA only on certain layers. An adapter trained with
target_modules="all-linear"may need a recent server version. Test loading before you plan a launch around it. - Wrong base. An adapter loads without error onto a different base of the same shape, and the outputs are quietly poor. Read
base_model_name_or_pathinadapter_config.json, and pin the base revision in your deployment. - Chat template mismatch. The server must format prompts exactly as training did. If your adapter directory has no tokenizer, the server may fall back to the base model's template, and that may not be the one you trained with.
- Dtype surprises. Merging in bf16 and then comparing against an fp32 run produces small differences that look like bugs. Compare in one dtype, as the verification script does.
- Missing adapter weights after merge. After
merge_and_unload()there is no adapter to save. Save the adapter before merging if you still want it.
Practical checklist
- Record the base model ID and revision next to every adapter you keep.
- Evaluate the exact artifact you will deploy (merged, quantized, or adapter on base), not only the training-time model.
- Save the tokenizer with the model or adapter and confirm the chat template renders as it did in training.
- Compare logits or fixed greedy outputs between the unmerged and merged models before release.
- Load-test the serving setup with the adapter mix you expect, since adapter swapping and batching change throughput.
Exercise
You trained an adapter with QLoRA on a 4-bit base. A teammate suggests loading the same 4-bit base, calling mergeandunload(), and shipping the result to save time. What is wrong with this, and what should you do instead?
Show answer
Merging adds (alpha/r)BA into weights that are stored in 4-bit, so the merged values must be rounded back into 4-bit. That adds error beyond what the adapter was trained to handle. Reload the base in bf16 or fp16, load the adapter onto it, merge there, and re-run the evaluation on the merged model. If a smaller model is needed, quantize the merged model afterwards with an inference-oriented method and evaluate again.
Exercise
A company has 40 customers, each with its own LoRA adapter of rank 16 trained on the same 7B base model. Compare merged deployment and shared-base deployment for this case, and name one cost of the shared-base choice.
Show answer
Merging gives 40 full copies of the 7B model, so disk and GPU memory grow about 40 times, and each copy must be loaded and kept warm. A shared base keeps one copy of the base weights plus 40 small adapters, and a LoRA-aware server such as vLLM can batch requests for different customers together. The cost is a small per-layer latency overhead from the extra low-rank matrix multiplications, plus the need for a server that supports LoRA and the rank and target modules you used.
Exercise
After merging, the logits from the merged model differ a lot from the unmerged PEFT model on the same input. List two likely causes you would check first.
Show answer
Likely causes are a different base checkpoint or revision for the two models, and a dtype mismatch or a merge done in low precision. Another common cause is merging an adapter into a quantized base. Load both models from the same base ID, use float32 for the comparison, and confirm the adapter was merged only once.