LearnTopic guide

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.

Applied LLM · Research8 key concepts18 questions

Start: Key concepts 6 lessons · about 17 min
Contents

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.

Flow · 4 stepsWhen to fine-tune

When to fine-tuneA task need is checked against prompting and retrieval, then an eval is run first. Good reasons lead to fine-tuning; bad reasons keep the work in prompting or retrieval.Task needformat, tone, tooluse, domainPrompting andretrievalexhaust firstEval firstmeasure thefine-tune's liftFine-tunecontinuingtraining oncuratedexamplesKeepprompting orretrievalretrieval forfast-changingfactsgood reasonsbad reasons1234CheckAct
When to fine-tuneA task need is checked against prompting and retrieval, then an eval is run first. Good reasons lead to fine-tuning; bad reasons keep the work in prompting or retrieval.Task needformat, tone, tool use, domainPrompting and retrievalexhaust firstEval firstmeasure the fine-tune's liftFine-tunecontinuing training oncurated examplesKeep prompting orretrievalretrieval forfast-changing factsgood reasonsbad reasons1234CheckAct
  1. Check first Exhaust prompting and retrieval with an eval first.
  2. Good reasons Consistent format or style, a narrow task, tool-calling conventions, domain language with thousands of examples.
  3. Bad reasons Fast-changing facts, uncharacterised problems, fewer than a few hundred examples, citations.
  4. Fine-tune Fine-tuning adapts behaviour by continuing training on curated examples.

Fine-tuning is the right call only after prompting and retrieval are exhausted and an eval shows the lift.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Check firstExhaust prompting and retrieval with an eval first.
2Good reasonsConsistent format or style, a narrow task, tool-calling conventions, domain language with thousands of examples.
3Bad reasonsFast-changing facts, uncharacterised problems, fewer than a few hundred examples, citations.
4Fine-tuneFine-tuning adapts behaviour by continuing training on curated examples.

Source: This page's text

Boxes
BoxGroupDetail
Task needCheckformat, tone, tool use, domain
Prompting and retrievalCheckexhaust first
Eval firstCheckmeasure the fine-tune's lift
Fine-tuneActcontinuing training on curated examples
Keep prompting or retrievalActretrieval for fast-changing facts

Source: This page's text

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.

Sequence · 5 stepsHow distillation moves a teacher into a student

How distillation moves a teacher into a studentA request flows left to right from task prompts to the teacher, then to a grader, then to the student and finally to the task eval. The teacher's outputs are filtered before training, and the student is judged against a pre-set bar at the target cost and latency.Task promptsTeacherGraderStudentTask eval1task prompts2teacher outputs3filtered outputs4student outputs5accept or reject
How distillation moves a teacher into a studentA request flows left to right from task prompts to the teacher, then to a grader, then to the student and finally to the task eval. The teacher's outputs are filtered before training, and the student is judged against a pre-set bar at the target cost and latency.TaskpromptsTeacherGraderStudentTaskeval1task prompts2teacher outputs3filtered outputs4student outputs5accept or reject
  1. Prompt the teacher The student is trained on the teacher's generated outputs for the task prompts.
  2. Filter teacher outputs Teacher outputs are filtered with graders before training.
  3. Train the student The student is fine-tuned on the accepted teacher outputs.
  4. Check the student The student is accepted when it meets the pre-set bar on the task eval.
  5. Verdict The student is accepted at the target cost and latency, or not.

The teacher generates outputs for task prompts, graders filter them, and the student is accepted only when it meets the pre-set task-eval bar.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Messages
StepFromToMessage
1Task promptsTeachertask prompts
2TeacherGraderteacher outputs
3GraderStudentfiltered outputs
4StudentTask evalstudent outputs
5Task evalStudentaccept or reject (reply)

Source: This page's text

Next: Worked examples Lesson 3 of 6 · about 4 min

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.

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.

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.

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.

Next: What changed Lesson 4 of 6 · about 2 min

What changed recently

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

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

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

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

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

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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.
Next: Quiz Lesson 6 of 6 · about 3 min

Quiz

Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.

  1. Question 1 of 3 · Applied LLM · Technical · Easy

    Give three situations where fine-tuning an LLM is the right call and three where it is the wrong one.

  2. Question 2 of 3 · Applied LLM · Technical · Medium

    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 adapters?

  3. Question 3 of 3 · Applied LLM · Technical · Medium

    You’re assembling 20k conversations to fine-tune a support assistant. What decides whether the fine-tune helps, and what are the technical gotchas?

Reading

Practise this topic

  1. Give three situations where fine-tuning an LLM is the right call and three where it is the wrong one.Applied LLM · Technical · Easy
  2. 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 adapters?Applied LLM · Technical · Medium
  3. You’re assembling 20k conversations to fine-tune a support assistant. What decides whether the fine-tune helps, and what are the technical gotchas?Applied LLM · Technical · Medium
  4. After domain fine-tuning, general reasoning and instruction-following dropped. Why, and what do you do?Applied LLM · Technical · Medium
  5. 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?Applied LLM · Technical · Medium
  6. Roughly how much GPU memory does full fine-tuning of a 7B model with Adam in mixed precision need, compared with LoRA and QLoRA?Applied LLM · Technical · Medium
  7. 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?Applied LLM · Technical · Hard
  8. 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 does that constraint assume about the update?Research · Technical · Medium
  9. 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 go wrong at each stage?Research · Technical · Medium
  10. A product team wants the assistant to “know” 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and fine-tuning — and when would you not use retrieval at all?Applied LLM · Technical · Easy
  11. 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 you choose grader-based reinforcement fine-tuning over supervised fine-tuning, and how would you design the grader?Applied LLM · Technical · Medium
  12. 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 it?Applied LLM · Technical · Hard
  13. 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, that generates, validates and decontaminates them.Applied LLM · System design · Hard
  14. 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?Research · Technical · Medium
  15. Derive GRPO’s advantage estimate and explain why it needs no value network. Then explain what DAPO and GSPO each change, and why.Research · Technical · Hard
  16. GEPA, a reflective prompt optimiser in DSPy, reports beating GRPO fine-tuning with far fewer rollouts. When would you optimise prompts automatically instead of fine-tuning, and what could go wrong?Applied LLM · Technical · Hard
  17. 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 what ‘sequence-level’ protects and what it does not, why DP scaling laws favour smaller models with larger batches, and when you would use DP training rather than deduplication and PII filtering for a model fine-tuned on customer messages.Research · Technical · Hard
  18. 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 not already do this with a better prompt, and how did you rule out length bias and reward hacking?Research · Research talk · Hard

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.