---
title: Fine-tuning, LoRA and distillation
url: https://gurkanozkan.ai/learn/topics/fine-tuning/
markdown: https://gurkanozkan.ai/learn/topics/fine-tuning.md
kind: topic
tracks:
  - Applied LLM
  - Research
json: https://gurkanozkan.ai/api/learn/topics/fine-tuning.json
---

# Fine-tuning, LoRA and distillation

Fine-tuning adapts a pretrained model's behaviour (format, tone, tool use, domain conventions, latency and cost) by continuing training on curated examples; it is a poor way to inject fast-changing facts. Interviewers want to hear when it is the right call versus prompting or retrieval, how supervised fine-tuning is set up so that training matches serving, the mechanics and memory arithmetic of LoRA and QLoRA, why models forget, and how to distil an expensive model into a cheap one with evidence that the student is good enough. Preference and RL post-training are covered in their own topic; here they appear only as later stages of the pipeline.

## Key concepts

### When to fine-tune (and when not to)

Good reasons: a consistent output format or style that prompting cannot hold, a narrow task where a small tuned model can replace a large one (cost, latency, on-prem), teaching tool-calling conventions, or domain language and labels with thousands of examples. Bad reasons: adding knowledge that changes weekly (use retrieval), fixing problems you have not yet characterised with evals, having fewer than a few hundred good examples, or needing citations to sources. Always exhaust prompting and retrieval with an eval first, so you can measure the fine-tune's lift.

### SFT mechanics and train/serve parity

Render every example with the exact chat template the serving stack uses (apply the tokenizer's template, never hand-built strings), include the same system prompt and tool schema, and mask the loss to assistant tokens. Make sure end-of-turn and EOS tokens are present in targets, or the model will not stop. Check special-token handling, truncation, packing boundaries and that thinking/no- thinking modes match. Most 'the fine-tune broke tool calls' incidents are template, stop-token or schema mismatches, not model capacity.

### Data quality beats quantity

A thousand carefully curated, diverse examples can beat tens of thousands of noisy ones because SFT mostly teaches format and behaviour on top of pretrained knowledge. Deduplicate, remove contradictory or low-quality answers, balance intents, keep a clean held-out set from the same distribution, and include refusals and edge cases you want handled. For support transcripts, strip personal data and remove agents' workarounds you do not want imitated.

### LoRA

Freeze W and learn a low-rank update ΔW = BA with B (d_out × r) and A (r × d_in), scaled by α/r; B starts at zero so training begins from the base model. A d×d matrix needs 2dr trainable parameters instead of d². Apply it to all linear layers including MLP (attention-only underperforms); use a learning rate about 10× higher than full fine-tuning; rank matters less than expected for small-to-medium datasets. Adapters can be merged into weights for zero-overhead serving or kept separate and hot-swapped. A 2026 re-evaluation of nine LoRA variants found that once learning rates are tuned separately for each, all land within 1–2% of vanilla LoRA, so claimed gains need a fair learning-rate sweep.

### QLoRA

Store the frozen base in 4-bit NormalFloat (NF4, suited to normally distributed weights), quantise the quantisation constants themselves (double quantisation, ~0.127 bits/parameter of overhead instead of 0.5), and page optimiser state to CPU memory on spikes. Weights are dequantised to bf16 on the fly for each matmul, so it is slower per step than LoRA but fits a 65B model on one 48 GB GPU. Serve the merged model in the precision you evaluated, or evaluate the quantised base plus adapter you will actually serve.

### Forgetting and how to limit it

Narrow fine-tuning shifts weights towards the new distribution and erodes general instruction following, reasoning and safety behaviour, worse with high learning rates, many epochs and full fine-tuning. Mitigations: mix in general instruction data (5–20% replay), fewer epochs and lower learning rate, LoRA (learns less and forgets less), early stopping on a general-capability eval suite run alongside the task eval, and starting from the instruct rather than base checkpoint when you need chat behaviour.

### Where SFT sits in post-training

A typical chat model is pretrained, then supervised fine-tuned on demonstrations, then optimised on preferences (RLHF with a reward model and a KL penalty to the reference, or DPO whose β plays the same role) and increasingly with RL from verifiable rewards (unit tests, maths answers) using critic-free group-relative methods such as GRPO and successors (DAPO, GSPO); on-policy distillation, where the student samples and a teacher grades every token, is a cheaper option when a stronger teacher exists. SFT mainly sets format and behaviour; capability gains on hard reasoning come mostly from the RL stages.

### Distillation

Sequence-level distillation fine-tunes a student on the teacher's generated outputs for your task prompts (works across tokenizers and through APIs, subject to the provider's terms). Logit distillation matches the teacher's softened token distribution with a KL loss at temperature T and needs the teacher's logits and a shared tokenizer. Filter teacher outputs with graders, cover the real input distribution including hard cases, and accept the student when it meets a pre-set bar on the task eval (e.g. within 2 points of the teacher, no regression on critical slices) at the target cost and latency.

## Worked examples

### LoRA parameter count for an 8B model

A Llama-3-8B-style model has 32 layers, hidden size 4096, 8 KV heads of dimension 128 (so k and v projections are 4096 → 1024) and an MLP width of 14,336 (gate, up, down). Count LoRA parameters at r = 16 for (a) attention only (q, k, v, o) and (b) all linear layers, and the adapter file size.

**Solution**

Parameters per adapted matrix = r × (d_in + d_out).

**Attention, per layer**: q: 16 × (4096 + 4096) = 131,072; k: 16 × (4096 + 1024) = 81,920;
v: 81,920; o: 131,072. Sum = **425,984**. × 32 layers = **13.6M**.

**MLP, per layer**: gate, up and down each 16 × (4096 + 14,336) = 294,912; × 3 = 884,736.

**All linear**: (425,984 + 884,736) × 32 = 1,310,720 × 32 = **41.9M**, about **0.52%** of 8.03B.

**Adapter size** in bf16: 41.9M × 2 B ≈ **84 MB** (vs ~16 GB for the full model).

**Single-matrix check**: a full d × d update at d = 4096 is 16.8M parameters; at r = 16 it is
2 × 4096 × 16 = 131,072, a 128× reduction, which assumes the useful update lies in a
low-dimensional subspace.


### GPU memory for full fine-tuning vs LoRA vs QLoRA on a 7B model

Estimate memory for full fine-tuning with Adam in mixed precision, LoRA on a bf16 base and QLoRA on a 4-bit base, for a 7B model. Excluding activations first, then comment on activations at 4k tokens.

**Solution**

**Full fine-tuning**: 16 B/param (bf16 weights 2 + grads 2 + fp32 master 4 + Adam 8) × 7e9 =
**112 GB** → needs sharding (FSDP/ZeRO) across several 80 GB GPUs.

**LoRA** (~40M trainable params): frozen bf16 base 7e9 × 2 = **14 GB**; adapter weights, grads and
Adam ≈ 40e6 × 16 B ≈ **0.64 GB**. Total ≈ 15 GB + activations → one 24–48 GB GPU.

**QLoRA**: NF4 base 7e9 × 0.5 B = 3.5 GB plus ~0.11 GB of constants (0.127 bits/param) ≈ **3.6 GB**;
adapters as above → ~4.3 GB + activations → fits a consumer GPU.

**Activations** dominate at long sequences. A common rule of thumb for bf16 with FlashAttention is
~34 × seq × batch × hidden bytes per layer: 34 × 4,096 × 1 × 4,096 ≈ 570 MB × 32 layers ≈ **18 GB**
at batch 1 without checkpointing. Gradient checkpointing stores only layer inputs (~1 GB here) and
recomputes the rest for roughly 30% more compute.


### Serving 50 customer-specific adapters

You have fine-tuned 50 LoRA adapters (r = 16, all linear layers) on one 8B base model, one per customer. Compare serving them as merged models vs multi-adapter serving.

**Solution**

**Merged models**: 50 × ~16 GB = **~800 GB** of weights, i.e. many GPUs mostly idle because each
customer's traffic is small.

**Multi-adapter serving**: one base (16 GB) + 50 × 84 MB ≈ **4.2 GB** of adapters, all resident on
one GPU. Batched LoRA kernels (as in S-LoRA/Punica-style serving in vLLM or SGLang) apply different
adapters to different requests in the same batch.

**Operational details**: set the maximum number of adapters active per batch at least as high as
expected concurrency (too low makes requests for other adapters queue behind the active ones and stalls throughput under load), cap rank across
adapters, keep cold adapters in CPU memory and load on demand, route by adapter ID for cache
locality, and evaluate each adapter on its customer's eval set at every base-model upgrade, because
adapters are tied to the exact base weights.


## What changed recently

- **Jun 2026: RL environments become shared infrastructure (OpenEnv).** OpenEnv, a Gymnasium-style interface (reset, step, state) for RL environments served over HTTP or WebSocket and packaged in Docker, moved to a committee including Meta-PyTorch, NVIDIA, Microsoft, Hugging Face, Prime Intellect and Unsloth; it deliberately leaves reward definitions and training loops to other libraries. Agentic RL fine-tuning now starts from reusable task environments rather than static datasets, so interviewers ask how you would build an environment, its verifier and its contamination checks. [Source](https://huggingface.co/blog/openenv-agentic-rl)
- **Feb 2026: Tuned learning rates erase most LoRA-variant gains.** Re-evaluating nine LoRA variants against vanilla LoRA with broad searches over learning rate, batch size, rank and duration, the authors found that each method has a different best learning-rate range and that, once tuned, all land within 1–2% of each other. Claims that a new adapter method beats LoRA need a fair learning-rate sweep, and vanilla LoRA remains the sensible default. [Source](https://arxiv.org/abs/2602.04998)
- **Oct 2025: On-policy distillation as a cheap middle path.** Thinking Machines described on-policy distillation: the student samples its own trajectories and the teacher scores every token, with a per-token reverse-KL loss, combining RL's on-policy relevance with dense supervision. It cited Qwen3 results in which on-policy distillation beat an RL stage on AIME'24 (74.4% versus 67.6%) at about a tenth of the GPU hours, and it is now a common option alongside SFT and RL with verifiable rewards. [Source](https://thinkingmachines.ai/blog/on-policy-distillation/)
- **Jul 2025: GSPO: sequence-level policy optimisation.** The Qwen team's Group Sequence Policy Optimization computes importance ratios, clipping and optimisation per whole sequence instead of per token, and reports more stable RL than GRPO, especially for mixture-of-experts models. It is one of several GRPO successors (with DAPO's clip-higher, dynamic sampling and token-level loss) that interviewers expect you to compare. [Source](https://arxiv.org/abs/2507.18071)
- **Jan 2025: DeepSeek-R1 makes RL with verifiable rewards the default recipe.** DeepSeek-R1 showed that reasoning behaviours such as self-verification and reflection can emerge from large-scale RL with rule-based rewards, without human-written reasoning traces, and that the resulting patterns distil into smaller models; the work was later published in Nature. Group-relative, critic-free methods with verifiable rewards replaced PPO with a learned reward model as the first thing interviewers expect you to describe for reasoning post-training. [Source](https://arxiv.org/abs/2501.12948)

## Pitfalls

- Fine-tuning to add facts that change often, then being surprised by confident stale answers.
- Building training strings by hand instead of using the serving chat template, causing malformed tool calls or no stop token.
- Computing loss on the prompt and system tokens as well as the assistant's response.
- Getting LoRA parameter counts wrong (d² instead of 2dr, or forgetting non-square k/v and MLP shapes).
- Reusing full fine-tuning learning rates for LoRA, or applying LoRA only to attention projections.
- Evaluating only the target task and missing regressions in general instruction-following and safety.

## How interviewers probe it

- Give three situations where fine-tuning is right and three where it is wrong.
- Explain LoRA: what is trained, how rank and α matter, where adapters go, and how QLoRA cuts memory.
- You have 20k support conversations: what decides whether the fine-tune helps, and what are the gotchas?
- After domain fine-tuning, general reasoning dropped: why, and what do you do?
- Training loss looks great but the served model emits malformed tool calls and does not stop: what do you check?
- Distil a frontier-model feature into a small model: data generation, filtering, evaluation bar and licensing.

## Reading

- [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685) (Paper, 40 min, Core): The original method, initialisation and α/r scaling, with the parameter savings.
- [QLoRA: Efficient Finetuning of Quantized LLMs](https://arxiv.org/abs/2305.14314) (Paper, 45 min, Core): NF4, double quantisation and paged optimisers; the 65B-on-48GB result.
- [LoRA Without Regret](https://thinkingmachines.ai/blog/lora/) (Blog, 35 min, Core): Current practical guidance: all-layer LoRA, ~10× learning rate, rank and batch-size effects.
- [LoRA Learns Less and Forgets Less](https://arxiv.org/abs/2405.09673) (Paper, 45 min, Deep): Quantifies the learning-vs-forgetting trade-off of LoRA against full fine-tuning.
- [Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155) (Paper, 60 min, Core): The InstructGPT pipeline: SFT, reward model and PPO with a KL penalty.
- [Distilling the Knowledge in a Neural Network](https://arxiv.org/abs/1503.02531) (Paper, 25 min, Intro): Soft targets and temperature: the foundation of logit distillation.
- [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://arxiv.org/abs/2501.12948) (Paper, 45 min, Core): The paper that made RL with verifiable rewards and GRPO the standard reasoning post-training recipe.
- [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) (Blog, 30 min, Core): A clear account of a middle path between SFT and RL in which the student samples and the teacher grades every token, with compute comparisons.

## Practise this topic

- [Give three situations where fine-tuning an LLM is the right call and three where it is the wrong one.](https://gurkanozkan.ai/learn/questions/applied-llm-ft-01.md)
- [Explain LoRA: what is trained, how rank and alpha matter, where adapters go, and how QLoRA cuts memory further. How would you serve 50 customer-specific…](https://gurkanozkan.ai/learn/questions/applied-llm-ft-02.md)
- [You're assembling 20k conversations to fine-tune a support assistant. What decides whether the fine-tune helps, and what are the technical gotchas?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-03.md)
- [After domain fine-tuning, general reasoning and instruction-following dropped. Why, and what do you do?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-07.md)
- [Your feature works with a large frontier model but costs too much. How would you distil it into a smaller model, and how do you know it's good enough?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-08.md)
- [Roughly how much GPU memory does full fine-tuning of a 7B model with Adam in mixed precision need, compared with LoRA and QLoRA?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-09.md)
- [Training loss looks great, but in the serving stack the fine-tuned model emits malformed tool calls and doesn't stop properly. What do you check?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-10.md)
- [Define linear independence and matrix rank. If a fine-tuning update to a d×d weight matrix is constrained to rank r, how many parameters does it use, and what…](https://gurkanozkan.ai/learn/questions/research-rank-and-low-rank-adaptation-006.md)
- [Walk through how a modern chat model is produced, from raw text to deployed assistant: pretraining, supervised fine-tuning and preference/RL training. What can…](https://gurkanozkan.ai/learn/questions/research-how-a-chat-llm-is-built-032.md)
- [A product team wants the assistant to "know" 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and…](https://gurkanozkan.ai/learn/questions/applied-llm-rag-01.md)
- [A team wants a hosted model to get better at a narrow task with a checkable answer, such as extracting the right clause and amount from contracts. When would…](https://gurkanozkan.ai/learn/questions/recent-a-ft-01.md)
- [Explain on-policy distillation. How does it differ from supervised distillation on teacher outputs and from RL with a verifiable reward, and when would you use…](https://gurkanozkan.ai/learn/questions/recent-a-ft-02.md)
- [You need RL training data for a coding agent: thousands of executable tasks, each with an environment and tests. Design a pipeline, in the spirit of SWE-smith…](https://gurkanozkan.ai/learn/questions/recent-a-datapipe-02.md)
- [What are persona vectors, how would you extract one for a trait such as sycophancy, and how could they be used during deployment and training?](https://gurkanozkan.ai/learn/questions/recent-a-interp-03.md)
- [Derive GRPO's advantage estimate and explain why it needs no value network. Then explain what DAPO and GSPO each change, and why.](https://gurkanozkan.ai/learn/questions/recent-a-ft-03.md)
- [GEPA, a reflective prompt optimiser in DSPy, reports beating GRPO fine-tuning with far fewer rollouts. When would you optimise prompts automatically instead of…](https://gurkanozkan.ai/learn/questions/recent-b-prompting-02.md)
- [Google's VaultGemma (2025) was trained from scratch with sequence-level differential privacy at ε ≤ 2 and ended up roughly as capable as GPT-2 1.5B. Explain…](https://gurkanozkan.ai/learn/questions/recent-b-privacy-01.md)
- [Your CV lists a GRPO fine-tune of a small Qwen model that raised maths accuracy. Defend the result: what was the baseline, how do you know the base model could…](https://gurkanozkan.ai/learn/questions/recent-b-projects-02.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
