Fine-Tuning and Alignment Training for LLMs: A Practical Guide to Avoiding Common Pitfalls
This article provides a practical, workflow-oriented guide to supervised fine-tuning (SFT) and alignment training for large language models. It covers verification of new model adaptations, correct implementation of gradient accumulation, memory-saving fine-tuning techniques, a comparison of DPO, PPO, GRPO, and RLOO, and monitoring strategies for reinforcement learning training. The content includes checklists, code snippets, and troubleshooting tables to help practitioners reproduce reliable results.
Introduction
When deploying large language models, supervised fine-tuning (SFT) and alignment training based on feedback are two fundamental capabilities that teams need to master. Full-parameter fine-tuning places high demands on GPU memory, and reinforcement learning training involves many implementation details. What makes these problems more troublesome is that errors often manifest as a normal decrease in loss while the model’s actual performance remains incorrect, making debugging costly.
This article is organized according to the training workflow: first verify that the new model is correctly adapted, then check gradient accumulation, choose memory-saving strategies and alignment algorithms, and finally monitor the reinforcement learning training process.
The memory and throughput conclusions mentioned in this article depend on the specific framework, model size, sequence length, and hardware. No universal performance gains are provided. Code is based on standard PyTorch 2.x interfaces. Before running anything, use the self-check script in Section 2 to confirm that your environment behaves as expected.
1. New Model Adaptation Verification Checklist
When a new base model architecture is released, fine-tuning frameworks usually require an adaptation period. During this phase, the following types of issues are most common:
- Inconsistent handling of special tokens, causing misalignment between labels and inputs.
- Different semantics of attention masks across implementations (e.g., padding on the left vs. right), leading to abnormal loss values.
- RoPE positional encoding parameters (e.g.,
rope_theta,rope_scaling) not matching the model configuration file. - Normalization layer
epsnot matching the configuration. - Different chat templates used during training versus inference.
After checking each item, you can use the checklist below:
- bos, eos, pad tokens match the model configuration; embedding size adjusted after adding new tokens.
- Labels are shifted right by one position (next-token prediction) and prompt parts are set to
-100. - Padding direction aligns with the framework’s mask semantics; valid positions in the mask have value 1.
-
rope_thetaandrope_scalingmatch the model configuration file. - RMSNorm or LayerNorm
epsmatches the configuration. - The same chat template is used for training and inference.
Initial loss is a very direct signal. For a randomly initialized model, the cross-entropy initial value is close to ln V, where V is the vocabulary size. For example, if the vocabulary size is 32,000, ln(32000) ≈ 10.4. For a model already loaded with pretrained weights, the initial loss should be significantly lower than this value. If the initial loss is close to ln V, first suspect that the weights were not loaded or that labels are misaligned.
It is recommended to debug in the following order rather than investing more compute immediately:
- Print 10 samples to confirm that the target text being trained is indeed the expected content.
- Check the magnitude of the initial loss.
- Run the first 50 steps on the same data with the old version of the framework and compare the loss curves.
- Record step, loss, number of valid tokens, learning rate, and gradient norm at each step.
The following function can be used to inspect label content:
def inspect_batch(tokenizer, batch, n=2):for i in range(n):lab = batch["labels"][i]valid = lab != -100print("Valid label count:", int(valid.sum()))print("Target text being trained:", tokenizer.decode(lab[valid].tolist()))
2. Correct Implementation of Gradient Accumulation
Gradient accumulation sums gradients over multiple micro-batches to simulate a larger batch size. A common approach is to first average the loss for each micro-batch, then divide by the number of accumulation steps. This approach is equivalent to training with a larger batch only when the number of valid tokens in each micro-batch is identical.
In variable-length sequence scenarios, this premise often does not hold. Language models compute loss per token. After removing padding and masked labels, the number of valid tokens per micro-batch can vary significantly.
Consider a simple example. Micro-batch A has 10 valid tokens, and micro-batch B has 90 valid tokens. In a full batch, each token should have the same weight, i.e., 1/100. If you first average each micro-batch and then sum them, each token in A gets a weight of 1/(2×10) = 0.05, which is 5 times larger than the correct value. Tokens in B are then underestimated.
Therefore, the correct approach is:
Full-batch gradient = (sum of per-token losses over all valid tokens in the entire accumulation group) / (total number of valid tokens in the entire accumulation group)
The specific steps are: first count the total number of valid tokens in the entire accumulation group; each micro-batch uses the per-token summed loss, divides by the total count, and backpropagates; after all micro-batches, perform gradient clipping and optimizer step.
The following code assumes that ignored positions in labels have the value -100, which is the default convention in PyTorch’s cross-entropy function:
import torchimport torch.nn.functional as FIGNORE_INDEX = -100 # Default ignore value in PyTorch's cross_entropydef sum_loss_and_count(logits, labels):# logits: [B, T, V], labels: [B, T], already aligned for next-token predictionvocab = logits.size(-1)loss_sum = F.cross_entropy(logits.reshape(-1, vocab),labels.reshape(-1),ignore_index=IGNORE_INDEX,reduction="sum",)n_valid = (labels != IGNORE_INDEX).sum()return loss_sum, n_validdef count_valid_tokens(micro_batches):# Single-GPU scenario. For multi-GPU, perform all_reduce(SUM) on this count to get the global total.return sum(int((mb["labels"] != IGNORE_INDEX).sum()) for mb in micro_batches)def accumulate_grads(model, micro_batches, world_size=1):# world_size: DDP averages gradients across GPUs; set to 1 for single GPU.n_total = count_valid_tokens(micro_batches)model.zero_grad(set_to_none=True)loss_total = 0.0for mb in micro_batches:logits = model(mb["input_ids"])loss_sum, _ = sum_loss_and_count(logits, mb["labels"])(loss_sum * world_size / n_total).backward()loss_total += loss_sum.item()return loss_total / n_totaldef train_step(model, optimizer, micro_batches, max_norm=1.0, world_size=1):loss = accumulate_grads(model, micro_batches, world_size)torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)optimizer.step()optimizer.zero_grad(set_to_none=True)return loss
Three important points for multi-GPU training:
- The total number of valid tokens must be the global total, i.e., all_reduce(SUM) over the counts from each GPU.
- DDP averages gradients across GPUs, so the
world_sizefactor in the code cancels out this averaging. - All micro-batches except the last one should be executed inside
model.no_sync()context; only the last micro-batch triggers gradient synchronization.
Gradient clipping must be applied to the complete gradient after the entire accumulation group finishes, not after each micro-batch.
The following script verifies the correctness of the implementation. It computes gradients from the same batch of data using both full-batch and accumulation methods, then compares the relative error:
def grad_vector(model):grads = [p.grad.detach().flatten() for p in model.parameters() if p.grad is not None]return torch.cat(grads)def check_grad_equivalence(model, full_batch, micro_batches, rel_tol=1e-5):# Disable dropout and use float32 before checking. After the check, restore model.train().model.eval()model.zero_grad(set_to_none=True)loss_sum, n = sum_loss_and_count(model(full_batch["input_ids"]), full_batch["labels"])(loss_sum / n).backward()g_ref = grad_vector(model).clone()accumulate_grads(model, micro_batches)g_acc = grad_vector(model).clone()model.train()rel_err = ((g_ref - g_acc).norm() / g_ref.norm().clamp_min(1e-12)).item()print(f"Relative error: {rel_err:.3e}")assert rel_err < rel_tol, "Gradient mismatch; check ignore_index, token count, and world_size."return rel_err
In float32, you can start with rel_tol = 1e-5. If using bf16 or with larger models, the error naturally increases; adjust the threshold based on actual measurements. The full batch and the micro-batches must be constructed from the same set of samples; otherwise, the comparison is meaningless.
When self-checking, you can verify each item in the table below:
| Check Item | Pass Condition | Action on Failure |
|---|---|---|
| Relative error | Less than the set threshold | Check valid token count and ignore_index |
| Total valid tokens | Equal to sum of valid tokens in all micro-batches | Check if labels contain unexpected tokens |
| Multi-GPU count | Has been globally all_reduced | Add all_reduce and confirm world_size factor |
| Gradient clipping location | After the accumulation group finishes | Move clipping outside the accumulation loop |
| Training mode | Restored after check | Call model.train() after the check function |
3. Common Techniques for Low-Memory Fine-Tuning
When GPU memory is insufficient, several common techniques can be considered. They can be combined, but the benefit of each should be measured in your own environment.
| Technique | Primary Purpose | Impact on Memory | Impact on Throughput | Main Risk or Prerequisite |
|---|---|---|---|---|
| Mixed precision (bf16) | Use low precision for forward/backward | Reduces activation and weight memory | Usually increases, depends on hardware | Requires hardware support for bf16; check numerical range |
| Gradient checkpointing | Recompute activations during backward, do not store all activations | Significantly reduces activation memory | Usually decreases due to recomputation | Training time increases; measure empirically |
| LoRA | Freeze base model, train only low-rank adapters | Greatly reduces optimizer state and gradients | Depends on implementation | Expressiveness limited by rank; choose appropriate rank and target layers |
| QLoRA | Quantize base model to 4-bit, train LoRA on top | Further reduces weight memory | Usually decreases due to dequantization overhead | Quantization error may affect quality; compare with full-precision baseline |
| AdaLoRA | Dynamically allocate rank across layers during training | Similar to LoRA | Slight overhead | Higher implementation complexity; benefits need measurement |
| ZeRO or FSDP | Shard parameters, gradients, optimizer states across GPUs | Reduces per-GPU memory depending on sharding stage | Adds communication overhead | Depends on multi-GPU interconnect bandwidth; complex configuration |
Selection guidance:
- If a single GPU lacks memory for full fine-tuning, prefer LoRA, and consider adding gradient checkpointing if necessary.
- If a single GPU cannot even hold the model weights, consider QLoRA.
- For multi-GPU full-parameter training, consider ZeRO or FSDP.
Regardless of the method, always run a small-scale experiment first, record peak memory usage and tokens processed per second, and then decide whether to scale up.
4. Selecting Among DPO, PPO, GRPO, and RLOO
In alignment training, the four common algorithms differ mainly in: whether online sampling is required, whether a reward model is needed, whether a value network (critic) is needed, and whether a reference model is required. The table below shows typical settings for common implementations; actual implementations may vary.
| Method | Online Sampling | Reward Model Needed | Value Network Needed | Reference Model Needed | Typical Data Form | Main Risks |
|---|---|---|---|---|---|---|
| DPO | No, uses offline preference pairs | No, optimizes directly on preference pairs | No | Yes | A good and a bad response for the same prompt | Quality of preference data determines upper bound; beta setting affects stability |
| PPO | Yes | Yes | Yes | Usually needed for KL constraint | Set of prompts plus reward signal | Multiple models reside simultaneously; highest memory and engineering complexity |
| GRPO | Yes | Can use rule-based reward or reward model | No, uses group-relative advantage instead | Usually needed | A group of responses sampled per prompt | When intra-group reward variance is small, advantage signal is weak |
| RLOO | Yes | Can use rule-based reward or reward model | No, uses leave-one-out group mean as baseline | Depends on implementation | Multiple responses sampled per prompt | With too few samples, baseline estimate has high variance |
Selection principles:
- If you only have offline preference data and want a simple pipeline, choose DPO.
- If you have a well-trained reward model and sufficient compute, PPO remains a reliable choice.
- If rewards can be determined by rules (e.g., automated answer verification), GRPO or RLOO are more suitable because they eliminate the value network.
- If sampling cost is high, prefer offline methods or reduce the number of samples per prompt, but be aware of baseline estimation quality.
Regardless of the method, first confirm on a small dataset that the reward function or preference data direction is correct, then scale up training.
5. Monitoring and Troubleshooting RL Training
In reinforcement learning training, the loss value alone does not indicate whether training is progressing correctly. You should also record the following metrics:
| Metric | Meaning | Abnormal Signals | Common Causes |
|---|---|---|---|
| KL divergence | Difference between current policy and reference model | Continuously rising rapidly | Learning rate too high, or KL coefficient too small |
| Reward mean | Average reward of sampled responses | Rising too fast but quality not improving | Reward hacking, i.e., the reward being exploited |
| Reward variance | Variance of rewards within the same group | Near zero for a long time | Insufficient sample diversity, or reward not discriminative |
| Response length | Average number of tokens in generated responses | Continuously increasing or suddenly decreasing | Length bias, or reward correlated with length |
| Entropy | Uncertainty of policy output distribution | Drops very quickly to low values | Premature convergence, loss of diversity |
| Gradient norm | Gradient magnitude before clipping | Sudden increase or NaN | Learning rate too high, or numerical overflow |
| Clip fraction | Proportion of samples clipped in PPO or GRPO | Persistently high | Single update step too large |
The following function records metrics at each step and halts immediately if NaN appears:
import mathdef rl_log_metrics(step, stats, logger):record = {"step": step,"kl": stats["kl"],"reward_mean": stats["rewards"].mean().item(),"reward_std": stats["rewards"].std().item(),"resp_len_mean": stats["resp_len"].float().mean().item(),"entropy": stats["entropy"],"grad_norm": stats["grad_norm"],}bad = [k for k, v in record.items() if isinstance(v, float) and math.isnan(v)]if bad:raise RuntimeError(f"NaN fields at step {step}: {bad}. Stop training and inspect logs.")logger.log(record)return record
Troubleshooting order:
- If NaN appears: first check the numerical range of bf16 or fp16, then check for log(0) in log-probability calculations, and finally lower the learning rate.
- If out-of-memory (OOM): first reduce the number of samples per step or sequence length, then enable gradient checkpointing, and finally consider ZeRO or FSDP.
- If KL keeps rising: lower the learning rate or increase the KL coefficient, and verify that the reference model was loaded correctly.
- If reward rises but response quality drops: check whether the reward function can be exploited by reward hacking, and manually sample responses for review.
- If response length continuously grows: check whether the reward correlates with length; if so, add length penalties or truncation rules.
- If reward stays unchanged for a long time: verify the reward function inputs and outputs, and ensure the sampled responses have sufficient diversity.
All thresholds should be set based on your own baseline; do not directly adopt values from other environments.
