Home / AI & GenAI

AI & GenAITroubleshootingAdvanced

LoRA fine-tuning loss goes to NaN, drops to zero or never moves: precision, learning rate, label masking and chat templates

When a LoRA or QLoRA run shows NaN loss, suspiciously low loss or a flat curve, it is usually precision, learning rate, label masks or a chat template mismatch. This post covers how to tell which one and how to fix it.

Deepak Bhardwaj7 min read

Applies toHugging Face Transformers 4.40+, PEFT 0.10+, TRL 0.19+ (SFTTrainer/SFTConfig), bitsandbytes QLoRA, PyTorch 2.x on NVIDIA GPUs; argument names vary between TRL versions

Symptom

A LoRA or QLoRA supervised fine-tuning run shows one of four patterns:

  • loss: nan or inf, either from step 1 or after a few hundred steps.
  • Loss falls to near 0.0 within the first epoch.
  • Loss stays flat and grad_norm is 0 or tiny.
  • Training looks healthy, but the served adapter behaves like the base model, never stops generating, or ignores the instructions it was trained on.

Each pattern has a different cause. Read the training log before you change any hyperparameter.

Map the symptom to a cause

Symptom Most likely cause Check Fix
NaN from the first steps fp16 on a model trained in bf16, overflowing activations fp16=True in config Use bf16=True on Ampere or newer
NaN after many steps, grad_norm spikes first Learning rate too high, no warm-up Plot grad_norm Lower the LR, add warm-up, keep max_grad_norm=1.0
NaN on some batches only Every label in the batch is -100 (nothing to average) Count unmasked labels per batch Fix truncation and masking, drop empty examples
Loss near 0 very fast Duplicated or leaked examples, or loss computed on a templated prompt that is easy to predict Dedupe, inspect the mask Dedupe, train on completions only
Flat loss, grad_norm 0 No trainable parameters, or gradient checkpointing breaks the graph print_trainable_parameters() Fix target_modules, enable input grads
Adapter acts like base model Adapter not loaded, wrong modules, or tiny LR/rank Diff outputs with and without adapter Verify load path and modules
Model never stops at inference EOS masked out or pad token = EOS with labels removed Inspect the final label tokens Keep EOS in the labels
Good eval offline, bad when served Training and serving chat templates differ Render both templates Use the same template in both

Checks

1. Confirm what is actually trainable

from peft import LoraConfig, get_peft_model

cfg = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                 target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
                 task_type="CAUSAL_LM")
model = get_peft_model(base_model, cfg)
model.print_trainable_parameters()

If the trainable percentage is 0, or much lower than you expect, the module names don't match the architecture. Module names vary by model family. List the real ones:

import torch.nn as nn
names = {n.split(".")[-1] for n, m in base_model.named_modules() if isinstance(m, nn.Linear)}
print(sorted(names))

Recent PEFT versions also accept target_modules="all-linear". Check that your installed version supports it.

2. Inspect label masks on real batches

Most "mysterious" NaNs and flat curves come from the data collator, not the optimizer. Pull batches from the trainer's own dataloader and count the tokens that contribute to the loss:

dl = trainer.get_train_dataloader()
for i, batch in zip(range(50), dl):
    labels = batch["labels"]
    active = (labels != -100).sum(dim=1)
    if (active == 0).any():
        print(f"batch {i}: {int((active == 0).sum())} examples with no trainable tokens")
    print(i, active.tolist()[:8])

Examples with zero active tokens usually mean one of two things. Either the prompt is longer than max_length, so the assistant turn was truncated away, or the completion-only mask failed to find the assistant marker. With packing=True and very long prompts, this can hit a whole batch, and the mean loss over zero tokens becomes NaN.

Fix it at the data stage:

def fits(example, tok, max_len=4096):
    ids = tok.apply_chat_template(example["messages"], tokenize=True)
    return len(ids) <= max_len

ds = ds.filter(lambda ex: fits(ex, tokenizer))

3. Decode what the model is trained to predict

Print the supervised tokens for a few examples:

b = next(iter(dl))
ids, labels = b["input_ids"][0], b["labels"][0]
print(tokenizer.decode(ids[labels != -100]))

You should see only assistant text, ending with the end-of-turn or EOS token. If you see system prompts and user turns, you are training on the prompt. That is the usual reason for a loss that falls very fast while quality does not improve. If the end token is missing, the served model will run until max_tokens.

Warning

A common trap is setting tokenizer.pad_token = tokenizer.eos_token. Collators that mask every pad token with -100 then mask the real EOS as well, so the model never learns to stop. Use a dedicated pad token if the tokenizer has one, or check that the final EOS stays unmasked.

4. Check precision and stability settings

from trl import SFTConfig

args = SFTConfig(
    output_dir="out",
    bf16=True,                    # not fp16 for bf16-native models
    learning_rate=1e-4,           # LoRA tolerates more than full FT; start 5e-5 to 2e-4
    warmup_ratio=0.03,
    lr_scheduler_type="cosine",
    max_grad_norm=1.0,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=8,
    logging_steps=10,
    max_length=4096,              # older TRL versions call this max_seq_length
    assistant_only_loss=True,     # needs a chat template with generation markers
    gradient_checkpointing=True,
    gradient_checkpointing_kwargs={"use_reentrant": False},
)

grad_norm appears in the Trainer logs. A rising grad_norm a few dozen steps before the NaN means the LR or warm-up is the problem, not the data.

For QLoRA, set the 4-bit compute dtype to bf16 and prepare the model before you wrap it:

import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import prepare_model_for_kbit_training

bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                         bnb_4bit_compute_dtype=torch.bfloat16)
base_model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb)
base_model = prepare_model_for_kbit_training(base_model)

5. Flat loss with gradient checkpointing

If training raises element 0 of tensors does not require grad and does not have a grad_fn, or runs with grad_norm stuck at 0, the frozen embeddings are cutting the graph under reentrant checkpointing. Use use_reentrant: False as above, or call base_model.enable_input_require_grads() before get_peft_model.

6. Find the first bad step

Use these when a NaN appears late and you need the layer responsible:

import torch
torch.autograd.set_detect_anomaly(True)   # slow; use on a short repro only

Alternatively, resume from the last checkpoint before the NaN with logging set to every step, and save the batch indices. If the same batch produces NaN again, the batch is the problem (empty labels, corrupt text, or extreme length). If it doesn't, the cause is numerical.

Adapter trained fine but serving looks wrong

Compare the base model and base-plus-adapter on the same prompts with greedy decoding:

from peft import PeftModel
tuned = PeftModel.from_pretrained(base_model, "out/checkpoint-best")
msgs = [{"role": "user", "content": "Classify: disk latency 400 ms on db01"}]
ids = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt").to(tuned.device)
with tuned.disable_adapter():
    print("base :", tokenizer.decode(tuned.generate(ids, max_new_tokens=40, do_sample=False)[0][ids.shape[1]:]))
print("tuned:", tokenizer.decode(tuned.generate(ids, max_new_tokens=40, do_sample=False)[0][ids.shape[1]:]))

If the outputs are identical, the adapter is not doing anything. Check the adapter path, check adapter_config.json for target_modules and r, and check that the serving engine loaded the adapter under the name the client calls. In vLLM, the model field must be the adapter name, not the base model name.

If the outputs differ here but not in production, render the serving engine's prompt and compare it byte for byte with apply_chat_template output from training. Different system prompts, missing BOS tokens or a different template version are enough to undo a narrow fine-tune.

Caution

Don't merge an adapter into the base weights and overwrite the original checkpoint until the merged model passes the same evaluation set. Merging into a quantized base can also lose quality. Merge into the full-precision base, then quantize.

Prevent it next time

  • Run a pre-flight script on every dataset: token length distribution, count of examples with zero supervised tokens, duplicate rate, and a decoded sample of the labels.
  • Log grad_norm, learning rate and supervised token count per step, and alert the run on NaN instead of discovering it in the morning.
  • Pin Transformers, PEFT, TRL and bitsandbytes versions in the training image, because argument names and defaults change.
  • Store the chat template with the adapter and test it against the serving engine as part of the release gate.
  • Keep a fixed evaluation set that compares base and tuned models, and block deployment if the adapter doesn't beat the base model.