Fine-tuning & alignment: SFT, RLHF, DPO, LoRA/QLoRA
How a raw base model becomes a helpful assistant: supervised and instruction fine-tuning, reward models and RLHF, the simpler DPO, and parameter-efficient methods (LoRA, QLoRA) that let you fine-tune billion-parameter models on a single GPU.
A pretrained base model has absorbed an enormous amount of knowledge, but it only continues text: it does not reliably follow instructions, refuse harmful requests, or answer in your company’s format. Fine-tuning continues training on a smaller, targeted dataset. Three questions define any fine-tuning project: what data (demonstrations or preferences), what objective (cross-entropy, RL with a reward model, or DPO), and which parameters (all of them, or a small adapter via PEFT).
Stage 1 — Supervised fine-tuning (SFT) and instruction tuning
SFT trains on (prompt, ideal response) pairs, formatted with the model’s chat template, using the same next-token cross-entropy as pretraining — but the loss is usually computed only on the response tokens. Instruction tuning is SFT on a broad mix of tasks phrased as natural-language instructions; it teaches the model to generalize to instructions it never saw (shown by Google’s FLAN models). Quality beats quantity: a few thousand carefully written examples often matter more than millions of noisy ones.
- L_SFT(θ)
- supervised fine-tuning loss for model parameters θ
- −Σ_{t ∈ response}
- minus the sum over positions t that belong to the response (prompt positions are masked out)
- π_θ
- the model (called a policy), with parameters θ
- y_t
- the t-th token of the ideal response
- x
- the prompt
- y_<t
- the response tokens before position t
- log
- natural logarithm
▸Worked example
Stage 2 — RLHF: learning from human preferences
Writing perfect demonstrations is hard; judging which of two answers is better is much easier. Reinforcement learning from human feedback exploits this. The idea was shown by Christiano et al. on games and robotics[2] and scaled to language models in InstructGPT, where labelers preferred outputs of a 1.3B InstructGPT model over those of the 175B GPT-3[1].
- Collect comparisons: for each prompt, sample two or more answers from the SFT model; humans rank them (chosen y_w vs rejected y_l).
- Train a [[reward-model|reward model]] r_φ(x, y) — usually the LLM with a scalar head — so that preferred answers get higher scores.
- Optimize the policy with RL (typically PPO): generate answers, score them with the reward model, update the LLM to increase reward while a KL penalty keeps it close to the SFT reference model.
- L_RM(φ)
- Reward model loss for its parameters φ
- σ
- Sigmoid (logistic function): turns the score gap into a probability
- r_φ(x, y_w)
- scalar reward for the chosen (“winning”) answer y_w to prompt x
- r_φ(x, y_l)
- reward for the rejected (“losing”) answer y_l
- −log
- negative log: 0 when the probability is 1, large when it is near 0
▸Worked example
- max_θ
- choose the policy parameters θ that make the expression largest
- E_{x, y∼π_θ}
- expected value (average) over prompts x and answers y sampled (∼) from the current model
- r_φ(x, y)
- reward model score of answer y
- β
- strength of the KL penalty (e.g. 0.01–0.1)
- KL( π_θ(·|x) ‖ π_ref(·|x) )
- Kullback–Leibler divergence: how different the new model's answer distribution is from the reference model's (0 = identical)
- π_θ
- the policy being trained
- π_ref
- frozen reference model (the SFT model)
▸Worked example
DPO: preference tuning without RL
RLHF with PPO needs four models in memory (policy, reference, reward model, value function), online sampling and careful tuning. Rafailov et al. showed that the optimal policy of the KL-constrained objective can be written in closed form, so the reward model can be eliminated: Direct Preference Optimization trains directly on preference pairs with a simple classification-style loss[3]. It is stable, cheap and now very widely used; many variants follow the same recipe.
- L_DPO
- Direct Preference Optimization loss
- σ
- Sigmoid (logistic function)
- β
- how strongly the policy may deviate from the reference (e.g. 0.1)
- log π_θ(y_w|x)/π_ref(y_w|x)
- log of the ratio: how much more (or less) likely the trained model makes the chosen answer than the reference does
- log π_θ(y_l|x)/π_ref(y_l|x)
- the same ratio for the rejected answer
- y_w
- chosen answer
- y_l
- rejected answer
▸Worked example
| Method | Data | Models in memory | Pros / cons |
|---|---|---|---|
| SFT | Prompt + ideal answer | 1 | Simple, teaches format and skills; limited by the quality of demonstrations |
| RLHF (PPO) | Ranked answers → reward model | 4 (policy, ref, RM, value) | Powerful, can use online samples; complex, unstable, reward hacking risk |
| DPO | Pairs (prompt, chosen, rejected) | 2 (policy, ref) | Simple and stable; usually offline data, sensitive to β and data quality |
Parameter-efficient fine-tuning: LoRA and QLoRA
Full fine-tuning with Adam in mixed precision needs roughly 16 bytes per parameter (weights, gradients, fp32 master copy, two optimizer moments) — over 100 GB for a 7B model. LoRA freezes the pretrained weight W₀ and learns a low-rank update ΔW = B·A, based on the observation that fine-tuning updates have low “intrinsic rank”[4]. B starts at zero, so training begins exactly at the base model. After training the update can be merged into W₀ (no extra latency) or kept as a small, swappable adapter file.
- h
- output of the adapted layer (size d)
- W₀
- frozen pretrained weight matrix (d × k)
- x
- layer input (size k)
- α / r
- scaling factor; α is a hyperparameter (often 16 or 2r)
- B
- trainable “up” matrix, d × r, initialized to zeros so training starts exactly at W₀
- A
- trainable “down” matrix, r × k, initialized randomly
- ℝ^{d×r}
- real matrices with d rows and r columns
- r ≪ min(d, k)
- the rank r is much smaller (≪) than both dimensions, e.g. 8 vs 4096
▸Worked example
QLoRA goes further: the frozen base model is stored in 4-bit NormalFloat (NF4) with double quantization, while LoRA adapters train in 16-bit; paged optimizers absorb memory spikes. This made fine-tuning a 65B model possible on a single 48 GB GPU while matching 16-bit fine-tuning quality on the reported benchmarks[5]. In practice, QLoRA lets you adapt 7–8B models on a 16–24 GB consumer GPU.
Try this
- Set d = 4096 and r = 8: compare the full fine-tune count (d²) with LoRA (2dr) and read the “% trainable”. Then double r and see the trainable share double too — it grows linearly in r.
- In the heatmap demo, raise r from 1 upward: the reconstruction error of the 24×24 update drops fast for the first few ranks, then slowly. That “elbow” is why small ranks (8–16) usually suffice.
- Increase the number of adapted layers and watch the memory estimate: even adapting every attention and MLP matrix stays a tiny fraction of full fine-tuning.
- What it is
- Inner dimension of the update B·A: how expressive the adapter is.
- ↑ If you increase it
- More capacity to learn large or complex changes (new language, new domain); more trainable params and memory; higher risk of overfitting small datasets.
- ↓ If you decrease it
- Tiny adapters, fast training; may underfit if the task really differs from pretraining.
- Typical values
- 8–16 for style/format tasks; 32–64 for heavier domain adaptation.
- What it is
- Scaling factor: the update is multiplied by α/r. Acts like a learning-rate multiplier for the adapter.
- ↑ If you increase it
- Stronger effect of the adapter on outputs; too high can destabilize training.
- ↓ If you decrease it
- Weaker, more conservative updates; training may look stuck unless the learning rate is raised.
- Typical values
- α = r or α = 2r (e.g. r = 16, α = 32).
- What it is
- Which weight matrices receive LoRA adapters (e.g. q_proj, k_proj, v_proj, o_proj, and MLP gate/up/down projections).
- ↑ If you increase it
- Adapting all linear layers usually gives the best quality (QLoRA found this important), at more memory and compute.
- ↓ If you decrease it
- Attention-only (q, v) is lightest but may limit how much the model can change.
- Typical values
- All attention + MLP projections, or
"all-linear"in PEFT.
- What it is
- Step size of the optimizer during fine-tuning.
- ↑ If you increase it
- Faster adaptation; too high causes loss spikes and catastrophic forgetting of general skills.
- ↓ If you decrease it
- Safer, preserves base abilities; too low and the model barely changes.
- Typical values
- Full SFT: 1e-5–2e-5. LoRA/QLoRA: 1e-4–2e-4. DPO: ~5e-7–5e-6 full, higher with LoRA.
- What it is
- How many passes over the fine-tuning dataset.
- ↑ If you increase it
- Better fit of the target style; with small datasets the model starts memorizing answers verbatim and loses generality (watch validation loss).
- ↓ If you decrease it
- Less overfitting; may not fully absorb the format or knowledge.
- Typical values
- 1–3 epochs for SFT; 1 epoch is common for DPO.
- What it is
- How strongly the tuned policy is tied to the reference model in RLHF and DPO.
- ↑ If you increase it
- Stays closer to the reference: safer, less reward hacking, but smaller preference gains.
- ↓ If you decrease it
- Moves further toward preferred answers; risk of degenerate outputs (verbosity, repetition) and forgetting.
- Typical values
- DPO β ≈ 0.1 (range 0.01–0.5).
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
bnb = BitsAndBytesConfig(
load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16,
)
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb,
device_map="auto")
model = prepare_model_for_kbit_training(model)
lora = LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
)
model = get_peft_model(model, lora)
model.print_trainable_parameters() # typically well under 5% trainablefrom datasets import load_dataset
from trl import SFTConfig, SFTTrainer, DPOConfig, DPOTrainer
# sft.jsonl rows: {"messages": [{"role": "user", "content": "..."},
# {"role": "assistant", "content": "..."}]}
sft_ds = load_dataset("json", data_files="sft.jsonl", split="train")
sft = SFTTrainer(model=model, train_dataset=sft_ds, processing_class=tok,
args=SFTConfig(output_dir="out-sft", learning_rate=2e-4,
num_train_epochs=2, per_device_train_batch_size=4,
gradient_accumulation_steps=4))
sft.train()
# prefs.jsonl rows: {"prompt": "...", "chosen": "...", "rejected": "..."}
pref_ds = load_dataset("json", data_files="prefs.jsonl", split="train")
dpo = DPOTrainer(model=sft.model, train_dataset=pref_ds, processing_class=tok,
args=DPOConfig(output_dir="out-dpo", beta=0.1, learning_rate=5e-6,
num_train_epochs=1))
dpo.train()
dpo.model.save_pretrained("my-adapter") # only the small LoRA weights▸Go deeper: prompt, RAG or fine-tune?
- Start with prompting (cheapest, instant iteration). Build an evaluation set first.
- Add RAG when the model lacks knowledge that changes or is private.
- Fine-tune (LoRA) when you need a consistent format/style/tone, a narrow skill, shorter prompts, or a smaller cheaper model that imitates a bigger one on your task.
- Preference tuning (DPO) when “good vs bad” is easier to label than to write, e.g. helpfulness, tone, or safety behaviour.
The PEFT library documents LoRA and many other adapter methods (prefix tuning, IA³, DoRA) with runnable examples[6].
Quiz
References
- [1]Training language models to follow instructions with human feedback (InstructGPT)PaperOuyang et al.2022arxiv.org
- [2]Deep reinforcement learning from human preferencesPaperChristiano et al.2017arxiv.org
- [3]Direct Preference Optimization: Your Language Model is Secretly a Reward ModelPaperRafailov et al.2023arxiv.org
- [4]LoRA: Low-Rank Adaptation of Large Language ModelsPaperHu et al.2021arxiv.org
- [5]QLoRA: Efficient Finetuning of Quantized LLMsPaperDettmers et al.2023arxiv.org
- [6]PEFT documentationDocsHugging Facehuggingface.co