94 Fine-Tuning Interview Questions and Answers (2026)

Fine-tuning has gone from a research trick to the default way teams ship models that actually fit their product. Interviewers know this, and they've stopped accepting "I called the Trainer API once" as an answer. They'll ask why your loss spiked, why LoRA rank matters, or why your model forgot everything it knew, and a shaky answer ends the conversation fast.
This guide gives you 94 questions with concise, interview-ready answers, plus code where it makes things clearer. They're ordered Junior → Mid → Senior, so you lock in transfer learning fundamentals before moving to QLoRA, distributed training, model merging, and evaluation. Work through them in order and you'll walk in ready to reason out loud like someone who has done this for real.
Q1.What is the difference between linear probing (feature extraction) and full fine-tuning?
Linear probing freezes the pretrained backbone and trains only a new linear head on its features. Full fine-tuning updates every weight, including the backbone. Probing tests and reuses what the model already knows. Fine-tuning reshapes the representations themselves for the new task.
Linear probing (feature extraction):
The backbone is frozen (
requires_grad=False), and only the headW·h(x) + bis learned.It is cheap: features can be precomputed once, with no backbone gradients or optimizer state.
It cannot fix features that are wrong for the task, so accuracy is capped by representation quality.
It is also used as a diagnostic: it measures how linearly separable a concept is in a layer's embeddings.
Full fine-tuning:
All parameters adapt, so it usually gives the best in-distribution accuracy when data is sufficient.
It needs much more memory and compute (gradients plus Adam states for every weight).
It risks overfitting on small data and catastrophic forgetting of general knowledge.
It can distort pretrained features and hurt out-of-distribution robustness.
The middle ground:
Partial fine-tuning updates only the top layers.
PEFT methods (LoRA, adapters) train a small number of added parameters.
LP-FT first probes to get a good head, then fine-tunes everything.
Q2.When would you fine-tune a model instead of using prompt engineering?
Fine-tune when prompting has plateaued and the gap is about consistent behavior, format, style, or a narrow skill, or when you need to cut cost and latency at scale. Prompt engineering should almost always come first because it is cheap, fast to iterate, and reversible.
Prompting is enough when:
The base model already has the capability and just needs instructions or a few examples.
Requirements change often, or you lack quality labelled data.
The missing piece is knowledge: use RAG, not fine-tuning.
Fine-tuning wins when:
You need reliable adherence to a strict output format, tone, or domain style that prompts only hit inconsistently.
The task is narrow and repeated (classification, extraction, routing) and you have hundreds to thousands of good examples.
Long prompts with many few-shot examples are eating context, cost, and latency; fine-tuning bakes that behavior into weights.
You want a smaller, cheaper model to match a larger one on a specific task (distillation).
Costs of fine-tuning to weigh: Data curation, training and eval infrastructure, re-training when the base model updates, and risk of catastrophic forgetting.
Interview framing: prompt first, add RAG for knowledge, fine-tune only when evals show a behavioral gap prompting cannot close.
Q3.What is the loss objective used during supervised fine-tuning (SFT)?
SFT uses the same next-token cross-entropy (negative log-likelihood) as pretraining, but typically computed only on the target/response tokens: prompt tokens are masked out so the model learns to produce answers, not to predict user inputs.
The objective:
Minimize L = -Σ log p(y_t | x, y_<t) over response tokens y given prompt x, with teacher forcing.
Usually averaged over the number of unmasked tokens in the batch.
Loss masking:
Set labels for prompt/system/user tokens to
-100so PyTorch'sCrossEntropyLossignores them.In multi-turn chat, train on all assistant turns (or only the final one), never on user turns; include the end-of-turn/EOS token so the model learns to stop.
Also ignore padding tokens.
Why mask: Focuses gradient on the behavior you want, and avoids wasting capacity modeling prompts (though for short-response data, some keep prompt loss as a mild regularizer).
Q4.What distinguishes instruction tuning from standard task-specific fine-tuning?
Task-specific fine-tuning teaches a model one task with a fixed input/output format. Instruction tuning trains on many tasks phrased as natural-language instructions, so the model learns the general skill of following instructions, including for tasks it never saw.
Objective:
Task-specific: maximise performance on one task (e.g. sentiment, NER), often with a classification head or a rigid template.
Instruction tuning: generalise across tasks; the instruction itself tells the model what to do.
Data:
Task-specific: many examples of a single task, usually from one dataset.
Instruction tuning: (instruction, optional input, response) triples spanning hundreds or thousands of tasks and phrasings (FLAN, T0, Alpaca-style data).
Outcome:
Task-specific: a specialist that is strong in-domain but brittle to new prompts or formats.
Instruction tuning: zero-shot ability on unseen tasks and a conversational assistant behaviour.
Shared mechanics: Both are usually supervised next-token prediction (SFT). The difference is the breadth and framing of the data, not the loss.
Trade-off: instruction tuning sacrifices some peak single-task accuracy in exchange for flexibility, and is typically the base that preference tuning (RLHF/DPO) builds on.
Q5.Why is deduplication critical when preparing an SFT dataset?
Duplicates silently up-weight some examples, so the model memorises them instead of learning general behaviour. They also waste compute and, if they overlap with eval sets, inflate benchmark scores.
Skewed training distribution:
A sample repeated 50 times acts like 50 epochs on that example. The model overfits its phrasing, style or answer.
Templated synthetic data is especially prone to this, producing repetitive, formulaic outputs.
Memorisation and regurgitation: Repeated text is far more likely to be reproduced verbatim, which is a privacy and copyright risk when it contains PII or licensed content.
Evaluation contamination:
Duplicates across train and test splits, or with public benchmarks, give misleadingly high scores.
Deduplicate against eval sets as well as within training data.
Wasted compute: SFT datasets are small and curated. Every redundant example takes budget away from diverse, informative ones.
How to do it:
Exact dedup: hash normalised text.
Near-dup: MinHash/LSH on n-grams.
Semantic dedup: embedding similarity, to catch paraphrases.
Dedup on the prompt as well as the full pair, so you catch the same question with conflicting answers.
Q6.Why are fine-tuning learning rates typically much lower than pretraining learning rates?
A pretrained model already sits in a good region of weight space; fine-tuning only needs small adjustments. Large learning rates would overwrite pretrained knowledge (catastrophic forgetting) and destabilize training, especially on small, narrow datasets.
Different goals:
Pretraining moves from random init across a huge, diverse corpus, so large steps (e.g. ~1e-4 to 6e-4 peak for many LLMs) are useful.
Fine-tuning is a local refinement, so full fine-tuning typically uses ~1e-5 to 2e-5 (often 10x+ lower).
Why large steps hurt:
Catastrophic forgetting: gradients from a narrow dataset pull weights away from general capabilities.
Small datasets give noisy gradients; big steps amplify noise and cause overfitting.
Loss spikes and divergence, since pretrained models are already near a sharp-ish minimum and optimizer state is fresh (hence warmup).
Exception: LoRA uses higher LRs: LoRA adapters (e.g. ~1e-4 to 2e-4) start from zero and are scaled by
alpha/r, and frozen base weights limit damage, so larger steps are safe.Common practice: short warmup, then cosine or linear decay, with few epochs.
Q7.Why are small SFT datasets prone to overfitting within just a few epochs?
Large LLMs have far more capacity than a few thousand examples need, so after one or two passes they can simply memorize the exact target tokens. Each extra epoch then reduces training loss by memorization rather than learning a generalizable pattern.
Capacity versus data:
Billions of parameters versus maybe millions of target tokens: the model can fit them verbatim.
Pretrained models are strong sequence memorizers already; repeated exposure accelerates verbatim recall.
Signs of overfitting:
Training loss drops sharply at each epoch boundary (staircase pattern) while validation loss rises.
Outputs parrot training phrasing, lose diversity, and general capabilities degrade (forgetting).
Low diversity compounds it: Templated or near-duplicate examples give the model a narrow pattern to latch onto.
Mitigations:
Fewer epochs (1 to 3) with early stopping on a held-out set and downstream evals, not just loss.
Lower LR, parameter-efficient methods (LoRA with small rank), dropout or weight decay.
Increase diversity, deduplicate, and mix in general instruction data to preserve capabilities.
Nuance: slightly rising validation loss doesn't always mean worse outputs (LIMA saw quality improve past that point), so judge by generation quality too.
Q8.How does gradient accumulation allow larger effective batch sizes under memory constraints?
Gradient accumulation runs several small micro-batches, each with its own forward and backward pass, and sums their gradients before taking a single optimizer step. Peak memory is set by the micro-batch, but the update matches what one large batch would produce.
Why it saves memory:
Activation memory scales with the micro-batch size.
After each backward pass, activations are freed and only the
.gradbuffers persist. Those buffers are a fixed size, regardless of how many micro-batches you accumulate.
Effective batch size:
effective = micro_batch × accumulation_steps × num_GPUsCorrectness details:
Scale each micro-batch loss by
1/kso the result is an average, not a sum.With variable-length sequences, normalize by the total token count across all micro-batches. Averaging per-micro-batch means gives a subtly wrong gradient.
Not exactly equivalent when layers depend on batch statistics (BatchNorm); this is rarely an issue for LLMs, which use LayerNorm.
In DDP, use
no_sync()on non-final micro-batches to avoid redundant all-reduces.
Cost: no extra memory, but steps take longer in wall-clock time, since micro-batches run sequentially and you get no added parallelism.
Q9.What is Low-Rank Adaptation (LoRA)?
LoRA is a parameter-efficient fine-tuning method. It freezes the pretrained weights and learns only a low-rank update to selected weight matrices, so a model can be adapted by training well under 1% of its parameters.
Core idea:
For a frozen weight
W(d×k), learnΔW = B·A, whereBis d×r,Ais r×k, and r ≪ min(d, k).Forward pass:
h = W·x + (α/r)·B·A·x.
Initialisation:
Ais random (Gaussian) andBis zero, soΔW = 0at step 0.Training therefore starts exactly from the pretrained model.
Why it's useful:
It needs far fewer gradients and optimizer states, so it fits on much smaller GPUs.
Adapters are tiny files (MBs, not GBs). You can keep one base model and swap task-specific adapters.
ΔWcan be merged intoWafter training, which gives zero extra inference latency.
Variants: QLoRA (LoRA on a 4-bit quantized base), DoRA, and rsLoRA.
Q10.How do you count the number of trainable parameters LoRA adds to a weight matrix?
For a weight matrix of shape d×k, LoRA adds two matrices: B (d×r) and A (r×k). That is r·(d + k) trainable parameters, compared with d·k for the full matrix.
Worked example: a 4096×4096 projection with r = 8:
LoRA adds 8 × (4096 + 4096) = 65,536 parameters.
The full matrix has 16,777,216 parameters, so the adapter is about 0.39% of it.
Totals across the model:
Sum
r·(d_in + d_out)over every targeted matrix in every layer.Example: targeting q and v in 32 layers gives 2 × 32 × 65,536 ≈ 4.2M parameters.
Non-square matrices count the same way: An MLP up-projection of 4096→11008 at r = 8 adds 8 × (4096 + 11008) ≈ 121K parameters.
Scaling behaviour: the cost is linear in r and in d + k, while the full matrix grows with d·k. This is where the savings come from.
Q11.What is the fundamental difference between LoRA and QLoRA?
Both train the same small low-rank adapters on a frozen base model. The difference is how the frozen base is stored. LoRA keeps it in 16-bit, while QLoRA quantizes it to 4-bit NF4, cutting base-model memory by about 4x so much larger models fit on one GPU.
How QLoRA computes:
Weights are stored in 4-bit and dequantized on the fly to
bf16for each matmul.Gradients flow through the frozen quantized weights into the
bf16LoRA adapters, which are the only trained parameters.
Extra memory tricks in QLoRA:
NF4data type.Double quantization of the scaling constants.
Paged optimizers, which absorb memory spikes.
Together these let you fine-tune a 65B model on a single 48GB GPU.
Trade-offs:
Training is slower because of the dequantization overhead.
There is slight quantization error, though the paper reports quality matching 16-bit fine-tuning.
Merging adapters requires dequantizing the base, or keeping the adapters separate.
Q12.How does parameter-based prompt tuning differ from prompt engineering?
Prompt engineering hand-writes discrete text instructions and trains nothing. Prompt tuning instead learns continuous "soft prompt" embedding vectors by gradient descent, which are prepended to the input while the model stays frozen.
What is optimized:
Prompt engineering: tokens chosen from the vocabulary by human trial and error.
Prompt tuning: a matrix of shape
num_virtual_tokens × d_modelin embedding space, trained on labeled task data.Soft prompts are not restricted to real tokens, so they can encode signals no text prompt can express.
Requirements:
Prompt tuning needs training data, gradient access, and the model's weights (or at least backprop through them).
Prompt engineering works on any black-box API.
Properties of soft prompts:
Tiny per-task artifact (often a few thousand to ~100k params), and one frozen model can serve many tasks.
Not human-readable, and not transferable across different models.
Quality improves with model scale: Lester et al. showed it approaches full fine-tuning around 10B+ params but lags on small models.
In
peft:PromptTuningConfig(num_virtual_tokens=20), optionally initialized from the embeddings of a text prompt.
Q13.What is continued pretraining?
Continued pretraining (also called domain-adaptive pretraining) resumes the original next-token-prediction objective on a large unlabeled corpus from a new domain or language. The goal is to inject knowledge and vocabulary, typically before instruction tuning.
How it differs from SFT:
Continued pretraining uses raw text (papers, code, legal docs, a new language) with loss on all tokens. It teaches what the model knows.
SFT uses instruction/response pairs with loss usually on responses only. It teaches how the model behaves and formats answers.
Typical recipe:
Curate and deduplicate the domain corpus, often billions of tokens.
Mix in general "replay" data to limit catastrophic forgetting.
Re-warm with a lower peak learning rate than the original pretraining, then decay.
For new languages, consider extending the tokenizer and training
embed_tokensandlm_head.Follow with SFT (and preference tuning) to restore chat behavior.
Full training vs LoRA:
Usually done with full fine-tuning.
LoRA works if you use high rank and also train the embeddings and LM head, but it absorbs less knowledge.
Examples: Code Llama (Llama 2 continued on code) and Gururangan et al.'s "Don't Stop Pretraining" (DAPT/TAPT).
Q14.What is catastrophic forgetting in the context of fine-tuning?
Catastrophic forgetting is when fine-tuning on new data overwrites weights that encoded earlier capabilities. The model gets better at the target task but noticeably worse at things it used to do well.
Why it happens:
Gradient descent optimizes only the new loss, so nothing in the objective preserves the old behavior.
Knowledge is distributed across shared parameters. Narrow data, a high LR, and many epochs all push those weights far from the pretrained solution.
Typical symptoms in LLMs:
Weaker general reasoning, coding, or math.
Loss of other languages.
Broken instruction following or chat formatting.
Eroded safety alignment, even from benign fine-tuning data.
How to detect it: Track general benchmarks (e.g. MMLU), held-out general prompts, and safety evals before and after training, not just target-task metrics.
Mitigations:
Replay of general data.
PEFT such as LoRA.
Lower LR and fewer epochs.
Regularization toward the original weights or outputs (EWC, KL penalty).
Multi-task mixing.
Q15.What is the conceptual difference between knowledge distillation and direct supervised fine-tuning?
SFT trains a model to match fixed ground-truth labels (one correct token per position); knowledge distillation trains a student to imitate a teacher model, usually its full output distribution, so the learning target is the teacher's behavior rather than the dataset's labels.
Target signal:
SFT: cross-entropy against one-hot labels; says only "this token is right".
KD: KL divergence to the teacher's soft distribution; also says "these alternatives are plausible, these are not" (the "dark knowledge"), giving far more information per example.
Data requirements:
SFT needs labeled, human-quality targets.
KD only needs inputs: the teacher produces targets, so unlabeled or synthetic prompts suffice.
Ceiling and goal:
SFT's ceiling is label quality; KD's ceiling is the teacher (student inherits its errors and biases).
KD is primarily a compression/transfer technique; SFT is a capability/behavior-teaching technique.
They blur in practice: training on teacher-generated text (sequence-level KD) is mechanically just SFT on synthetic data; the conceptual difference is where the targets come from. Often both are combined:
loss = α·CE(labels) + (1−α)·KL(teacher‖student).
Q16.What is model merging?
Model merging combines the weights of several models into one model without further training. The models typically share an architecture and are fine-tuned from the same base. The result can carry the combined skills at the inference cost of a single model.
Why it works: Fine-tunes of a shared base tend to stay in the same loss basin. Their weights (or deltas from the base) can therefore be combined arithmetically without breaking the model.
Common methods:
Linear averaging / model soups: a weighted mean of the weights.
SLERP: spherical interpolation between two models.
Task arithmetic: add or subtract task vectors (fine-tuned weights minus base weights).
TIES and DARE: sparsify the deltas and resolve conflicts between them to reduce interference.
Passthrough ("frankenmerges"): stack layers from different models.
Benefits:
No training data or GPUs needed (runs on CPU with tools like
mergekit).Can combine skills, improve robustness, or recover general ability lost during a narrow fine-tune.
Limits:
Requires a compatible architecture and tokenizer, and usually a shared initialization.
Parameter interference can degrade every merged skill, so the merge must be evaluated.
Q17.How do you distinguish task adaptation from overfitting using training and validation loss curves?
Task adaptation shows training and validation loss falling together and then plateauing. Overfitting shows training loss still falling while validation loss bottoms out and climbs, so the gap between them keeps widening. Confirm the diagnosis with task metrics, because loss alone can mislead.
Healthy adaptation pattern:
Both losses drop sharply early. The model is mostly learning format, style and the output distribution, which are cheap wins.
Validation loss then flattens close to training loss, leaving a small and stable gap.
Overfitting pattern:
Validation loss reaches a minimum and then rises, while training loss keeps decreasing toward near zero.
Multi-epoch SFT often shows staircase drops in training loss at each epoch boundary. That is a sign of memorizing seen examples.
Outputs start parroting training phrasing, and general capabilities degrade.
Don't trust loss alone:
Validation loss can tick up while task accuracy still improves, because the model grows more confident and is penalized harder on wrong tokens. Track the real metric (accuracy, F1, win rate) per checkpoint.
Run a small general-capability probe alongside, to catch forgetting that in-domain validation loss can't see.
Make the comparison valid:
Use a held-out set with no near-duplicates of training data. Leakage hides overfitting.
Compute loss the same way on both splits, with the same masking (for example, completion tokens only).
Response:
Pick the checkpoint at the best validation metric, or use early stopping.
Reduce epochs or learning rate, add data or diversity, or use regularization (dropout, LoRA instead of full fine-tuning).
Q18.What is the intuition behind using discriminative (layer-wise) learning rates during fine-tuning?
Different layers hold different kinds of knowledge, so they should change by different amounts. Lower layers encode general features that already fit the new task, so they get small learning rates. Upper layers are task- and objective-specific, so they get larger ones. This adapts the model without wrecking what transfers.
Layers are not equally transferable:
Early layers capture generic structure: edges and textures in vision, morphology and syntax in language.
Late layers specialize to the pretraining objective and need the most rewriting.
Protects against forgetting:
A single high LR would overwrite useful low-level features (catastrophic forgetting).
A single low LR would under-adapt the top layers.
How it's implemented:
ULMFiT (Howard & Ruder, 2018) divides the LR by about 2.6 per layer going down.
For BERT-style models, layer-wise LR decay (LLRD) multiplies the LR by a factor of roughly 0.8 to 0.95 per layer from the top.
In practice this is done with optimizer parameter groups.
It is often combined with gradual unfreezing and warmup. All three serve the same goal: stable adaptation that preserves pretrained knowledge.
Q19.Why do early layers of a deep neural network transfer across domains better than later layers?
Deep networks build features hierarchically. Early layers learn simple, low-level patterns that appear in almost any data from that modality. Later layers compose these into abstractions tied to the specific pretraining data and objective, so they transfer less well.
Early layers are general:
In CNNs, first layers learn Gabor-like edge and color-blob detectors almost regardless of dataset.
In language models, lower layers capture token identity, morphology and local syntax.
These are statistics shared by all natural images or all text.
Later layers are specific:
They encode class- or objective-specific concepts (e.g., dog breeds, next-token heuristics) that may not exist in the target domain.
They have large receptive fields and context, so they model domain-specific configurations rather than primitives.
Empirical evidence:
Yosinski et al. (2014) showed transferability drops with depth, and drops faster as source and target domains diverge.
They also found splitting co-adapted middle layers hurts performance (fragile co-adaptation).
Practical consequences:
Freeze or use low LRs on the bottom layers.
Retrain the top layers.
Under large domain shift, unfreeze deeper.
Q20.Why is gradual unfreezing applied to transformer layers during domain adaptation?
Gradual unfreezing trains the top layers first and unfreezes lower layers one stage at a time. The new head and task-specific layers settle before gradients reach the general-purpose lower layers. This prevents early, noisy updates from destroying pretrained knowledge (catastrophic forgetting).
The problem it solves:
At the start, a randomly initialized head produces large, poorly directed gradients.
If every layer is trainable, these gradients propagate down and distort good low-level features before the head is useful.
How it works (ULMFiT style):
Freeze everything except the head or last block, then train briefly.
Unfreeze the next layer group down and train.
Repeat until the whole network trains. This is usually combined with discriminative LRs and warmup.
Why it suits domain adaptation:
Top layers need the most change for the new domain, while bottom layers mostly transfer.
The schedule spends adaptation where it's needed and touches general features last and most gently.
It is especially helpful with small target datasets, where overfitting and forgetting are likely.
Trade-offs:
It adds schedule hyperparameters.
For large LLMs it is often replaced by warmup with a low LR, LP-FT, or PEFT methods (LoRA), which keep the base frozen entirely.
Q21.Under what dataset constraints would you choose linear probing over full fine-tuning?
Choose linear probing when the labeled data is too small or too unreliable to safely update millions of parameters, and the target domain is close enough that frozen features already separate the classes. Under those conditions full fine-tuning mostly adds overfitting and forgetting.
Very few labeled examples:
With tens to a few hundred examples per class, full FT has huge capacity relative to the data and overfits.
A linear head has few parameters and is well regularized.
Target close to pretraining distribution:
If embeddings are already linearly separable for the task, updating the backbone yields little gain.
Quick check: compare probe accuracy against a small fine-tuning run.
Noisy or weak labels: A frozen backbone cannot memorize noise into its features.
Expected distribution shift at test time: Probing preserves pretrained features and often generalizes better out of distribution than full FT.
Related practical constraints:
Limited compute or memory.
Many tasks sharing one backbone.
Need for fast iteration.
When to switch to fine-tuning: Use full FT or PEFT with large, clean datasets, or when the domain differs strongly (new modality, specialized jargon) so the features themselves must change.
Q22.How does domain shift between the pretraining corpus and the fine-tuning dataset affect adaptation?
The larger the gap between pretraining and target data, the less pretrained features fit and the more the model must change. That means more data and compute, deeper adaptation, and a higher risk of forgetting. Small shifts can be handled with light adaptation. Large shifts often need continued pretraining first.
Small shift (e.g., news to reviews):
Pretrained features transfer well.
Linear probing, LoRA, or a few epochs of low-LR fine-tuning suffice.
Large shift (e.g., web text to clinical notes, code, a new language):
Features and even lower layers may be mismatched, so frozen or low-rank methods can underfit.
Domain-adaptive pretraining on unlabeled in-domain text before task fine-tuning helps substantially (Gururangan et al., "Don't Stop Pretraining").
Tokenization mismatch:
Domain terms fragment into many subword tokens, which wastes context and weakens representations.
Vocabulary extension (with new embedding training) may be needed.
Forgetting vs. plasticity trade-off:
Bigger shifts require bigger updates, which overwrite general capabilities.
Mitigations: mix in general replay data, regularize toward the base weights, or use PEFT.
Evaluation:
Measure in-domain gains and general benchmarks together.
A model can improve on the target while silently regressing elsewhere.
Q23.How do you determine whether a target task has sufficient labelled data to justify fine-tuning over few-shot prompting?
There is no fixed threshold: you decide empirically by establishing a strong few-shot baseline, then measuring how fine-tuning performance scales with data on a held-out eval set. If a learning curve shows fine-tuning clearly beats the baseline with the data you have (or can affordably get), it is justified.
Build the baseline first: Optimize the few-shot prompt (example selection, instructions) and score it on a fixed held-out test set with task-appropriate metrics.
Run a data-scaling experiment:
Fine-tune (cheaply, e.g. LoRA) on subsets such as 100, 500, 1k, all examples.
Plot metric vs. dataset size against the few-shot line.
If the curve is still rising, more data will help; if it crosses the baseline early, you have enough; if flat below baseline, fine-tuning is not the answer.
Quality and coverage matter more than raw count:
Check label consistency (inter-annotator agreement), coverage of input variety and edge cases, and class balance.
A few hundred clean, diverse examples often beat thousands of noisy ones.
Rough heuristics:
Narrow format/style tasks can benefit from ~50 to a few hundred examples; complex reasoning or many classes needs thousands.
Can you generate or label more cheaply (synthetic data from a stronger model, weak labels)? That shifts the decision.
Also factor in the business gain: the improvement must outweigh training, maintenance, and re-labelling costs.
Q24.Why is loss masking applied to prompt tokens during SFT?
Masking sets prompt token labels to an ignore value so the loss is computed only on the response. The model is then trained to produce good answers given a prompt, rather than spending capacity learning to model or regurgitate user prompts.
Aligns the objective with inference: At inference the prompt is always given; only the response is generated. So only the response should drive gradients.
Avoids learning the wrong behaviour:
Unmasked prompts teach the model to imitate user-style text and templated system prompts.
Long prompts (documents, RAG context) would otherwise dominate the loss and dilute the response signal.
How it works:
Prompt positions get label
-100, which PyTorch'sCrossEntropyLossignores viaignore_index.Prompt tokens still pass through attention as context, so the model conditions on them. They just contribute no loss.
In multi-turn chats, all user/system turns are masked and every assistant turn (including its end-of-turn token) is trained.
Caveat: on small or short-prompt datasets the difference can be modest, and some work finds prompt loss mildly helpful. Masking is still the standard default.
Q25.Why does a mismatch between training and inference chat templates degrade output quality?
During SFT the model learns that specific special tokens and formatting mark roles and turn boundaries. If inference uses a different template, the prompt falls outside the training distribution, so the learned turn-taking and stopping behaviour fails to trigger.
The template is learned signal, not decoration:
Tokens like
<|im_start|>assistantor[INST]tell the model "now produce an assistant reply".Fine-tuned behaviour is conditioned on seeing exactly those tokens.
Typical symptoms:
It never emits the end-of-turn/EOS token, so it rambles or keeps writing the user's next turn.
It ignores system prompts or confuses roles.
It reverts to base-model completion style, and instruction-following quality drops.
Subtle causes:
Whitespace or newline differences change the tokenization.
A BOS token gets added twice.
The generation prompt suffix is missing.
Special tokens are tokenized as plain text.
Fix: use one source of truth:
Apply
tokenizer.apply_chat_templatein both training and serving, withadd_generation_prompt=Trueat inference.Ship the template inside the tokenizer config.
Q26.How does sequence packing improve compute utilisation during SFT?
Packing concatenates several short examples into one fixed-length sequence instead of padding each to the max length. Nearly every token the GPU processes is then real data, which reduces wasted FLOPs and the total number of steps.
The problem: padding waste:
SFT examples vary widely in length. Padding to the batch or global maximum can make a large fraction of tokens pad tokens.
Pad tokens still consume attention and MLP compute and memory, yet contribute no loss.
What packing does:
It fills each context window (e.g. 4096 tokens) with multiple examples separated by EOS.
The result is fewer, denser sequences: higher tokens/sec, fewer optimizer steps per epoch, and predictable memory use.
Doing it correctly:
Block cross-example attention with a block-diagonal mask or varlen attention (FlashAttention
cu_seqlens,position_idsreset per example).Keep per-example loss masks. In TRL this is
SFTConfig(packing=True).
Side effects:
Changes the effective batch size in examples, so step counts and LR schedules need adjusting.
Long examples can dominate loss weighting.
Naive greedy packing may truncate or split examples.
Q27.What unique considerations arise when constructing fine-tuning examples for multi-turn conversations compared to single-turn instructions?
Multi-turn examples must teach the model to use conversation history, keep roles straight and respond to the latest turn. That raises questions single-turn data never faces: which turns to train on, how to format and truncate history, and whether the history itself is coherent.
Loss masking across turns:
Train on every assistant turn in a single pass, not just the last one, and mask user and system turns.
Alternatively, unroll each conversation into one example per assistant turn. This costs more compute and over-weights early turns.
Formatting:
Apply the chat template consistently: role tokens, end-of-turn tokens after each assistant reply, and the system prompt placement.
Template errors compound over many turns.
Context length and truncation:
Long dialogues exceed the window. Truncate from the oldest turns, not mid-response.
Never keep an assistant turn whose triggering user turn was cut.
Context dependence:
Include turns that require earlier information: coreference ("make it shorter"), corrections, clarifying questions, and topic shifts.
Otherwise the model learns to ignore history.
Consistency and quality:
Every assistant turn becomes a target, so one bad mid-conversation reply teaches errors.
Persona and facts must stay consistent across turns.
Distribution: Mix conversation lengths and keep some single-turn data, so the model handles both short queries and long sessions.
Q28.Why does increasing the number and diversity of tasks in instruction tuning improve zero-shot generalisation?
With many diverse tasks, the cheapest way to lower the loss is to learn the general skill "read the instruction and do what it says" rather than memorise task-specific shortcuts. That general skill is exactly what transfers to unseen tasks.
Forces abstraction over memorisation:
With few tasks, the model can map surface patterns to outputs.
With thousands of tasks, it must actually condition on the instruction text.
Better coverage of the task space: A new task is more likely to resemble some combination of seen tasks (formats, reasoning types, domains), so it falls closer to the training distribution.
Unlocks latent pretraining knowledge: The model already knows a lot. Diverse instructions teach it the interface for applying that knowledge on demand.
Template and phrasing diversity matters too: Multiple phrasings per task reduce sensitivity to exact prompt wording.
Empirical evidence:
FLAN, T0 and Flan-T5/PaLM (~1.8K tasks) show held-out performance rising with the number of task clusters, with diminishing returns.
Gains appear mainly at sufficient model scale; small models can even get worse.
Mixing in chain-of-thought and few-shot formats further broadens generalisation.
Caveat: diversity beats raw volume. Many near-duplicate examples of one task add little; quality and balance across tasks matter.
Q29.What does the LIMA result suggest about data quality versus quantity in fine-tuning?
LIMA (Zhou et al., 2023) fine-tuned a 65B LLaMA on only ~1,000 carefully curated prompt/response pairs and got responses competitive with much larger instruction-tuned systems in human preference studies. The takeaway: for alignment-style SFT, a small set of high-quality, diverse examples can matter more than a large, noisy one.
The Superficial Alignment Hypothesis:
Knowledge and capabilities come from pretraining; SFT mostly teaches the format and style of interacting with users.
If SFT only selects a "mode" the model already has, a few clean demonstrations are enough to unlock it.
What made the 1,000 examples work:
Quality: consistent, helpful, well-written answers (curated from community Q&A plus hand-written ones).
Diversity: broad coverage of tasks and topics rather than many near-duplicates.
Their ablations: scaling up quantity without adding diversity gave little gain, while filtering for quality helped.
Limits of the claim:
It applies to style/alignment tuning, not to teaching new knowledge or hard skills (math, code, new domains), which still need more data.
It relies on a strong base model; weak bases can't be "unlocked" by 1,000 examples.
LIMA still lagged on multi-turn and safety-heavy prompts versus RLHF-trained models.
Practical lesson: invest in curation, deduplication, and diversity before scaling example count.
Q30.Why is benchmark decontamination critical when assembling an instruction fine-tuning dataset?
Decontamination removes examples that overlap with evaluation benchmarks from your training set. Without it, the model may memorize test items, inflating scores so they measure recall rather than generalization, and you lose the ability to trust any comparison or decision based on those benchmarks.
Why contamination is easy in instruction data:
Instruction datasets are scraped or aggregated from the web, GitHub, and other public sets that often contain benchmark questions (MMLU, GSM8K, HumanEval).
Synthetic data from a teacher can regurgitate benchmark items the teacher itself memorized.
What goes wrong:
Inflated scores hide regressions and make model/checkpoint selection unreliable.
Hyperparameter and data-mix choices get optimized toward leaked items, not real capability.
Published comparisons become invalid and credibility suffers once discovered.
How it's done:
Exact and normalized string matching against benchmark test (and ideally dev) sets.
N-gram overlap (e.g. 13-gram matches, as in GPT-3 style checks) to catch partial copies.
Embedding similarity or LLM judges to catch paraphrases and translated variants.
Remove or quarantine hits, and report the contamination analysis alongside results.
Complement with held-out, private, or freshly created evals that can't have leaked.
Q31.What is synthetic data distillation when preparing an SFT corpus?
Synthetic data distillation means using a stronger "teacher" LLM to generate instruction/response pairs (or responses to your own prompts) and then fine-tuning a smaller "student" on those outputs with standard SFT. The student imitates the teacher's behavior at a fraction of the inference cost.
Typical pipeline:
Collect or generate prompts covering the target tasks (seed sets, self-instruct, real user queries).
Have the teacher produce responses, often with a strong system prompt, chain-of-thought, or multiple samples.
Filter: dedupe, verify (unit tests for code, answer checks for math), score with a judge or reward model, keep the best (rejection sampling).
Decontaminate against benchmarks and fine-tune the student.
Why it's popular:
Cheap and fast versus human annotation; examples: Alpaca, Vicuna-style data, Orca (explanation traces), reasoning traces from R1-style models.
Consistent style, and it can transfer reasoning patterns when traces are included.
Distinct from logit distillation: This is sequence-level: the student trains on teacher text with cross-entropy, so you only need API access, not teacher logits.
Caveats: student inherits teacher errors and biases, can mimic style without capability, and teacher license terms may forbid training competing models.
Q32.How do label noise and inconsistent output style across SFT examples affect fine-tuning?
SFT is maximum-likelihood imitation, so the model learns whatever the targets contain. Wrong labels teach wrong answers (and hallucination), and inconsistent styles force the model to learn a blurred mixture, producing unpredictable formats and weaker task performance per example.
Label noise (incorrect or low-quality targets):
With small datasets each bad example has large influence; the model can memorize errors.
Answers stating facts the base model doesn't know can teach it to confidently fabricate.
Noisy gradients raise the loss floor and make validation loss a less reliable signal.
Inconsistent output style:
Same kind of prompt answered with different lengths, formats (JSON vs prose), tones, or refusal policies: the model learns a distribution over these and samples among them.
Result: format breakage in production, parsing failures, unstable verbosity.
Capacity is spent learning style variance instead of the task.
Mitigations:
Write annotation guidelines and a style spec; measure inter-annotator agreement.
Normalize/rewrite targets to one format, or condition style explicitly via the system prompt.
Filter with validators, judge models, or loss-based outlier detection (high-loss examples are often mislabeled).
Prefer fewer clean examples over more noisy ones.
Q33.How does the self-instruct method generate instruction-tuning data?
Self-instruct (Wang et al., 2022) bootstraps instruction data from the model itself: start with a small human-written seed set, prompt an LLM to generate new instructions and responses, filter them, add survivors back to the pool, and repeat. The resulting dataset is then used for SFT (Stanford Alpaca used this with a stronger teacher).
The loop:
Seed: 175 hand-written tasks, each with an instruction and an example.
Instruction generation: sample a few tasks from the pool as in-context examples and ask the model to write new instructions.
Classification check: decide whether each task is a classification task, which changes how instances are generated.
Instance generation: input-first for open tasks; output-first for classification (generate the label, then an input) to avoid label imbalance.
Filter and add: drop near-duplicates (ROUGE-L overlap > 0.7 with existing tasks), invalid or unsuitable tasks (e.g. needing images), then add to the pool.
Why it works:
Cheap diversity at scale (~52K instructions in the paper) with minimal human labor.
Fine-tuning vanilla GPT-3 on it closed much of the gap to InstructGPT-001.
Weaknesses:
Many generated outputs are wrong or shallow; quality is bounded by the generator.
Diversity drifts toward the model's favorite topics; later variants (Evol-Instruct, stronger filtering, judge scoring) address this.
Q34.Why is a warmup phase useful when fine-tuning a pretrained model?
Warmup ramps the learning rate from near zero up to its target over the first few hundred steps. Early updates are the least reliable: optimizer statistics are still empty and newly added layers produce large, noisy gradients. Starting at full learning rate can knock the pretrained weights out of their good region before training settles.
Adam's statistics start out unreliable:
The second-moment estimate
vis built from only a handful of gradients, so it has high variance. The per-parameter step sizelr / sqrt(v)can be erratically large.A small learning rate during this window keeps those noisy steps harmless (this is the motivation behind RAdam).
Protecting pretrained features:
A freshly initialized head (classifier, reward head) produces large gradients that backpropagate into the pretrained body.
Big early steps can overwrite useful representations: catastrophic forgetting, or an early loss spike the run never recovers from.
Distribution shift:
The fine-tuning data and prompt format differ from pretraining, so the first gradients point in sharp, inconsistent directions.
Warmup lets the model adapt gradually.
Stability of large transformers:
Deep transformers (especially Post-LN ones) are known to diverge without warmup.
With mixed precision, warmup also reduces the risk of fp16 overflow early in training.
Typical practice:
Use linear warmup over roughly 1–10% of steps (e.g.
warmup_ratio=0.03), then cosine or linear decay.Use longer warmup for larger learning rates, larger models, or small batches.
Q35.How do small batch sizes affect gradient stability when fine-tuning an LLM?
A small batch averages fewer examples, so each gradient is a noisier estimate of the true gradient. Updates zig-zag, the loss becomes jumpy, and outlier examples can dominate a step. You compensate with a lower learning rate, gradient clipping, or gradient accumulation.
Variance scales roughly as 1/B:
The mini-batch gradient's variance falls inversely with batch size
B.With B=1–4, a single unusual example (very long, mislabeled, off-distribution) can steer the whole update.
LLM-specific amplifiers:
Token counts vary between batches: a batch with few supervised tokens (e.g. heavy masking of prompt tokens) yields a much noisier loss.
Adam's moment estimates get noisy too, so per-parameter step sizes fluctuate.
Noisy steps raise the odds of loss spikes and divergence, especially in fp16.
Interaction with learning rate:
The "noise scale" is roughly proportional to lr / B, so a small batch at a large learning rate is unstable.
Common heuristics scale the learning rate down linearly or by square root as batch size shrinks.
Not purely bad:
Some gradient noise acts as a regularizer and can help generalization on small fine-tuning datasets.
Small batches also mean more updates per epoch.
Mitigations:
Gradient accumulation, to raise the effective batch size.
Gradient clipping (
max_grad_norm=1.0).A lower learning rate with warmup, and bf16 instead of fp16.
Q36.How does gradient checkpointing trade compute for memory?
Gradient checkpointing keeps only a few activations (typically each layer's input) instead of every intermediate tensor. During the backward pass, the forward computation of each segment is re-run to rebuild what was discarded. Activation memory drops sharply at the cost of roughly one extra forward pass.
Normal backprop:
Every intermediate activation (attention outputs, MLP hidden states, norms) is stored for the backward pass.
Memory therefore grows with layers × batch × sequence length.
With checkpointing:
Forward: save only the checkpoint tensors at segment boundaries (usually one per transformer block) and discard the rest.
Backward: for each segment, recompute its forward from the saved checkpoint, then backprop through it.
The trade-off:
Memory: activations go from O(L) full layer states to roughly checkpoints plus one segment's internals (O(√L) with optimal spacing).
Compute: about one extra forward pass, typically ~20–35% slower training.
The freed memory often enables larger batches or longer sequences, which can offset some of the slowdown.
In practice:
Enable with
model.gradient_checkpointing_enable()ortorch.utils.checkpoint.Set
use_cache=Falseduring training.Commonly combined with LoRA/QLoRA to fit large models on a single GPU.
Q37.What is the difference between ZeRO stages 1, 2, and 3?
ZeRO removes the redundancy of data parallelism, where every GPU holds a full copy of the training state. It shards that state across GPUs, and each stage shards more of it. Stage 1 shards optimizer states, Stage 2 also shards gradients, and Stage 3 also shards the parameters themselves.
Baseline (mixed-precision Adam):
About 16 bytes per parameter: 2 (weights) + 2 (gradients) + 12 (fp32 master weights plus Adam moments).
Optimizer state is the largest piece.
ZeRO-1: shard optimizer states:
Each GPU updates only its 1/N slice of the master weights and Adam moments.
Roughly a 4× memory reduction at large N.
Same communication volume as plain DDP.
ZeRO-2: also shard gradients:
Gradients are reduce-scattered, so each GPU keeps only the shard it needs for its optimizer slice.
Roughly an 8× reduction.
Still the same communication volume as DDP.
ZeRO-3: also shard parameters:
Each layer's weights are all-gathered just in time for its forward and backward passes, then freed.
Memory falls linearly with the number of GPUs, which allows models that don't fit on one device.
Costs about 1.5× DDP communication, plus more latency sensitivity.
Related options:
ZeRO-Offload and ZeRO-Infinity push states to CPU or NVMe.
PyTorch FSDP equivalents:
FULL_SHARD≈ ZeRO-3 andSHARD_GRAD_OP≈ ZeRO-2.Rule of thumb: choose the lowest stage that fits, since each step up adds overhead.
Q38.Why does activation memory grow quickly with sequence length during fine-tuning?
Every layer must save its intermediate tensors for backprop, and almost all of them scale with the number of tokens. So activation memory grows at least linearly with sequence length. Naive attention adds a term that grows quadratically, because it stores a seq × seq score matrix per head.
Linear terms (per layer, per token):
Hidden states, Q/K/V, attention outputs, norm inputs, and the MLP intermediate (often about 4× hidden size) are all stored.
These scale as
batch × seq × hidden × layers, so doubling the sequence doubles them.
Quadratic term:
Standard attention materializes scores and softmax probabilities of size
batch × heads × seq²per layer.At long contexts this dominates: 8k tokens means 64M entries per head per layer.
Logits are a hidden giant:
The output logits are
batch × seq × vocab, and vocabularies run to 100k+ entries.They are often upcast to fp32 for the loss, which can take several GB on its own.
Why this matters in fine-tuning:
Even with LoRA (tiny optimizer state), activations still flow through the full frozen model.
As a result, activation memory, not weight memory, is what limits long-context fine-tuning.
Mitigations:
FlashAttention: recomputes attention tiles and never stores the seq² matrix, which makes attention memory linear.
Gradient checkpointing.
Chunked or fused cross-entropy.
Smaller micro-batches with gradient accumulation.
Sequence or context parallelism.
Q39.What role does the LoRA alpha scaling hyperparameter play relative to the rank?
Alpha sets the magnitude of the LoRA update. The update is scaled by α/r, which decouples how strongly the adapter affects the output from the rank you choose. You can then change r without re-tuning the learning rate.
Mechanics:
The effective update is
ΔW = (α/r)·B·A.With Adam, raising α acts roughly like a larger learning rate on the adapter.
Why divide by r:
Without it, a larger r sums more rank-1 terms and would grow the update's scale.
The original paper fixes α and varies r so that hyperparameters transfer across ranks.
Common practice:
Set
α = r(scale 1) orα = 2r(scale 2).If you scale α with r, the update strength stays constant.
Caveat at high rank:
With a fixed α,
α/rshrinks as r grows, so high-rank adapters can under-learn.rsLoRA instead uses
α/√rto keep learning stable at large ranks.
Q40.Why does merging a trained LoRA adapter back into the base weights add no inference latency?
Merging folds the adapter into a single matrix, W' = W + (α/r)·B·A, with the same shape as W. The merged model therefore runs exactly the same architecture and matmuls as the original, with no extra computation.
Unmerged inference has overhead:
Each adapted layer computes
W·xplusB·(A·x).That is two extra small matmuls and extra kernel launches per layer. The FLOPs are small, but the sequential ops add latency.
Why merging works:
The update is purely linear and additive:
W·x + BA·x = (W + BA)·x.So it can be precomputed once, offline.
Contrast with adapter layers (Houlsby-style): they insert new sequential modules with nonlinearities, which cannot be folded away.
Trade-offs:
A merged model serves one task. Multi-adapter serving keeps adapters unmerged to batch many LoRAs over one shared base (e.g. S-LoRA, vLLM multi-LoRA).
With a quantized base (QLoRA), merging requires dequantizing first. Re-quantizing afterwards can cost some accuracy.
Q41.What is the low-rank hypothesis that justifies LoRA?
The hypothesis is that the weight change needed to adapt a pretrained model to a task has low intrinsic rank. A small number of directions captures most of ΔW, so constraining it to B·A with small r loses little quality.
Origins:
Aghajanyan et al. (2020) showed that pretrained models have a low intrinsic dimension. Fine-tuning in a small random subspace recovers most of full fine-tuning performance.
LoRA (Hu et al., 2021) extends this idea to the update matrices themselves.
Intuition:
Pretraining already learned rich features.
Adaptation mostly re-weights or amplifies a few task-relevant directions rather than learning new representations.
Empirical support from the LoRA paper:
On GPT-3, ranks as low as 1 to 8 matched full fine-tuning.
The top singular directions learned at different ranks overlapped heavily.
Limits:
The hypothesis holds less well when the task is far from the pretraining distribution (new languages, heavy domain shift, continued pretraining).
Those cases need higher rank or full fine-tuning.
Q42.Which transformer weight matrices does LoRA most commonly target, and why?
The original LoRA paper targeted the attention query and value projections (W_q, W_v). Modern practice usually targets all linear layers, attention and MLP alike, because it gives better quality for a modest parameter increase.
Why
qandvoriginallyHu et al. compared configurations under a fixed parameter budget on GPT-3.:
Adapting
W_qandW_vat low rank beat adapting a single matrix at higher rank.Spreading capacity across matrices helped more than raising rank.
Why all linear layers now:
Layers covered:
q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj, anddown_proj.The QLoRA paper found that adapting all linear layers was key to matching full fine-tuning.
MLP blocks hold most of the parameters and much of the factual and stylistic knowledge.
Usually left out:
Embeddings and the LM head are typically frozen.
Exception: when you add new tokens, train them fully via
modules_to_save.
In PEFT,
target_modules="all-linear"selects these layers.
Q43.Why does LoRA drastically reduce optimiser memory compared to full fine-tuning?
Optimizer state scales with the number of trainable parameters. LoRA freezes the base model and trains only a tiny adapter, so Adam's per-parameter states and the fp32 master weights exist for perhaps 0.1–1% of the parameters instead of all of them.
Full fine-tuning cost (mixed-precision Adam): about 16 bytes per parameter:
fp16 weights: 2 bytes
fp16 gradients: 2 bytes
fp32 master weights: 4 bytes
Adam
mandvstates: 8 bytesFor a 7B model that is about 112 GB before activations.
LoRA cost:
Frozen weights need only storage: 2 bytes per parameter in bf16, or about 0.5 in 4-bit QLoRA.
There are no weight gradients and no optimizer states for the frozen weights.
Gradients and Adam states apply only to the adapter: tens of MB to a few GB.
What doesn't shrink:
Activations: backprop still flows through the frozen layers to reach earlier adapters.
Activation memory therefore remains, and gradient checkpointing is still useful.
Q44.What is the trade-off of increasing the rank r in LoRA?
Higher rank gives the update more capacity to express complex changes, at the cost of more trainable parameters and memory, larger adapters, and greater overfitting risk. Returns often diminish quickly because the needed update is usually low-rank.
Benefits of higher r:
More expressive
ΔW, closer to full fine-tuning.Helps tasks far from the pretraining distribution (new domain or language, heavy knowledge injection).
Costs of higher r:
Parameters grow linearly as
r·(d+k). This increases optimizer memory and adapter file size, though it is still small next to the base model.There is more risk of overfitting on small datasets.
With fixed α, the
α/rscale shrinks the update. Retune α, or use rsLoRA, which scales byα/√r.
Costs of low r:
It is cheap and acts as an implicit regulariser.
It may underfit complex or heavily shifted tasks.
Practical guidance:
Typical ranks are 8 to 64.
Covering more modules often helps more than raising r.
Sweep r against validation loss rather than assuming bigger is better.
Q45.Why does LoRA typically use a higher learning rate than full fine-tuning?
LoRA trains a small, zero-initialized low-rank update instead of the full weights, so each step moves the model's effective weights far less than a full fine-tuning step at the same learning rate. A higher LR compensates. Typical values are about 1e-4 to 2e-4 for LoRA versus 1e-5 to 2e-5 for full fine-tuning, and empirically the optimal LoRA LR is roughly 10x higher.
The update is a product that starts at zero:
ΔW = BAwithB = 0at init, so early updates are tiny and grow slowly. A small LR would keep the adapter near zero for a long time.The gradient reaching each factor is scaled by the other factor, which starts small. That shrinks the effective step on
W.
Scaling and rank interact with LR:
The update is multiplied by
alpha / r, and the effective step size depends on this scaling.With the common
alpha / rconvention, the optimal LR stays roughly constant across ranks.
Stability allows it:
The base weights are frozen and the update is confined to a low-rank subspace, so a large LR cannot wreck the pretrained representation the way it would in full fine-tuning.
Full fine-tuning uses a small LR because every weight moves, which risks catastrophic forgetting and divergence.
Caveat: too high still diverges, especially at large batch sizes or high
alpha, so sweep the LR rather than copying a full fine-tuning value.
Q46.How does prefix tuning differ from prompt tuning?
Prompt tuning learns soft embeddings only at the input layer. Prefix tuning learns trainable key/value vectors that are prepended inside every transformer layer's attention, so it steers each layer directly rather than relying on the input to propagate.
Prompt tuning (Lester et al., 2021):
Trains
n × d_modelparameters, concatenated to the token embeddings.Has the fewest parameters, but is weak on smaller models; it becomes competitive mainly at 10B+ scale.
Prefix tuning (Li & Liang, 2021):
For each layer, learns prefix
KandVtensors that every real token can attend to.Parameter count is about
n × layers × 2 × d_model.Often reparameterized through a small MLP during training for stability; afterwards, only the resulting prefixes are kept.
More expressive and works better on smaller models and generation tasks. P-tuning v2 is essentially the same deep-prompt idea.
Shared traits:
Both freeze the base model.
Both consume context/KV-cache positions at inference.
Both are generally outperformed by LoRA in practice.
Q47.Which parameters does BitFit fine-tune?
BitFit (Ben Zaken et al., 2021) trains only the bias terms of the network, plus the task-specific head. Every weight matrix stays frozen.
Which biases:
Attention projections (
query,key,value, and the output projection).Both FFN linear layers.
LayerNorm bias (beta) terms.
Scale:
About 0.08 to 0.1% of BERT's parameters, yet competitive with full fine-tuning on GLUE for small and medium data.
The paper found that just the query biases and the second FFN layer biases recover most of the gain.
Limitations:
Expressiveness is limited: it only shifts activations and cannot change how features are mixed.
Many modern LLMs (e.g. LLaMA) have no bias terms in their linear layers, so BitFit barely applies to them.
Q48.Why did LoRA largely supersede classic bottleneck adapter modules?
LoRA matches or beats adapter quality while adding zero inference latency. Its update is linear and runs in parallel with the frozen weight, so it can be merged into that weight. Bottleneck adapters, by contrast, insert extra sequential layers that run on every forward pass.
Classic adapters (Houlsby et al., 2019):
Structure: down-projection, then a nonlinearity, then an up-projection, plus a residual connection. They are inserted in series after the attention and/or FFN blocks.
The nonlinearity prevents folding them into existing weights, so they remain extra layers at inference.
The added depth is sequential and hard to parallelize. The LoRA paper measured noticeable latency increases at small batch sizes, which is exactly the online-serving regime.
LoRA (Hu et al., 2021):
Computes
h = Wx + (α/r)·BAx, a parallel, linear low-rank update.Merge with
W' = W + (α/r)·BA; the deployed model then has the original architecture and speed.Alternatively keep adapters unmerged and hot-swap many tasks on one base model (multi-LoRA serving).
Practical momentum:
No architecture surgery is needed; you just target existing
nn.Linearmodules.There is a single interpretable knob (rank
r).Strong ecosystem support (
peft, QLoRA, vLLM multi-adapter serving).
Q49.When should you choose continued pretraining instead of supervised instruction tuning?
Choose continued pretraining (CPT) when the model lacks knowledge (a new domain, language, or vocabulary) and you have lots of unlabeled text. Choose supervised instruction tuning (SFT) when the knowledge is already there and you need to change behavior (format, task following, tone). In practice they are often chained: CPT first, then SFT.
Signals that CPT is the right tool:
The base model has low exposure to the domain or language (legal, biomedical, internal codebase, a low-resource language), which shows up as high perplexity on domain text.
You have a large raw corpus (hundreds of millions to billions of tokens) but few labeled input/output pairs.
SFT alone yields fluent but shallow or hallucinated domain answers: SFT teaches the model how to answer, not new facts at scale.
Signals that SFT is enough:
The model already knows the material but doesn't follow your format, task, or style.
You have thousands of high-quality demonstrations rather than a huge corpus.
How they differ mechanically:
CPT uses next-token loss on every token of raw documents, with no prompt/response structure.
SFT uses prompt/response pairs and usually masks the loss to response tokens only.
Costs and risks of CPT:
It needs far more compute and data than SFT.
It carries higher forgetting risk, and CPT on an instruct model can erode its chat and alignment behavior. Mitigate with general-data replay, a lower LR, and SFT afterward.
If the knowledge changes often or must be cited, consider RAG instead of either approach.
Q50.What steps must you take when introducing new special tokens to an existing model's tokenizer during fine-tuning?
Adding special tokens means changing the tokenizer and the model together. Register the tokens, resize the embedding and output matrices, initialize the new rows sensibly, make sure those rows actually get trained, and ship the updated tokenizer and template alongside the weights.
Register the tokens as special:
Use
tokenizer.add_special_tokens()so they are never split and are matched atomically.Set roles where needed:
pad_token,eos_token, and chat delimiters.
Resize the model:
Call
model.resize_token_embeddings(len(tokenizer)). This grows both the input embeddings and thelm_head(or the tied weight).Optionally pass
pad_to_multiple_of(e.g. 64) for GPU efficiency.
Initialize the new rows:
Random init can produce huge logits and destabilize training.
Use the mean of the existing embeddings, or the mean of the subword embeddings of a related word.
Make the new rows trainable: With LoRA, the embeddings are frozen by default. Add
embed_tokensandlm_headtomodules_to_save, or the new tokens never learn a meaning.Update formatting and config:
Update the
chat_templateand the loss masking to use the new tokens.Update
pad_token_idandeos_token_idin the model and generation configs so generation stops correctly.
Verify and ship:
Tokenize a sample to confirm each new token maps to a single ID.
Save the tokenizer together with the model or adapter. A mismatched vocab size at load time will error or silently misbehave.
Q51.How does replay (data rehearsal) mitigate catastrophic forgetting?
Replay mixes examples from the original or general distribution into the fine-tuning data. Each update then has to keep the old loss low while it lowers the new one, which turns sequential training into something close to joint training.
Mechanism:
Without replay, gradients point only toward the new task and freely overwrite shared weights.
Old-task samples add gradient terms that penalize drift in the directions that matter for prior capabilities.
Sources of replay data:
A subset of pretraining-style text, used for continued pretraining.
General instruction and chat data, used for SFT.
Pseudo-rehearsal: when the original data is unavailable, generate it from the original model (self-distillation) and train on those outputs.
Practical knobs:
Mix ratio: often around 5 to 30% replay. More replay retains more but slows target learning.
Interleave replay throughout training rather than appending it at the end.
Pick diverse, high-quality replay that covers the capabilities you need to keep.
Limitations:
It adds compute.
It only protects what the replay set covers.
It requires access to suitable data, which may be blocked by licensing or privacy.
Q52.Why does parameter-efficient fine-tuning like LoRA reduce catastrophic forgetting compared to full fine-tuning?
LoRA freezes the pretrained weights and learns only a small low-rank update ΔW = BA. This sharply limits how far, and in how many directions, the model can move from its original solution, so less prior knowledge gets overwritten.
Frozen base weights: The original parameters are untouched. Every change lives in the adapter, which can be scaled down or removed to recover the base model exactly.
Low-rank constraint:
The update can only span
rdirections per matrix, while full fine-tuning updates are much higher rank.With far fewer degrees of freedom, the model can't drift arbitrarily. This acts as an implicit regularizer.
Empirical evidence: Biderman et al., 2024, "LoRA Learns Less and Forgets Less": LoRA underperforms full FT on hard new domains such as code and math CPT, but better preserves source-domain performance.
Caveats:
It reduces forgetting but does not eliminate it. A high rank, a high LR, many epochs, or including
embed_tokensandlm_headall increase drift.The same constraint limits plasticity, so LoRA may underfit when large knowledge injection is needed.
Q53.What is the stability-plasticity dilemma in the context of fine-tuning?
The stability-plasticity dilemma is the trade-off between keeping what a model already knows (stability) and learning new tasks or data (plasticity). Settings that make the model adapt faster also make it forget more, and the reverse is also true.
Too much plasticity:
High LR, many epochs, full fine-tuning, and narrow data all push toward this end.
Result: strong target metrics but catastrophic forgetting of general and safety behavior.
Too much stability:
Tiny LR, very low LoRA rank, heavy regularization, and few steps all push toward this end.
Result: general ability is preserved but the model underfits the new task.
Knobs that move you along the trade-off:
Learning rate, epochs, and warmup.
Number of trainable parameters: LoRA rank and which layers are trained.
Replay ratio.
Regularization toward the base model: EWC, L2-SP, or a KL penalty to a reference model.
In practice: Evaluate both axes on every run (target metrics plus a general and safety suite) and pick the point on the trade-off curve that fits the product's needs.
Q54.What is the difference between multi-task fine-tuning and sequential fine-tuning across multiple domains?
Multi-task fine-tuning trains on a mixture of all domains at once, optimizing a joint objective. Sequential fine-tuning trains on domain A, then B, then C. Joint training balances the domains against each other, while sequential training lets later domains overwrite earlier ones.
Multi-task (joint) fine-tuning:
Every batch draws from several domains, so gradients trade off all tasks together. This gives minimal forgetting and allows positive transfer.
It requires all the data up front and careful mixing ratios, using temperature or proportional sampling so large domains don't dominate.
Risk: negative transfer or task interference between conflicting domains or formats.
Sequential fine-tuning:
Natural when data arrives over time or a pipeline is staged, for example CPT then SFT then preference tuning.
Main risk: catastrophic forgetting of earlier domains. The order of training also affects the final result.
Needs mitigations such as replay of earlier domains, regularization toward previous weights, or lower LRs at later stages.
Alternatives:
Train a separate LoRA adapter per domain and route or swap between them at inference.
Merge independently fine-tuned models (task arithmetic, TIES).
Rule of thumb:
If all the data is available and you want one model, prefer multi-task.
If you must go sequential, add replay.
Q55.What is the function of the temperature parameter in the distillation loss?
Temperature T softens both teacher and student softmax distributions (softmax(z/T)) so the student learns from the relative probabilities of non-top tokens/classes, which carry the teacher's "dark knowledge" that a near-one-hot distribution would hide.
Why softening helps:
At T=1 a confident teacher puts ~0.99 on one class; the rest are tiny and contribute almost no gradient.
Higher T flattens the distribution, amplifying similarity structure (e.g. "cat" is closer to "dog" than to "car").
Choosing T:
T > 1 (commonly 2 to 5) for classification; LLM distillation often uses T near 1 since vocab distributions are already rich.
Too high: distributions approach uniform and the signal vanishes. Too low: equivalent to hard-label training.
The T² factor: Soft-target gradients scale as 1/T², so the KD loss is multiplied by T² to keep its magnitude comparable to the hard-label loss when T changes.
Same T is applied to teacher and student during training; inference uses T=1.
Q56.What is the difference between logit-level distillation and sequence-level distillation?
Logit-level distillation matches the teacher's full probability distribution at every token position; sequence-level distillation has the teacher generate complete outputs and trains the student on them with ordinary cross-entropy, i.e. matching the teacher's mode rather than its distribution.
Logit-level (word/token-level):
Loss: per-token KL between teacher and student distributions, usually on a fixed dataset (teacher-forced).
Richest signal per token (dark knowledge across the vocabulary).
Requires white-box teacher access (logits), a shared tokenizer/vocabulary, and costly logit storage or an online teacher (often top-k logits are kept).
Sequence-level (Kim & Rush, 2016):
Teacher decodes outputs (beam search or sampling); student does SFT on those sequences.
Works with black-box APIs and different tokenizers; simple and cheap to store.
Approximates the teacher's sequence distribution by its high-probability outputs, which are easier for a small student to fit; loses per-token uncertainty.
Shared weakness and fix: Both train on sequences the student didn't produce (exposure bias). On-policy distillation (e.g. GKD) has the student generate and the teacher score those tokens.
In practice, combine: generate teacher data, then also add a logit loss if logits are available.
Q57.What are the trade-offs between distilling a large LLM into a smaller model versus fine-tuning the small model directly?
Distillation gives the small model a stronger, cheaper-to-scale training signal (the teacher's knowledge and generated data) at the cost of teacher compute, access constraints, and inherited teacher errors; direct fine-tuning is simpler and bounded by your labeled data and the small model's own capacity.
Advantages of distillation:
Soft targets carry more information per example, so the student often beats the same model fine-tuned on hard labels alone.
Teacher can label unlimited unlabeled prompts: solves data scarcity, and can transfer reasoning traces or style.
Costs and risks of distillation:
Teacher inference (and logit storage) is expensive; a large model must be served during data generation or training.
Student inherits teacher hallucinations and biases; ceiling is the teacher.
Capacity gap: if teacher is far larger, the student can't fit its distribution; an intermediate teacher or sequence-level KD can help.
Logit KD needs white-box access and a shared tokenizer; API-based distillation may violate provider terms of service.
When direct fine-tuning wins:
You have plenty of high-quality labeled data, a narrow task, or ground truth the teacher can't match (proprietary domain knowledge).
Lower pipeline complexity and no dependency on a teacher.
Common practice: combine them: generate/filter teacher data, mix with real labels, and verify outputs (e.g. with tests or a judge) before training.
Q58.How can multiple LoRA adapters be combined to give one model several skills?
Each LoRA adapter is a low-rank weight delta ΔW = BA on a shared base. There are three main ways to use several of them:
Static merge into one adapter or into the base:
Compute a weighted sum of the deltas:
W = W0 + Σ wᵢ·BᵢAᵢ.Averaging the
AandBmatrices separately is not equal to summing the products. Concatenating along the rank dimension (cat) reproduces the sum exactly.TIES or DARE variants (
ties,dare_ties) reduce interference when the adapters conflict.
Dynamic switching per request:
Keep the adapters separate and load the right one for each request.
Multi-LoRA serving (S-LoRA, vLLM, LoRAX) batches requests that use different adapters over one base model.
This approach has no interference, but each request gets only one skill.
Learned routing or composition:
Mixture-of-LoRA-experts uses a gate that weights adapters per token or per input.
LoraHub learns composition weights from a few examples.
Alternative: train a single adapter on the mixed data.: This is often the strongest option when the training data is available.
Q59.How do you debug a fine-tuned model that generates repetitive text or never emits an end-of-sequence token?
Endless generation is almost always a data or template bug: the model never learned to predict EOS. Repetition usually comes from that same bug, or from decoding settings and overfitting. Debug by inspecting the exact tokenized training examples and the inference configuration.
Was EOS actually trained?:
Decode a few tokenized training samples and confirm each target ends with EOS or the end-of-turn token.
Watch for the classic bug of
pad_token = eos_tokencombined with masking pad labels to-100. This also masks the real EOS, so it never contributes to the loss.Check that truncation (
max_seq_lengthtoo small) isn't cutting off the ending, EOS included.With packing, make sure EOS separators sit between the concatenated examples.
Template and stop-token mismatch:
Inference must use the same chat template as training (use
apply_chat_templateconsistently).The
generation_config.eos_token_idmust include the token the model learned to stop on, such as<|eot_id|>or<|im_end|>.
Decoding settings: Greedy decoding loops easily. Try modest sampling,
repetition_penaltyorno_repeat_ngram_sizeas a diagnostic, not as the fix.Training dynamics and data:
An overly high learning rate or too many epochs can collapse the output distribution into loops.
Look for repetitive or templated targets, or very long targets, that teach the model to ramble.
Q60.What makes a representative evaluation set for a fine-tuned classification or extraction task?
A representative eval set mirrors the production input distribution, is strictly held out from training, and carries trustworthy labels. It also needs enough coverage of rare classes, edge cases and slices to give statistically meaningful per-category results.
Distribution match:
Sample from real or production-like inputs, not cleaned synthetic data. Match the length, formatting noise, language and source mix.
Refresh it periodically to track drift, and version it so results stay comparable over time.
No leakage:
Deduplicate exact and near-duplicate examples against training data.
Split by document, customer or time, so related examples don't land on both sides.
Coverage:
Stratify by class. Oversample rare classes so each has enough examples for a stable estimate, then report per-class results.
Include hard negatives, ambiguous cases and adversarial inputs.
For extraction, include missing or null fields, multiple values and unusual formats.
Label quality:
Write clear annotation guidelines and use multiple annotators on a subset. Measure agreement (Cohen's kappa) and adjudicate disagreements.
Treat the eval set as gold: it should be cleaner than the training data.
Appropriate metrics and size:
For classification, use macro-F1 and a confusion matrix rather than accuracy alone on imbalanced data.
For extraction, use field-level precision and recall plus exact-match, with normalization rules.
Size the set so confidence intervals are narrower than the differences you care about.
Q61.What causes negative transfer during fine-tuning?
Negative transfer happens when starting from (or jointly training on) source knowledge makes target performance worse than a better baseline. The usual root cause is that the source features or gradients conflict with what the target task needs, and the fine-tuning setup can't overcome or isolate that conflict.
Source-target dissimilarity:
Pretrained features encode the wrong invariances. For example, color invariance hurts a task where color matters.
Strong priors from the source bias the model toward wrong solutions.
Conflicting objectives in multi-task or sequential tuning:
Gradients from different tasks point in opposing directions (task interference).
One task degrades another.
Destructive optimization: A too-high LR, a random head without warmup, or too many epochs distort good features (catastrophic forgetting).
Data problems:
Small or noisy target data lets the model overfit spurious patterns.
Format and template mismatches (prompt style, label schema) teach the wrong mapping.
Capacity or architecture mismatch: Examples include a different input resolution, modality, or tokenizer coverage.
Diagnosis and fixes:
Compare against a from-scratch or other-checkpoint baseline.
Choose a closer source model.
Lower LRs, add layer freezing, or use PEFT.
Reweight or filter source tasks, or use gradient-conflict methods (e.g., PCGrad) in multi-task setups.
Q62.Under what conditions does linear probing outperform full fine-tuning on out-of-distribution data?
Linear probing tends to beat full fine-tuning out of distribution when pretrained features are already high quality and the OOD shift is substantial. Full fine-tuning with a randomly initialized head distorts those features: it adapts them only along directions seen in the in-distribution data. Kumar et al. (2022) found FT averaged about 2% better in-distribution but about 7% worse OOD than LP.
The mechanism: feature distortion:
Early in FT, the random head sends large gradients into the backbone.
Features change in the subspace spanned by the ID training data, while OOD directions barely move.
The co-adapted head and features then mismatch on OOD inputs.
LP never touches the features, so their pretrained robustness is preserved.
Conditions favoring LP on OOD:
Strong, broad pretrained features (e.g., CLIP, large self-supervised models) that already encode the OOD domains.
A large shift between the ID training set and the OOD test set (e.g., ImageNet to sketches or renditions).
Limited or narrow ID training data, which amplifies distortion.
Aggressive FT (random head, high LR), which makes distortion worse.
When FT still wins: When pretrained features are poor for the target, the features must change, and FT wins both ID and OOD.
Getting both:
LP-FT: probe first, then fine-tune from the good head with a small LR, so features barely distort.
Weight interpolation (WiSE-FT) and PEFT also preserve OOD robustness.
Q63.Why is fine-tuning generally ineffective for teaching a model new factual knowledge?
Fine-tuning is good at shaping how a model uses what it already knows (format, style, behavior) but poor at reliably injecting new facts: a few gradient steps on small data rarely store retrievable knowledge, and pushing them can increase hallucination and damage existing knowledge.
Knowledge is learned mainly in pretraining:
Facts become robustly stored after being seen many times in varied phrasings across huge corpora. SFT data is small and each fact appears once or a few times in one phrasing.
The model tends to memorize the surface form, so it can recite the training sentence but fails on paraphrased questions or reasoning that uses the fact.
Learning unknown facts teaches hallucination: Research (e.g. Gekhman et al., 2024) found new-knowledge examples are learned slower than known ones, and once fit, they increase the model's tendency to hallucinate: it learns to answer confidently beyond what it actually knows.
Side effects:
Aggressive training to force facts in causes catastrophic forgetting of other capabilities.
Baked-in facts go stale, cannot be cited, and require retraining to update or delete.
What to do instead:
Use RAG for knowledge (updatable, attributable); use fine-tuning for behavior.
If knowledge must live in weights, use continued pretraining on a large domain corpus with heavy paraphrase/augmentation, mixed with general data.
Q64.How do you decide whether a production problem requires RAG, fine-tuning, or both?
Diagnose what is actually failing: if the model lacks or misstates information, use RAG; if it has the knowledge but behaves wrong (format, tone, task skill, latency/cost), fine-tune; if you need both fresh knowledge and specialized behavior, combine them.
Choose RAG when:
Knowledge is private, large, or changes frequently (docs, tickets, catalogs).
You need citations, access control per user, or easy deletion of data.
Errors are hallucinations or outdated answers.
Choose fine-tuning when:
Failures are behavioral: inconsistent structured output, wrong domain style, poor tool-calling, weak performance on a narrow task.
You need a smaller, cheaper, faster model or shorter prompts at high volume.
You have good labelled examples and stable requirements.
Use both when: Retrieval provides facts while a fine-tuned model is better at using context: grounding on retrieved passages, ignoring irrelevant chunks, domain jargon, output format (e.g. RAFT-style training).
Process:
Start with prompting plus an eval set; do error analysis on failures.
Bucket errors: retrieval misses vs. knowledge gaps vs. behavior/format errors.
Fix the dominant bucket with the matching tool; re-evaluate.
Q65.When does fine-tuning a smaller model become economically preferable to prompting a frontier model?
It becomes preferable when request volume is high and the task is narrow and stable enough that a small fine-tuned model matches frontier quality: then lower per-token cost and latency outweigh the fixed costs of data, training, hosting, and maintenance.
Do a break-even calculation:
Frontier cost: volume × (prompt + output tokens) × API price; long few-shot prompts inflate this.
Small-model cost: one-off data labelling and training, plus serving (GPU hours or hosted per-token price), plus ongoing eval, retraining, and engineering time.
Break-even volume = fixed costs / per-request savings. Above it, the small model wins.
Conditions that favor the small model:
High, steady traffic (millions of calls) that keeps self-hosted GPUs well utilized.
Narrow, well-defined task (classification, extraction, routing, fixed-format generation) where quality is measurable.
Tight latency SLAs, on-device/edge, or data-residency constraints.
You can distill: use the frontier model to label training data for the small one.
Conditions that favor staying on the frontier model:
Low or bursty volume, open-ended tasks needing broad reasoning, fast-changing requirements, or no team to run ML ops.
API prices fall quickly, so savings must hold up over the model's lifetime.
Always gate the decision on evals: savings only count if the small model meets the quality bar.
Q66.When fine-tuning for a downstream task, how do you decide whether to start from a base checkpoint or an instruction-tuned checkpoint?
Start from the instruction-tuned checkpoint when your task resembles chat or instruction following and your data is limited; start from the base checkpoint when you are training a very different behavior or format, have plenty of data, or want full control over the model's alignment and style.
Instruction-tuned checkpoint:
Already follows instructions, uses a chat template, and has safety behaviors, so small datasets go further.
Good for assistants, tool use, or tasks phrased as instructions.
Caveats: you must use its exact chat template; its priors (verbosity, refusals, style) can fight your target behavior; fine-tuning may erode its alignment.
Base checkpoint:
A clean slate with no chat formatting or assistant persona; better for continuation tasks, custom formats, classification heads, or domain continued pretraining.
Preferred when you will run your own full SFT plus preference tuning pipeline.
Needs more data to learn instruction following from scratch.
Decide empirically: With a small budget, fine-tune both (e.g. LoRA) on the same data and compare on held-out evals, including regressions on general capability.
Q67.When would you use a hosted fine-tuning service instead of fine-tuning an open-weight model on your own infrastructure?
Use a hosted service (e.g. OpenAI, Vertex AI, Bedrock fine-tuning) when you want speed and low operational burden and the provider's models and data terms are acceptable; self-host open weights when you need control over data, model internals, cost at scale, or deployment location.
Hosted service fits when:
The team lacks GPU or ML-infra expertise and needs results quickly.
You need a proprietary model's base quality that no open model matches.
Volume is modest, so pay-per-token beats running GPUs; scaling and serving are handled for you.
Sending training data to the vendor is allowed by compliance.
Self-hosted open weights fit when:
Data must stay in your environment (regulated data, air-gapped, on-prem, edge).
You need control the API won't give: custom losses, RLHF/DPO variants, hyperparameters, adapters, quantization, merging.
High steady volume makes owned serving cheaper; you want to avoid vendor lock-in or model deprecation.
You need full weights for reproducibility or auditing.
Trade-off summary: hosted buys simplicity at the cost of control and portability; self-hosted buys control at the cost of infra and expertise.
Q68.Why does sequence packing require modifying the causal attention mask?
A standard causal mask lets every token attend to all earlier tokens in the sequence. After packing, tokens of example B could therefore attend to unrelated example A, contaminating its context. The mask must become block-diagonal so each example only attends within itself.
What goes wrong without it:
Cross-contamination: the model conditions on irrelevant prior conversations, which leaks information and adds noise.
Train/inference mismatch: at inference, a prompt never has unrelated text before it.
Later examples get a different (longer, noisier) context than earlier ones in the pack.
The fix: block-diagonal causal mask:
The mask stays causal within each example, with zero attention across example boundaries.
Efficient implementations avoid materialising the full mask by using FlashAttention varlen kernels with
cu_seqlens, or HF'sDataCollatorWithFlattening.
Reset positions too:
position_idsshould restart at 0 for each example, so RoPE/positional encodings match unpacked inference.Note: some pretraining pipelines skip this and rely only on EOS separators, accepting the contamination. For SFT, where each example is a self-contained prompt/response, proper masking is preferred.
Q69.What are the risks of fine-tuning a model exclusively on synthetic outputs from a larger teacher model?
Training only on teacher outputs caps the student at an imitation of the teacher: it inherits the teacher's errors and biases, often copies its style without its underlying capability, and loses diversity, with additional legal and evaluation risks.
Imitation without capability:
"The False Promise of Imitating Proprietary LLMs" showed students match the teacher's confident tone but not its factuality or reasoning, fooling human raters.
Teaching facts the student's base doesn't know encourages hallucination.
Error and bias inheritance:
Teacher hallucinations, refusals, safety quirks, and biases are learned as ground truth.
Student performance is effectively upper-bounded by the teacher on that distribution.
Diversity collapse:
Teacher outputs are lower-entropy and stylistically homogeneous (verbosity, stock phrases).
Repeated rounds of training on model outputs can lead to model collapse, losing the tails of the distribution.
Evaluation and practical risks:
Teacher may reproduce benchmark items, causing contamination.
LLM-as-judge from the same family favors the student's style, inflating evals.
Provider terms of service may prohibit training competing models.
Mitigations: verify outputs (tests, answer checks), mix in human and real-user data, use multiple teachers, filter with judges, and evaluate on held-out human-graded tasks.
Q70.What causes loss spikes during fine-tuning of large models?
A loss spike happens when one update is far too large for the local curvature: the model is pushed into a worse region and the loss jumps. The usual triggers are an aggressive learning rate, pathological batches, numerical overflow, and optimizer-state mismatches.
Optimization settings:
Learning rate too high, or no or too-short warmup.
No gradient clipping, so a single huge gradient goes straight into the weights.
Bad or unusual data:
Corrupted, duplicated, or mislabeled examples.
Extremely long sequences, or batches with almost no unmasked tokens (tiny denominators in the loss).
Abrupt domain shifts caused by unshuffled data ordering.
Adam dynamics:
Parameters that rarely receive gradient (e.g. rare-token embeddings) end up with a tiny second moment
v.When a large gradient finally arrives,
lr / sqrt(v)produces an outsized step.A lower
beta2(e.g. 0.95) makesvadapt faster.
Numerical precision:
fp16 overflow or underflow, and loss-scaler issues, produce inf or NaN values or spikes.
bf16 has a larger exponent range and is far more robust.
Architectural instability at scale:
Attention logits grow without bound, which saturates the softmax.
Output logits drift.
Mitigations: QK-norm and z-loss.
How to respond:
Log the per-batch gradient norm and inspect the offending batch.
Add clipping and lower the learning rate, or extend warmup.
For big runs: rewind to a checkpoint before the spike and skip the bad data.