Sub topic 14
Common failure modes and fixes
This chapter assumes you have trained a LoRA adapter with PEFT and TRL's SFTTrainer, and that you can read a training loss curve. It covers the problems that show up most often, how to recognize each one, and what to change. The goal is to go from a vague symptom ("the model got worse") to a specific cause and a specific fix.
A diagnostic mindset
Most fine-tuning failures fall into three groups.
- Data and format problems. The model trains on text it will never see at inference time, or the training text is wrong in some other way.
- Optimization problems. The learning rate, rank, or number of epochs does not suit the data.
- Setup problems. The adapter is not attached to the right layers, the wrong weights are saved, or the merge goes wrong.
Check the data and format first. They are the most common cause, and the cheapest to inspect. Change one thing at a time between runs, and keep the held-out evaluation from the previous chapter so you can compare runs.
Wrong chat template
A chat template is the rule that turns a list of messages into one string with special tokens such as role markers. An instruct model was trained with one specific template. If you train with a different format, or serve with a different one, the adapter learns patterns the model never sees at inference time.
Typical symptoms:
- The model answers well in training-style prompts but poorly in your application.
- The output contains stray role words such as
assistantoruser. - The model keeps generating after the answer is complete, sometimes writing a new user turn itself.
Fixes:
- Use the tokenizer's own template in both training and inference. Do not build prompt strings by hand.
- Print one fully formatted training example and read it. Confirm the special tokens are where you expect them.
- At inference, call
apply_chat_templatewithadd_generation_prompt=Trueso the prompt ends where the assistant's reply should begin.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
messages = [
{"role": "user", "content": "Summarize: LoRA trains small low-rank matrices."},
{"role": "assistant", "content": "LoRA adapts a model by training only small low-rank matrices."},
]
# What the trainer should see during training
print(tok.apply_chat_template(messages, tokenize=False))
# What the model should see at inference: ends with the assistant turn opened
print(tok.apply_chat_template(messages[:1], tokenize=False, add_generation_prompt=True))Compare the two outputs. The inference prompt must be a prefix of the training text, up to the start of the assistant reply. If it is not, the model sees a different format at inference than it was trained on.
Missing or wrong end-of-sequence token
The model learns to stop by seeing an end-of-sequence (EOS) token after each answer. If the training text does not contain the right EOS token, the model has no signal to stop and generates until it hits the length limit. Base models and instruct models often use different EOS tokens, and a mismatch between the tokenizer's eos_token and the token the template uses to end a turn is a known source of this bug.
Check by decoding a training example and looking at its last tokens. If generation never stops, confirm that tokenizer.eos_token and the model's generation_config.eos_token_id match the token that closes an assistant turn in your template. You can also pass eos_token_id explicitly to generate.
Padding and truncation problems
Two related issues come from how sequences are cut and padded.
- No pad token. Some tokenizers define no pad token, and batching with padding then fails or behaves oddly. A common fix is
tokenizer.pad_token = tokenizer.eos_token. Recent TRL versions handle this in many cases, but verify it for your model. - Truncation that removes the answer. If a training example is longer than the maximum sequence length, the end is cut off. The assistant reply, which is the part you want to learn, may be lost along with the EOS token. Measure token lengths across your dataset, then raise the maximum length or shorten or drop the long examples.
A quick check:
import numpy as np
def token_lengths(dataset, tokenizer):
lengths = []
for row in dataset:
text = tokenizer.apply_chat_template(row["messages"], tokenize=False)
lengths.append(len(tokenizer(text)["input_ids"]))
return np.array(lengths)
# lengths = token_lengths(train_ds, tok)
# print(lengths.max(), np.percentile(lengths, 95))If the 95th percentile is above your maximum sequence length, many examples are being truncated.
Overfitting
Overfitting means the model memorizes the training examples instead of learning the pattern. Training loss keeps falling while validation loss stops improving and then rises. On small datasets of a few hundred examples, this can happen within two or three epochs.
Signs:
- Validation loss turns upward while training loss continues down.
- The model repeats phrases from training answers word for word.
- Quality on held-out prompts is worse than after an earlier checkpoint.
Fixes, roughly in order of effort:
- Train for fewer epochs, and keep the checkpoint with the best validation loss (
load_best_model_at_endwith an evaluation strategy in the trainer arguments). - Lower the rank
r, or raiselora_dropoutto something like 0.05 to 0.1. - Lower the learning rate.
- Add more data, or remove near-duplicate examples. Duplicates make memorization easier.
Underfitting and no learning
If the training loss barely moves, the adapter is not learning. Check these in order.
- Trainable parameters. Call
model.print_trainable_parameters(). If the count is zero, nothing is training. If it is tiny, yourtarget_modulesmay not match any layer. - Target module names. Names such as
q_projare specific to some architectures. Other models use different names. PEFT raises an error when none match, but a partial match can silently leave out layers you wanted. Print the module names withmodel.named_modules()and check them. - Learning rate. LoRA usually works with learning rates around 1e-4 to 3e-4, which is higher than full fine-tuning. A rate suited to full fine-tuning, such as 1e-5, can make the adapter learn very slowly.
- Rank and alpha. The update is scaled by
alpha / r. A very smallalpharelative torshrinks the update. BecauseBstarts at zero, the model begins identical to the base model, so early steps show little change by design. - Frozen by mistake. With a custom setup, confirm that
requires_gradis true on the adapter weights, and that gradient checkpointing with a frozen base does not cut the gradient path. When using gradient checkpointing with PEFT, you may needmodel.enable_input_require_grads().
Loss spikes and divergence
If the loss suddenly jumps or becomes nan, suspect the learning rate or numeric precision.
- Lower the learning rate and add warmup steps (
warmup_ratioof 0.03 to 0.1). - Set gradient clipping (
max_grad_norm=1.0is the usual default). - Use bfloat16 instead of float16 on hardware that supports it. float16 has a narrow range and can overflow.
- For QLoRA, keep the compute dtype at bfloat16 where available, as in the earlier chapter.
Catastrophic forgetting
Forgetting means the model loses general abilities while it learns your task. After fine-tuning on narrow data, it may follow your format perfectly yet fail at basic reasoning, switch languages badly, or refuse to answer questions outside the domain. LoRA reduces forgetting compared with full fine-tuning, because the base weights stay frozen, but it does not remove it. A high rank, a high learning rate, or many epochs all make it worse.
How to detect it: run a small general-purpose check, such as a handful of prompts unrelated to your task, against both the base model and the adapted model, as part of your evaluation. Do this every time, not only when something looks wrong.
Fixes:
- Lower the learning rate, rank, or number of epochs.
- Mix a portion of general instruction data into the training set, so the model keeps seeing varied tasks.
- Use a smaller
alpha, or scale the adapter down at inference. Some PEFT versions let you adjust adapter weighting, which blends the adapted and base behavior.
Training on the prompt instead of the answer
By default, the loss may be computed over every token, including the user's prompt. That teaches the model to predict user text, which is wasted capacity and can distort behavior. Many setups compute loss on the assistant reply only. In TRL this is controlled by options such as assistant_only_loss or completion_only_loss, depending on the dataset format and version. The assistant_only_loss option needs a chat template that marks assistant tokens, so check your TRL version's documentation. If your results are poor on tasks with long prompts and short answers, this is a likely cause.
Out-of-memory errors
When training runs out of GPU memory, reduce the memory cost in this order:
- Lower
per_device_train_batch_sizeand raisegradient_accumulation_stepsso the effective batch size stays the same. - Shorten the maximum sequence length. Activation memory grows with sequence length.
- Turn on gradient checkpointing, which trades extra compute for lower activation memory.
- Load the base model in 4-bit with QLoRA.
- Lower the rank or reduce the number of target modules. This helps, but the savings are usually small next to the first four steps, because the adapter is a small share of memory.
Merge and loading problems
Several failures appear only after training.
| Symptom | Likely cause | Fix |
|---|---|---|
| Merged model behaves like the base model | Adapter not loaded, or wrong adapter path | Check that `PeftModel.from_pretrained` points to the saved adapter directory and that trainable parameters are non-zero |
| Shape or key mismatch on load | Adapter loaded onto a different base model or revision | Load the same base model ID and revision that was used for training |
| Merged model is slightly different from the adapter model | Merging into a quantized base introduces rounding error | Reload the base in 16-bit precision, then merge, instead of merging into the 4-bit weights |
| Merged model has no tokenizer or chat template | Only the model weights were saved | Save the tokenizer into the same directory |
| Output differs between training and serving | Different template or generation settings | Use the same template and compare generation settings, including temperature and EOS |
When you train with QLoRA, the safe path to a deployable model is to load the base in bfloat16 or float16, attach the saved adapter, then call merge_and_unload().
A short checklist before blaming LoRA
- Did you print and read one formatted training example?
- Does the label include the EOS token, and is the answer not truncated?
- Is loss computed on the answer tokens you intend?
- Is the trainable parameter count what you expect?
- Do you compare the adapter with the base model on the same held-out prompts?
- Did you change only one setting between runs?
Exercise
After fine-tuning, your model answers correctly but never stops generating, and sometimes writes a fake "user" message after its answer. Training loss and validation loss both looked healthy. Name the two most likely causes and how you would check each.
Show answer
The most likely causes are a chat template mismatch and a missing or wrong EOS token. Check the template by printing one training example with apply_chat_template(..., tokenize=False) and confirming that the same template, with add_generation_prompt=True, is used at inference. Check the EOS token by decoding the last tokens of a training example and comparing the token that closes an assistant turn with tokenizer.eos_token and the model's generation_config.eos_token_id. Truncation that cuts off the end of examples is a third thing to rule out.
Exercise
Training loss falls steadily for five epochs, but validation loss reaches its minimum at epoch two and then rises. List three changes you could make, and say which one you would try first.
Show answer
Options include stopping at two epochs and keeping the best checkpoint, lowering the rank, raising dropout, lowering the learning rate, and adding more or deduplicated data. Try the best-checkpoint option first. It costs nothing, it needs no new training run, and it directly targets the point where validation loss was lowest.
Exercise
You merge a QLoRA adapter into the 4-bit base model and the merged model's answers are slightly worse than the adapter model's. What went wrong and what is the better procedure?
Show answer
Merging adapter weights into quantized 4-bit weights adds rounding error. The better procedure is to load the base model in bfloat16 or float16, load the saved adapter onto it with PeftModel.from_pretrained, call merge_and_unload(), and save the result together with the tokenizer.