Module deck
Fine-tuning flashcards
Reviewing needs JavaScript. You can read every card in the list below.
Loading your cards...
Back to the module87 cards in this deck
Read all 87 cards as a list
When to tune, and what it costs
- Front
- Retrieval or tuning: which fits a changing fact, and which fits a behaviour?
- Back
- Retrieval for what the model should know (current, citable, permissioned). Tuning for how it should behave (format, tone, routine, cost). Weights cannot cite a source or be edited by changing one document.
- Front
- Name three sound reasons to fine-tune.
- Back
- A format or routine that a strong prompt still gets wrong at volume; a small model matching a large one on a narrow task; a consistent tone or policy at scale. Also: baking in a long fixed prefix, or running an open model you host.
- Front
- What must a tuned model beat before it ships?
- Back
- The best prompt plus retrieval, on a held-out set, using the newest base model you could use. Beating a first-draft prompt proves little.
- Front
- Break-even for a tuning project?
- Back
- Payback = one-off cost (data, training, evaluation) ÷ (gross saving per day − hosting per day − maintenance per day). Maintenance is the re-tune cost spread over its interval.
- Front
- How can a cheaper alternative cancel a tune's saving?
- Back
- The baseline moves. If prefix caching already makes a repeated prefix cheap, baking it in can save at most what is still being paid, which may be less than the tuned model's hosting.
- Front
- What is the model treadmill?
- Back
- A tune is tied to one base model, and bases improve every few months. Budget for re-tuning, and re-run the prompt and retrieval baseline on the newest base before re-investing.
- Front
- Bytes per parameter for full fine-tuning with Adam in mixed precision?
- Back
- About 16: 2 (16-bit weights) + 2 (gradients) + 12 (32-bit master copy, momentum and variance at 4 each). This is model states only.
- Front
- Why do LoRA and QLoRA need so much less memory?
- Back
- The base is frozen, so it needs no gradients or optimiser state, only storage: 2 bytes per parameter in 16-bit, about 0.5 in 4-bit. Only the small adapter pays the 16 bytes.
- Front
- What does a model-state memory estimate leave out?
- Back
- Activations (grow with batch and sequence length), the logits tensor (tokens × vocabulary × bytes), framework overhead and 4-bit quantisation constants. Treat the estimate as a floor.
- Front
- Training compute for a dense model?
- Back
- About 6 × N × D FLOPs: roughly 2 forward plus 4 backward per parameter per token. Time = FLOPs ÷ sustained FLOP/s. N is approximately non-embedding parameters.
- Front
- How much compute does LoRA save?
- Back
- About a third: frozen layers skip weight gradients but still compute the gradients that reach the adapters, so roughly 4ND instead of 6ND. The big saving is memory.
- Front
- Why not divide by a vendor's headline teraFLOPS to get training time?
- Back
- Headline figures can be marked 'with sparsity' and are peaks. Use the rate your job sustains, or an assumed round figure that you state. The share of peak reached is model FLOPs utilisation.
Data engineering for fine-tuning
- Front
- What is the main trap of each tuning data source: experts, logs, a stronger model, a checker, public sets?
- Back
- Experts: slow, costly, annotators drift. Logs: personal data, consent, weakly checked approvals. Stronger model: copied errors and provider terms. Checker: a weak checker is gamed. Public sets: licence, overlap with your evals, wrong distribution.
- Front
- What did LIMA show, and what does it not show?
- Back
- 1,000 curated examples were enough to teach a 65B base model a response style that generalised. It does not show that new skills or facts can be taught with so few. It is one study, and its authors name the effort of writing such data as the limit.
- Front
- How do you make synthetic data usable?
- Back
- Seed by hand, vary personas and difficulty, then verify with something other than the generator (run code, validate schema, recompute numbers, second judge). Drop failures, deduplicate, blend with real data, and keep a real-only test set.
- Front
- How do you answer 'how many examples do I need?'
- Back
- Train on 10, 25, 50 and 100 percent with the same recipe and score each on the same golden set. A flat end of the curve means more of the same data will not help; fix coverage or labels. A rising curve means collect more.
- Front
- What is the order of cleaning steps, and what does each protect against?
- Back
- Filter (junk), deduplicate (memorisation and train-test overlap), decontaminate (eval items in training), remove personal data (regurgitation, privacy), then split. Rendering and masking come after the split.
- Front
- Why does the decontamination window need to fit your data?
- Back
- A 13-word overlap filter, as used for GPT-3, cannot match a test item shorter than 13 words. Choose N from the item lengths and test the filter, because the GPT-3 filter had a bug that let some overlaps through.
- Front
- Why strip personal data before training?
- Back
- Models can emit training text verbatim; Carlini et al. extracted names, phone numbers and emails from GPT-2, including strings seen in one document. Removing data from trained weights is hard, so clean first and keep lineage to retrain.
- Front
- Why is a random row split dangerous?
- Back
- Related rows (turns of one thread, chunks of one document) land on both sides, so the held-out score partly measures recall of seen content. Split by group, as GroupKFold and GroupShuffleSplit do, or by time when the task drifts.
- Front
- What is the golden set for, and how is it different from validation?
- Back
- The golden set is hand-verified and used for the final answer only; nobody trains or tunes on it. A separate validation set drives early stopping and settings. Report slices (rare intents, long inputs, languages) as well as the average.
- Front
- What does 'the chat template is the contract' mean?
- Back
- Render training data with the exact template used at serving, through the tokenizer's own template function. Omit the generation prompt for training and do not add special tokens twice. A mismatch leaves the loss looking normal and production output poor.
- Front
- How do you mask the loss in SFT, and what must stay unmasked?
- Back
- Positions to ignore get label -100. Common chat practice is to learn from assistant tokens only; in TRL this is a setting and the default depends on the data format. The end-of-turn token stays in the target so the model learns to stop.
- Front
- What is the decoded-batch audit?
- Back
- Before training, decode a few real batches with their labels shown. Check by eye that the template matches serving, the end token is present, and the mask covers the prompt but not the answer. Template and mask faults do not show in the loss.
PEFT, LoRA and QLoRA in depth
- Front
- How many trainable numbers does a rank-r LoRA adapter have for a d-output, k-input matrix, and what is its limit?
- Back
- r × (d + k), against d × k for a full update. The product B·A has rank at most r, so it can move the layer only within an r-dimensional family: good for narrow changes, weaker for big new skills.
- Front
- Why is B initialised to zero and A random, not both zero?
- Back
- The gradient of each factor depends on the other. With both at zero neither moves. With B at zero and A random, the update starts at zero (the base model) and B receives a non-zero gradient first.
- Front
- What does alpha over r do in a LoRA layer?
- Back
- It multiplies the B·A term, setting how loudly the adapter speaks. Change rank without alpha and the scale changes. PEFT defaults are r=8, alpha=8, so a scale of 1.
- Front
- How do you count a whole model's LoRA parameters?
- Back
- For every adapted matrix add r × (inputs + outputs), then sum over matrices and layers. Narrower matrices (such as grouped-query key and value projections) add less.
- Front
- How do you turn an adapter count into training memory?
- Back
- Multiply by the 16 bytes per trained parameter of states with Adam in mixed precision. A 15-million-parameter adapter is about 0.24 GB. The frozen base adds only its storage.
- Front
- Targets or rank: which do the papers say to change first?
- Back
- Targets. LoRA on all linear layers was needed to match full fine-tuning in the QLoRA study, and rank was close to flat in both papers' tests. Test two ranks on held-out data before raising it.
- Front
- What learning rates did the QLoRA paper use?
- Back
- 2e-4 for the 7B and 13B models, 1e-4 for 33B and 65B, with a bigger batch for the larger ones. One team's setup, not a default: sweep your own.
- Front
- What does NF4 do, and what is the block size in QLoRA?
- Back
- A 4-bit data type fitted to bell-shaped, zero-centred weights, not evenly spaced. Weights are quantised in blocks of 64, each with its own constant, so an outlier harms only its block.
- Front
- What does double quantisation save?
- Back
- It quantises the per-block constants to 8 bits in blocks of 256, cutting their overhead from 0.5 to 0.127 bits per parameter. About 0.11 GB instead of 0.44 GB for a 7B base.
- Front
- What do paged optimisers do, and what stays in 16-bit in QLoRA?
- Back
- They move optimiser state between GPU and CPU memory (unified memory) to survive memory spikes, at the cost of slower steps. The adapter, its gradients and the matrix multiply stay in 16-bit; only storage is 4-bit.
- Front
- When does full fine-tuning beat LoRA?
- Back
- On demanding domains with lots of data, such as code and maths with continued pretraining, where low-rank LoRA substantially underperformed in one study. LoRA forgot less. Ladder: LoRA on all linear layers, then higher rank, then full tune only if the gap justifies the cost.
- Front
- Merge an adapter or keep it swappable?
- Back
- Merge (W + (alpha/r)·B·A) for one dominant adapter: no added latency. Swap for many tenants on one base: small files, shared base, and mixed-task batching is awkward after merging. Merge a 4-bit-trained adapter into a 16-bit copy and re-evaluate.
Training practice and distributed training
- Front
- Which tokens carry the loss in a typical SFT run, and why?
- Back
- The response (completion or assistant) tokens, so the number measures the behaviour you want to teach. Padding is excluded by an ignore index. Check that the prompt is masked and the end token is present.
- Front
- Why not pick the checkpoint by validation loss alone?
- Back
- Cross-entropy measures imitation, not the task. Choose by a held-out task metric (JSON-valid rate, exact match, rubric score), and use validation loss as a sanity check.
- Front
- Name two quiet setup errors that give a healthy-looking SFT curve.
- Back
- A length limit that truncates the answer away, and an end token that is missing or does not match the chat template so the model never stops. Loss on prompt tokens is a third.
- Front
- Effective batch size with accumulation and several GPUs?
- Back
- Sequences per pass x accumulation steps x data-parallel GPUs. Accumulation saves activation memory and costs wall-clock time; the update is the same as one large batch.
- Front
- What does gradient checkpointing save, and what does it cost?
- Back
- It saves activation memory by not storing them all, and costs extra compute because they are recomputed in the backward pass. It does not shrink weights, gradients or optimiser state.
- Front
- Which memory levers attack activations, and which attack model states?
- Back
- Activations: smaller per-pass batch (accumulation), checkpointing, shorter sequences, activation offloading. States: LoRA or QLoRA, sharding (ZeRO or FSDP), offloading states to CPU or NVMe.
- Front
- The accumulation loss trap for token-level losses?
- Back
- Correct loss = total loss over the accumulation step divided by the total non-padding tokens in it, not the average of per-batch averages. Averaging the averages over-weights short sequences.
- Front
- Per-GPU model states with Adam in mixed precision, P parameters, N GPUs?
- Back
- Replicated: 16P. ZeRO-1: 4P + 12P/N. ZeRO-2: 2P + 14P/N. ZeRO-3 or FSDP full shard: 16P/N. Floors, before activations and temporary gathered layers.
- Front
- What does full sharding pay for its memory saving?
- Back
- More communication: parameters are all-gathered around the forward and backward passes and gradients reduce-scattered. The ZeRO paper counts 1.5 times the data-parallel volume for stage 3.
- Front
- When should you not shard?
- Back
- When weights, gradients, optimiser state and activations already fit on one GPU. Plain data parallelism is simpler and avoids the gathering traffic. Offload only after sharding is not enough.
- Front
- Training loss falls, validation loss rises, task metric falls. What is it and what do you do?
- Back
- Overfitting. Restore an earlier checkpoint or train fewer epochs, and consider more varied data. It is different from forgetting, which validation loss on your own data does not show.
- Front
- The debugging order for a misbehaving run?
- Back
- Decode what the model sees (inputs and labels), overfit a tiny batch, compare training and serving prompts, run the base model for a true baseline, then change one variable at a time with seed, versions and data hash pinned.
- Front
- Loss flat from step 0: first checks?
- Back
- Decode a batch to see whether the labels are all masked, count trainable parameters, and try to overfit eight examples. Only then look at learning rate.
Alignment and preference optimisation
- Front
- What are the three steps of the RLHF recipe in InstructGPT?
- Back
- SFT on demonstrations, a reward model trained on human rankings of outputs, then reinforcement learning (PPO) against that reward. Reported in Ouyang et al., 2022.
- Front
- What does the KL penalty do in RLHF, and what does it cost?
- Back
- It charges the policy for drifting from the SFT model, keeping it where the reward model's scores can be trusted and its answers varied. The cost is some of the possible gain; beta sets the balance.
- Front
- What does a PPO-based RLHF run need that DPO does not?
- Back
- A separately trained reward model, a value model (about the size of the policy), and sampling from the policy during training. Both need the preference data and a frozen reference.
- Front
- Write the DPO loss in words.
- Back
- Minus log-sigmoid of beta times [log(new/ref) for the preferred answer minus log(new/ref) for the rejected answer]. It rewards raising the preferred answer's ratio above the rejected one's.
- Front
- What does beta do in DPO?
- Back
- It scales the log-ratios and so controls deviation from the reference. A larger beta makes the same movement count for more, the loss saturates sooner, and the model stays closer.
- Front
- Why does DPO still need a reference model?
- Back
- Every log-ratio divides the trained model's probability by the reference's. The reference defines what 'moved' means. Its log-probabilities for fixed pairs can be computed once and reused.
- Front
- A DPO pair has beta 0.1, preferred log-ratio +1.0 and rejected -2.0. What is the loss?
- Back
- Margin = 0.1 × 3.0 = 0.3. Loss = -ln(sigmoid(0.3)) ≈ 0.554. At the start, with both log-ratios 0, the loss is ln 2 ≈ 0.693.
- Front
- Which DPO relative fits which data or constraint?
- Back
- IPO: pairs, bounded target gap. KTO: single answers with a binary label. ORPO: pairs, adds an odds-ratio term to SFT, no reference. SimPO: pairs, length-normalised reward plus margin, no reference.
- Front
- Why are reported gains for DPO-family methods not a ranking?
- Back
- Each paper uses its own models, datasets, judges and tuned baselines, and the methods are not run against each other under one setup. The KTO paper itself says no single loss wins everywhere. Test on your evaluation.
- Front
- How is a group-relative advantage computed in GRPO?
- Back
- Sample G answers per prompt, score them, then A_i = (r_i − group mean) ÷ group standard deviation. No value model is needed. An all-equal group gives zero advantage and no signal.
- Front
- GRPO versus verifiable rewards: what is the difference?
- Back
- GRPO is the optimiser. Verifiable rewards are one source of scores. DeepSeekMath scored groups with a reward model; DeepSeek-R1 used rule-based accuracy and format rewards with GRPO.
- Front
- What is reward hacking, and what are two defences?
- Back
- The model scores well on the proxy without doing what you wanted (for example longer or more confident answers). Defences: a KL leash or larger beta, early stopping on a held-out measure, fresh pairs on current outputs, length checks.
- Front
- Does having no reward model make DPO immune to over-optimisation?
- Back
- No. It removes one moving part. IPO's analysis describes overfitting to one-sided pairs, and SimPO's ablation shows length being exploited when it is not normalised.
- Front
- When is each approach worth its cost?
- Back
- SFT for demonstrations; DPO-style when you have pairs and a gap SFT cannot close; KTO for thumbs-only data; GRPO for checkable tasks with a sampling budget; PPO-RLHF for specialist teams. Judgment, not data.
Evaluation, deployment and special cases
- Front
- What is a baseline ladder for a tuned model?
- Back
- Base zero-shot, then the best prompt with examples, then prompt plus retrieval or tools, then a cheaper small model if plausible. The tune must beat the highest rung you could realistically ship, on the newest base.
- Front
- Why report an interval and slices, not one score?
- Back
- On a few hundred items a gain of a couple of points can sit inside the noise. A bootstrap shows the spread, and slices show groups that got worse while the average rose.
- Front
- Which suites does a gate keep separate, and why?
- Back
- Task (interval, slices), regression against the base, safety (refusals and over-refusal), and format validity. They fail differently, and valid format is not correct content. Pass rules are written before training.
- Front
- How do you detect forgetting in practice?
- Back
- Run the same general suite on the base and the tuned model and read the drop relative to the base. The task score may rise while the general suite falls. Mitigate with lower learning rate or epochs, a smaller adapter, and mixed-in general data.
- Front
- Why must the safety suite run on the tuned model itself?
- Back
- Qi et al. (2023) report that tuning an aligned model can weaken its safety behaviour, and that benign data can do it too, to a lesser degree. Base results do not carry over. Measure refusals on harmful prompts and answers on harmless ones.
- Front
- Overfitting or forgetting: how do the signals differ?
- Back
- Overfitting shows as a held-out score below the training score, sometimes with verbatim repeats. Forgetting shows as a fall on abilities the data never touched. Check the held-out set for one and the regression suite for the other.
- Front
- Merged weights or separate adapters?
- Back
- Merge for one dominant model, with no extra per-request step. Keep adapters separate on a shared base for many tenants, A/B tests and rollback by pointing to the earlier adapter. Whichever you choose, version the base, adapter, data and template together.
- Front
- Task arithmetic, TIES and DARE in one line each?
- Back
- Task arithmetic: add or negate scaled task vectors (tuned minus base). TIES: trim small changes, elect a sign per parameter, merge only agreeing values. DARE: randomly drop most deltas and rescale the rest to reduce interference (TIES trims by size and resolves signs; DARE drops at random).
- Front
- What must you re-check after a merge?
- Back
- Everything. A merge is a new model and can lose abilities, and merging into a quantised base re-quantises the weights, so the result is not the tested artefact. Re-run the whole gate on the merged model.
- Front
- What does tuning an embedding model force downstream?
- Back
- Vectors from the old and new models are not comparable, so re-embed the whole corpus into a new index and re-check similarity thresholds. Evaluate recall on held-out queries and passages not used to build the training pairs.
- Front
- When is a reranker the smaller tune?
- Back
- When the right passages are retrieved but ranked badly. A cross-encoder reranker needs no corpus re-embedding and leaves the generator alone. Check its latency, since it runs on every query.
- Front
- What do you check on a distilled student?
- Back
- The teacher's failure slices and rare cases, not only the average, the cheaper rungs of the baseline ladder, and the terms of use for the teacher's outputs as training data.
Fine-tuning: interview drills
- Front
- The 90-second answer to 'Should we fine-tune?'
- Back
- Sort the failure (knowledge to retrieval, behaviour to prompt first, cost to caching or a smaller model). A tune must beat the best prompt-plus-retrieval baseline on the newest base, held out. Test the break-even against caching. LoRA first, gate, canary, rollback, re-run when the base changes.
- Front
- What closing line shows judgement?
- Back
- "If the failure is stale facts, I would not tune at all." Name a case where you would not use the method.
- Front
- Full fine-tuning states for 8B and 34B?
- Back
- 16 bytes per parameter: 128 GB and 544 GB. A floor: activations, logits and overhead come on top.
- Front
- LoRA parameters for a stated config?
- Back
- Sum r × (d_in + d_out) over every adapted matrix. Hidden 3,072, 28 layers, MLP 8,192, rank 16, all linear: 26,148,864, about 0.82 percent of the base linear parameters, about 0.42 GB of states.
- Front
- QLoRA states for a 34B model, adapter 0.5 percent?
- Back
- 0.5 × 34 = 17 GB base, plus 2.72 GB adapter states, plus about 0.54 GB of constants: about 20.3 GB. Not a normal batch on 24 GB; activations and logits decide.
- Front
- ZeRO per-GPU states for 34B on 16 GPUs?
- Back
- Data parallel 544 GB; ZeRO-1 161.5; ZeRO-2 97.75; ZeRO-3 34 GB. Stage 3 costs about 1.5 times the communication.
- Front
- Training time from 6ND, and LoRA?
- Back
- FLOPs = 6 × N × D; time = FLOPs ÷ sustained rate. 8B, 100M tokens, 300 TFLOP/s: about 4.4 hours; LoRA about two thirds, roughly 3.0 hours. A memory trick more than a compute trick.
- Front
- DPO loss for beta 0.25, log-ratios +0.6 and -1.4?
- Back
- Margin = 0.25 × 2.0 = 0.5; loss = -ln sigmoid(0.5) ≈ 0.474. At beta 1.0 the loss is about 0.127: the pair looks solved sooner, so the model stays nearer the reference.
- Front
- The nine parts of a tuning-program answer?
- Back
- Clarify; baseline with caching; data; method; training plan; gate; serving and rollout; upkeep; alternatives and fallback.
- Front
- Clean loss, broken production JSON?
- Back
- Template mismatch, missing end token, truncation. Decode a batch, then compare the training and serving prompts.
- Front
- Task up, general ability down?
- Back
- Forgetting. Run the regression suite on base and tuned; lower strength, smaller adapter, mix general data.
- Front
- Score jumped 15 points after a data refresh?
- Back
- Leakage or duplicates between train and evaluation. Check overlap and re-split by group.