Slides · Evaluation and model adaptation

Fine-tuning methods: SFT, LoRA, QLoRA and DPO

Fine-tuning methods: SFT, LoRA, QLoRA and DPO

How a model is trained in stages, and how to adapt one cheaply when you cannot retrain all of it.

Concept

Mechanism first, then the bill

  • Last lesson: whether to fine-tune. This one: how.
  • Interviews and design reviews ask two things: what is the method doing, and what does it cost in memory and hardware?
  • The stages tell you which data to collect. The arithmetic tells you what you can afford.

Diagram

A model is trained in stages

Diagram: Going down the left path, raw text trains pretraining, instruction pairs train SFT, and comparisons train preference tuning.

1 Pretraining
raw text

2 SFT
prompt + ideal response

3 Preference tuning
preferred vs rejected

Model you use

Large model outputs

4 Distillation

Small narrow-task model

Diagram summary: Going down the left path, raw text trains pretraining, instruction pairs train SFT, and comparisons train preference tuning. Distillation is a separate path that trains a small model on a large model’s outputs.

Compare

Which data, which lesson learned

StageData it usesWhat it teaches
PretrainingA huge text corpusLanguage ability and most world knowledge, via next-token prediction
SFT(prompt, ideal response) pairsFollow instructions in a format, style or task routine
RLHFHuman preference pairs, then a reward modelPrefer better over worse answers, via reinforcement learning
DPOPreference pairs directlyThe same preferences, with a classification-style loss
DistillationA large model’s outputsA small model keeping a narrow task’s quality at lower cost

Compare

What one record looks like (invented examples)

StageOne training record
SFTprompt: “Classify: ‘My card was charged twice.’” response: “billing”
Preferenceprompt: “My phone battery is swollen. What should I do?”; preferred: “Stop using it, do not charge or puncture it, and take it to a repair or recycling point.”; rejected: “It is probably fine; keep using it unless it gets hot.”
  • An SFT record holds one answer to imitate.
  • A preference record holds a prompt plus a ranked pair, so the model learns which of two answers is better.

Diagram

RLHF versus DPO

Diagram: Both start from the same preference pairs, shown at the top.

input to loss

Preference pairs

RLHF: train a
reward model

Optimise with RL (PPO)
+ KL penalty to SFT model

DPO: train directly,
classification-style loss

Frozen reference
copy of the model

Diagram summary: Both start from the same preference pairs, shown at the top. Going down the left branch, RLHF fits a reward model and then optimises with reinforcement learning under a KL penalty to the SFT model. The right branch is DPO, which skips both and trains directly; a frozen reference copy of the model (dotted line) is an input to its loss.

Sources1 Training language models to follow instructions with human feedback2 Direct Preference Optimization: Your Language Model is Secretly a Reward Model

Concept

RLHF in InstructGPT

  • Step 1: supervised fine-tuning on labeller demonstrations (SFT).
  • Step 2: labellers rank model outputs, and a reward model learns to predict which one people prefer.
  • Step 3: the SFT policy is optimised against that reward with PPO.
  • At each token the objective also charges a KL penalty relative to the SFT model, which the authors add to limit over-optimisation of the reward model.

The cost: two extra training pieces, a reward model and a reinforcement-learning loop.

Source1 Training language models to follow instructions with human feedback

Math

DPO’s loss in one line

L=−E[log⁡σ(β(log⁡pθ(yw∣x)pref(yw∣x)−log⁡pθ(yl∣x)pref(yl∣x)))]L = -\mathbb{E}\left[ \log \sigma\left( \beta \left( \log \frac{p_\theta(y_w \mid x)}{p_{\mathrm{ref}}(y_w \mid x)} - \log \frac{p_\theta(y_l \mid x)}{p_{\mathrm{ref}}(y_l \mid x)} \right) \right) \right]
SymbolMeaning
xxThe prompt
ywy_w, yly_lThe preferred (winning) and rejected (losing) responses
pθp_\thetaThe model being trained
prefp_{\mathrm{ref}}The frozen reference model, the starting point
β\betaControls how far the model may move from the reference
σ\sigmaSquashes (sigmoid) the margin into a probability, giving a classification-style loss

Reading it: the gap between the two log-ratios widens. The TRL docs note that in practice this is typically achieved by pushing the rejected response down rather than lifting the preferred one. No reward model and no RL loop.

Sources2 Direct Preference Optimization: Your Language Model is Secretly a Reward Model3 DPO Trainer (TRL documentation)

Concept

LoRA: a removable overlay

  • Full fine-tuning rewrites the whole textbook.
  • LoRA leaves the textbook frozen and learns a small correction for each page.
  • Only the overlay is trained, so you can store many overlays and swap them.
  • The overlay is not literal extra text: the correction is a matrix added to a weight matrix.

Math

The LoRA update

y=Wx+αrBAxy = Wx + \frac{\alpha}{r} BAxW:d×k (frozen)B:d×r (trainable)A:r×k (trainable)r≪min⁡(d,k)W : d \times k \ \text{(frozen)} \qquad B : d \times r \ \text{(trainable)} \qquad A : r \times k \ \text{(trainable)} \qquad r \ll \min(d, k)trainable weights=dr+rk\text{trainable weights} = dr + rk
SymbolMeaning
WWThe pretrained weight matrix, frozen
AA, BBThe small trainable matrices; ΔW=BA\Delta W = BA
rrThe rank, much smaller than dd and kk
α\alphaA constant that scales the update

At the start, A is random Gaussian and B is zero, so ΔW is zero and training begins from the original model.

Source4 LoRA: Low-Rank Adaptation of Large Language Models

Diagram

Two parallel paths, summed

Diagram: Going down, the input feeds the frozen weight matrix and, in parallel, the small trainable pair A then B.

Input x

Frozen W

Down-project A
r x k

Up-project B
d x r

+

Output y

Diagram summary: Going down, the input feeds the frozen weight matrix and, in parallel, the small trainable pair A then B. The two outputs are added to give the layer output.

Source4 LoRA: Low-Rank Adaptation of Large Language Models

Concept

Why keeping W frozen is the saving

  • No gradients or optimiser state are kept for the big matrix; only A and B are updated.
  • The authors estimate VRAM falls by up to two thirds when training with Adam and r is far below the model dimension, because optimiser state is not kept for the frozen weights.
  • For GPT-3 175B the authors report a checkpoint shrinking from 350 GB to 35 MB (r=4r = 4, query and value matrices only).
  • After training, B·A can be merged into W, so serving adds no latency. Or keep it separate and swap adapters.

Sources4 LoRA: Low-Rank Adaptation of Large Language Models5 LoRA (PEFT conceptual guide)

Worked example

Worked example: a rectangular layer

Layers are not always square. Take a 4096×110084096 \times 11008 layer with rank 16 (illustrative shape).

layer weights=4096×11008=45,088,768B (d×r)=4096×16=65,536A (r×k)=16×11008=176,128adapter total=65,536+176,128=241,664fraction=241,66445,088,768=0.536%\begin{aligned} \text{layer weights} &= 4096 \times 11008 = 45{,}088{,}768 \\ B\ (d \times r) &= 4096 \times 16 = 65{,}536 \\ A\ (r \times k) &= 16 \times 11008 = 176{,}128 \\ \text{adapter total} &= 65{,}536 + 176{,}128 = 241{,}664 \\ \text{fraction} &= \frac{241{,}664}{45{,}088{,}768} = 0.536\% \end{aligned}

The count is dr+rkdr + rk, not 2dr2dr. The "2dr2dr" shortcut only holds when d=kd = k.

Worked example

Worked example: rank sweep, then a whole model

Same 4096×110084096 \times 11008 layer (45,088,768 weights), different rank:

Rank rd·r + r·kFraction of the layer
416,384+44,032=60,41616{,}384 + 44{,}032 = 60{,}4160.134 %
832,768+88,064=120,83232{,}768 + 88{,}064 = 120{,}8320.268 %
1665,536+176,128=241,66465{,}536 + 176{,}128 = 241{,}6640.536 %
32131,072+352,256=483,328131{,}072 + 352{,}256 = 483{,}3281.072 %

Doubling the rank doubles the count and the fraction. Now a hypothetical model that adapts two 4096×40964096 \times 4096 matrices in each of 32 layers at r=8r = 8 (illustrative):

per matrix=2×4096×8=65,536adapters=32 layers×2=64total=64×65,536=4,194,304(about 4.2 million)file size=4,194,304×2 B≈8.4 MB at 16-bit\begin{aligned} \text{per matrix} &= 2 \times 4096 \times 8 = 65{,}536 \\ \text{adapters} &= 32\ \text{layers} \times 2 = 64 \\ \text{total} &= 64 \times 65{,}536 = 4{,}194{,}304 \quad (\text{about } 4.2 \text{ million}) \\ \text{file size} &= 4{,}194{,}304 \times 2\ \text{B} \approx 8.4\ \text{MB at 16-bit} \end{aligned}

Which matrices get adapters is a design choice, so the whole-model fraction depends on it.

Concept

What LoRA gives, and what it limits

  • Small files and swappable: one base model can serve many adapters, for example one per task or tenant.
  • Mergeable: fold B·A into W for no added latency, or keep it separate to stay swappable.
  • Limit: a low rank restricts how much the model can change. It suits style, format and narrow domain behaviour. A very large shift may need a higher rank or full fine-tuning.

Source4 LoRA: Low-Rank Adaptation of Large Language Models

Concept

QLoRA: freeze the base in 4-bit

  • The frozen base model is stored in 4-bit; gradients flow back through it into LoRA adapters trained in higher precision.
  • Each time a 4-bit tensor is needed for compute, it is first converted up to BFloat16 and the multiplication runs in 16-bit.
  • Three ingredients: the NF4 data type, double quantisation (quantising the quantisation constants), and paged optimisers for memory spikes.
  • The authors report fine-tuning a 65B-parameter model on a single 48 GB GPU, preserving 16-bit fine-tuning task performance in their experiments.

Source6 QLoRA: Efficient Finetuning of Quantized LLMs

Worked example

Worked example: weights-only memory

bytes per weight: 16-bit = 2, 4-bit = 0.5

weights (GB)=parameters (billions)×bytes per weight\text{weights (GB)} = \text{parameters (billions)} \times \text{bytes per weight}
Model size16-bit weights4-bit weightsFits a 24 GB GPU for weights alone?
7B7×2=14 GB7 \times 2 = 14\ \text{GB}7×0.5=3.5 GB7 \times 0.5 = 3.5\ \text{GB}Both
20B20×2=40 GB20 \times 2 = 40\ \text{GB}20×0.5=10 GB20 \times 0.5 = 10\ \text{GB}Only 4-bit
33B33×2=66 GB33 \times 2 = 66\ \text{GB}33×0.5=16.5 GB33 \times 0.5 = 16.5\ \text{GB}Only 4-bit, with 7.5 GB left

Weights only. Activations, optimiser state, adapters and quantisation constants come on top, so real use is higher. The authors say paged optimisers are what make 33B and 65B QLoRA tuning possible on a single 24 or 48 GB GPU.

Source6 QLoRA: Efficient Finetuning of Quantized LLMs

Concept

The price of QLoRA

  • Every use of a weight adds a dequantise step, so training steps are typically slower than 16-bit LoRA. That is an expectation to measure, not a number from the paper.
  • The “matches 16-bit quality” result is reported for specific settings. Check it on your own task.
  • You save memory; you spend time and some certainty.

Source6 QLoRA: Efficient Finetuning of Quantized LLMs

Compare

Full fine-tune, LoRA or QLoRA

MethodTrainsHardware needTypical use
Full fine-tuneAll weightsHighestLarge behaviour shift with budget and plenty of data; higher forgetting risk
LoRASmall adapters, base in 16-bitModerateStyle, format, domain behaviour; many swappable variants
QLoRAAdapters, base in 4-bitLowestLarge model on limited GPUs, accepting slower steps

Diagram

Choosing a method

Diagram: Going down, a large behaviour shift with budget and data points to full fine-tuning.

large shift,
big budget

style, format,
domain behaviour

yes

no

How big is the
behaviour change?

Full fine-tune

Fits GPU with
base in 16-bit?

LoRA

QLoRA

Diagram summary: Going down, a large behaviour shift with budget and data points to full fine-tuning. Style, format and domain work goes on to a memory check: LoRA if the 16-bit base fits, QLoRA if it does not.

Check yourself

Check: name the stage

A team collects 200,000 answers produced by a large model on its ticket-triage prompts and trains a small model to reproduce them. Which stage is this, what data does it use, and what is the goal?

Answer

Distillation. The data are the large model’s outputs on the task’s prompts. The goal is to keep a narrow task’s quality at lower cost and latency. It is not pretraining (no raw corpus) and not preference tuning (no ranked pairs).

Check yourself

Check: count an adapter

A layer maps 1024 inputs to 4096 outputs (a 4096×10244096 \times 1024 weight matrix, d=4096d = 4096, k=1024k = 1024). You attach a rank-4 adapter. How many trainable weights, and what fraction of the layer?

Answer

BB is d×r=4096×4=16,384d \times r = 4096 \times 4 = 16{,}384 and AA is r×k=4×1024=4,096r \times k = 4 \times 1024 = 4{,}096, so 20,480 trainable weights. The layer has 4096×1024=4,194,3044096 \times 1024 = 4{,}194{,}304 weights, so the fraction is 20,4804,194,304=0.488%\dfrac{20{,}480}{4{,}194{,}304} = 0.488\%.

Check yourself

Check: when not to reach for QLoRA

A team has one 80 GB GPU and a 7B base model. They want a modest change of reply style. Weights alone are 14 GB at 16-bit. Which method, and why not the one with the lowest memory?

Answer

LoRA with the base in 16-bit. The weights fit comfortably, and the change is style, which suits a small adapter. QLoRA would save memory the team does not need while adding dequantisation work per step and an unverified quality match for their task. Full fine-tuning is not needed for a modest shift.

Summary

Recap

  • Pretraining gives knowledge, SFT teaches behaviour, RLHF and DPO teach preference, distillation shrinks a model.
  • DPO drops the reward model and the RL loop, but still needs a frozen reference.
  • LoRA freezes W and trains B·A: d·r + r·k weights, swappable and mergeable.
  • QLoRA keeps the frozen base in 4-bit: least memory, slower steps.
  • Choose by hardware and size of change: full fine-tune, LoRA or QLoRA.

References

References & Sources (1 of 2)

  1. Training language models to follow instructions with human feedback (opens in a new tab)

    Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, et al.2022NeurIPS 2022Paper

    Used for The RLHF pipeline of demonstrations, a reward model trained on comparisons, and PPO with a per-token KL penalty from the SFT model.

  2. Direct Preference Optimization: Your Language Model is Secretly a Reward Model (opens in a new tab)

    Rafael Rafailov, Archit Sharma, Eric Mitchell, Christopher D. Manning, et al.2023NeurIPS 2023Paper

    Used for DPO trains on preference pairs with a classification-style loss and a reference policy, without a separate reward model or RL loop.

  3. DPO Trainer (TRL documentation) (opens in a new tab)

    Hugging Face2026Documentation

    Used for The DPO loss form and the roles of the reference model and beta in a widely used implementation.

  4. LoRA: Low-Rank Adaptation of Large Language Models (opens in a new tab)

    Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, et al.2022ICLR 2022Paper

    Used for The low-rank update W x + B A x with a random Gaussian A and zero B, the VRAM and checkpoint savings, and merging for no extra inference latency.

  5. LoRA (PEFT conceptual guide) (opens in a new tab)

    Hugging Face2026Documentation

    Used for How rank, alpha, target modules and merging appear in a LoRA configuration.

References

References & Sources (2 of 2)

  1. QLoRA: Efficient Finetuning of Quantized LLMs (opens in a new tab)

    Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, Luke Zettlemoyer2023NeurIPS 2023Paper

    Used for A frozen 4-bit base with LoRA adapters, NF4, double quantisation, paged optimisers, dequantisation to BFloat16 on use, and the 65B-on-48-GB result.