AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
✎Large Language Models
  1. Tokenization: how text becomes numbers
  2. How LLMs work: next-token prediction at scale
  3. Decoding: greedy, beam search, temperature, top-k, top-p
  4. Scaling laws: parameters, data and compute
  5. Fine-tuning & alignment: SFT, RLHF, DPO, LoRA/QLoRA
  6. Prompting: zero-shot, few-shot, chain-of-thought, structured output
  7. Retrieval-Augmented Generation (RAG)
  8. Agents & tool use: ReAct, function calling, MCP
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Large Language Models

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.

Advanced~28 min·6 references
Key terms
Fine-tuningInstruction tuningRLHF (Reinforcement Learning from Human Feedback)Reward modelDPO (Direct Preference Optimization)PEFT (Parameter-Efficient Fine-Tuning)LoRA (Low-Rank Adaptation)

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).

≈
Analogy: training a brilliant new graduate
The base model is a graduate who has read every book but never worked. SFT is shadowing: “here is a request, here is how a senior colleague answered it.” Preference tuning is a manager’s feedback: “of these two drafts, this one is better.” LoRA is giving them a small notebook of adjustments instead of rewriting their entire education — cheap, removable, and swappable per job.

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(θ) = −Σ_{t ∈ response} log π_θ(y_t | x, y_<t)
Cross-entropy on response tokens only; the prompt tokens are masked out of the loss.
In words: The usual next-token cross-entropy, but summed only over the tokens of the ideal response: the model is graded on how well it writes the answer, not on predicting the prompt it was given.
Symbols(hover a symbol in the formula)
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
Prompt “Ibukota Prancis?” (not scored), response “Paris .” + end token, 3 tokens Model probabilities of the correct tokens: 0.9, 0.6, 0.8 L = −(ln 0.9 + ln 0.6 + ln 0.8) = 0.1054 + 0.5108 + 0.2231 = 0.8393 Training raises those probabilities, mostly the weakest one (0.6).

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].

  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).
  2. Train a [[reward-model|reward model]] r_φ(x, y) — usually the LLM with a scalar head — so that preferred answers get higher scores.
  3. 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(φ) = −log σ( r_φ(x, y_w) − r_φ(x, y_l) )
Bradley–Terry loss: the chosen answer should out-score the rejected one.
In words: The reward model scores both answers; the sigmoid of the score difference is its probability that the human-preferred answer is better. The loss is small when the chosen answer clearly out-scores the rejected one, and large when the order is wrong.
Symbols(hover a symbol in the formula)
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
Correct order: r(y_w) = 1.5, r(y_l) = 0.5 → σ(1.0) = 0.7311 → loss = 0.3133 Wrong order: r(y_w) = 0.5, r(y_l) = 1.5 → σ(−1.0) = 0.2689 → loss = 1.3133 Only the difference matters: adding 10 to both rewards changes nothing.
max_θ E_{x, y∼π_θ} [ r_φ(x, y) ] − β · KL( π_θ(·|x) ‖ π_ref(·|x) )
The RLHF objective. The KL term stops the model from drifting into gibberish that fools the reward model (reward hacking).
In words: Change the model so that the answers it generates get high reward on average, but pay a price for drifting away from the reference (SFT) model. β sets the exchange rate between reward and staying close.
Symbols(hover a symbol in the formula)
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
One sampled answer: reward r = 2.0 log π_θ(y|x) = −10, log π_ref(y|x) = −12 → per-sample KL estimate = −10 − (−12) = 2 β = 0.1 → penalty 0.1 · 2 = 0.2 → effective reward 2.0 − 0.2 = 1.8 If the policy drifted much further (KL = 30), the penalty 3.0 would wipe out the reward.
Loading interactive…
InstructGPT's three steps side by side. Walk through them and notice how the SFT model is reused: it generates the answers humans rank (step 2), and it is both the starting point and the frozen KL reference for PPO (step 3). The last step shows how DPO skips the reward model and the RL loop.

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 = −log σ( β · [ log π_θ(y_w|x)/π_ref(y_w|x) − log π_θ(y_l|x)/π_ref(y_l|x) ] )
Increase the chosen answer’s likelihood relative to the reference model, decrease the rejected one’s. β controls how far the policy may move.
In words: For each preference pair, measure how much the model has raised the chosen answer's probability relative to the reference, minus the same for the rejected answer. The loss pushes that margin up — it is the reward-model loss with the policy itself acting as an implicit reward model.
Symbols(hover a symbol in the formula)
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
β = 0.1. Chosen: log π_θ = −20, log π_ref = −22 → +2. Rejected: log π_θ = −25, log π_ref = −24 → −1 Margin = 2 − (−1) = 3 → β · 3 = 0.3 → σ(0.3) = 0.5744 → loss = 0.5544 At the start (π_θ = π_ref) the margin is 0 → σ(0) = 0.5 → loss = ln 2 = 0.6931.
MethodDataModels in memoryPros / cons
SFTPrompt + ideal answer1Simple, teaches format and skills; limited by the quality of demonstrations
RLHF (PPO)Ranked answers → reward model4 (policy, ref, RM, value)Powerful, can use online samples; complex, unstable, reward hacking risk
DPOPairs (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 = W₀x + (α / r) · B A x, B ∈ ℝ^{d×r}, A ∈ ℝ^{r×k}, r ≪ min(d, k)
Trainable parameters per matrix: r(d + k) instead of d·k. For d = k = 4096 and r = 8: 65,536 vs 16.8M (≈ 0.4%).
In words: Keep the pretrained weight W₀ frozen and add a small trainable detour: A squeezes the input down to r numbers, B expands it back, and α/r scales the result. Only A and B are trained, so the update B·A has rank at most r.
Symbols(hover a symbol in the formula)
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
Toy: d = k = 2, r = 1, α/r = 1, W₀ = I, B = [1; 2], A = [0.5, 0], x = [2, 1] A x = 0.5·2 + 0·1 = 1.0 → B·1.0 = [1, 2] → h = [2, 1] + [1, 2] = [3, 3] Real size: d = k = 4,096, r = 8 → A and B have 8 · (4,096 + 4,096) = 65,536 parameters vs 16,777,216 in W₀ (0.39%).

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.

Loading interactive…
Parameter counts and a real low-rank approximation of an update matrix.

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.
knobr (LoRA rank)
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.
knoblora_alpha (α)
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).
knobtarget_modules
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.
knoblearning_rate (fine-tuning)
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.
knobnum_train_epochs
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.
knobβ (KL coefficient / DPO beta)
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).
python
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% trainable
QLoRA setup with transformers + bitsandbytes + PEFT.
python
from 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
SFT then DPO with Hugging Face TRL (dataset formats shown in comments).
!
Common pitfalls
(1) Fine-tuning to add facts: it is unreliable and goes stale — use RAG for knowledge, fine-tuning for behaviour, style and format. (2) Wrong chat template at training vs inference time silently ruins results. (3) Catastrophic forgetting: too high a learning rate or too many epochs erodes general skills; keep a general eval set. (4) Overfitting tiny datasets: watch validation loss and sample outputs, not just training loss. (5) Reward hacking: models learn to be verbose or flattering if the reward model or preference data rewards that. (6) Check the base model’s licence and your data’s rights before training.
▸Go deeper: prompt, RAG or fine-tune?
  1. Start with prompting (cheapest, instant iteration). Build an evaluation set first.
  2. Add RAG when the model lacks knowledge that changes or is private.
  3. 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.
  4. 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

1.
In the RLHF pipeline, what does the reward model learn from?
2.
What is the main practical advantage of DPO over PPO-based RLHF?
3.
A weight matrix is 4096 × 4096. How many trainable parameters does a LoRA adapter with r = 16 add to it?
4.
You lower DPO’s β from 0.1 to 0.01. What is the most likely effect?
5.
What makes QLoRA use so much less GPU memory than ordinary LoRA?
Score: 0/5

References

  1. [1]
    Training language models to follow instructions with human feedback (InstructGPT)
    PaperOuyang et al.2022arxiv.org
  2. [2]
    Deep reinforcement learning from human preferences
    PaperChristiano et al.2017arxiv.org
  3. [3]
    Direct Preference Optimization: Your Language Model is Secretly a Reward Model
    PaperRafailov et al.2023arxiv.org
  4. [4]
    LoRA: Low-Rank Adaptation of Large Language Models
    PaperHu et al.2021arxiv.org
  5. [5]
    QLoRA: Efficient Finetuning of Quantized LLMs
    PaperDettmers et al.2023arxiv.org
  6. [6]
    PEFT documentation
    DocsHugging Facehuggingface.co
← Previous
Scaling laws: parameters, data and compute
Next →
Prompting: zero-shot, few-shot, chain-of-thought, structured output