Skip to content
Tech Interview Prep
Technical interview guide

Fine-Tuning & Adaptation

Adapting a pretrained LLM's behavior via further training, and how that differs from prompting or RAG.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Transformer, InstructGPT, LoRA, QLoRA, DPO, LIMA, Model Cards, Datasheets, Hugging Face PEFT/Transformers/TRL, NIST AI RMF, and OWASP supply-chain references reviewed 2026-09-06.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Choose fine-tuning versus prompt, RAG, tools, or code.

Answer

Start with the simplest thing that could work. For most production LLM features, that's prompt engineering. If the model lacks private or current knowledge, add retrieval-augmented generation (RAG). If the task requires live computation or side effects, use tools (function calling). If the requirement is exact, auditable rules or authorization, put it in code. Fine-tuning is the last resort: it's for stable behavior, style, or output format that prompting can't reliably achieve, and only when you have enough high-quality examples to justify the training and lifecycle cost.

Assumptions: you have a working LLM application, a baseline prompt, and a way to evaluate outputs. You're choosing one or a combination.

Why retrieval beats tuning for freshness: fine-tuning updates model weights via gradient descent on your examples. That bakes facts into parameters, which become stale as soon as the world changes. RAG fetches documents at inference time, so freshness is bounded by your index update latency, not retraining. Tuning also can't reliably add new facts: it shifts the distribution of outputs, which may cause hallucination if you try to teach facts.

Why tools for live computation: a tool call is a structured request to an external function. The model doesn't compute; it emits a JSON payload. That gives you deterministic results, auditability, and access to real-time data. Code is for rules that must never be violated, like "only refund if amount < $100 and user is admin."

Trade-offs table (hypothetical figures, labeled):

ApproachLatency addedCost per 1k queriesFreshnessControl
Prompt0 ms$0.50staticlow
RAG+50-200 ms$1.20minutesmedium
Tools+100-500 ms$2.00real-timehigh
Fine-tune0 ms (inference)$0.30 + $100 trainingfrozenmedium
Code<1 msnegligiblereal-timeexact

Failure modes: Fine-tuning overfits to your examples; detection: eval score drops on held-out set, or format violations increase. Catastrophic forgetting: model loses general ability; detection: regression on unrelated tasks. RAG retrieval misses: detection: low recall on golden set, or answers cite wrong doc. Tools: API timeouts; detection: p99 latency spike, error rate. Code: brittle rules; detection: false rejections in logs.

Worked example: customer support bot. User: "What's my balance?" → tool call to get_balance(user_id). User: "How do I reset password?" → RAG over help center. User: "Write a friendly apology" → fine-tune on 500 examples of brand voice. User: "Refund if order < $50" → code rule. Trace: if you tried to fine-tune the balance question, the model would hallucinate a number. If you used RAG for balance, it would fetch stale docs. So the decision is driven by the nature of the gap.

Code snippet (tool definition):

JSON
{
  "name": "get_balance",
  "description": "Get current account balance",
  "parameters": {
    "type": "object",
    "properties": {
      "user_id": {"type": "string"}
    },
    "required": ["user_id"]
  }
}

What would change the decision: if fine-tuning became cheap enough to retrain daily, or if you had a small model and needed to reduce prompt length for latency, fine-tuning might win for style. If your knowledge base updates every second, RAG index latency matters. If tools are unavailable, you might simulate with code.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do Full Fine-Tuning and Parameter-Efficient Fine-Tuning differ across memory footprint, catastrophic forgetting, and multi-task serving?

Answer

Full Fine-Tuning (FFT) updates all model parameters ($W \leftarrow W + \Delta W$), requiring optimizer states, gradients, and activation memory for every weight. Parameter-Efficient Fine-Tuning (PEFT, exemplified by LoRA) freezes the base parameters $W_0 \in \mathbb{R}^{d \times k}$ and injects low-rank trainable decomposition matrices $\Delta W = B \cdot A$ where $B \in \mathbb{R}^{d \times r}, A \in \mathbb{R}^{r \times k}$ with rank $r \ll \min(d, k)$.

1. Compute and Memory Arithmetic

For a 7B parameter model in 16-bit mixed precision (bfloat16):

  • Base weights: $7 \times 10^9 \times 2\text{ bytes} = 14\text{ GB}$.
  • FFT memory profile (AdamW):
    • Model weights: 14 GB
    • Gradients: 14 GB (bfloat16)
    • AdamW states (fp32 first/second moments): $7 \times 10^9 \times 8\text{ bytes} = 56\text{ GB}$
    • Static training footprint: $\approx 84\text{ GB}$ (excluding activations and KV cache), requiring at least 2x80GB A100/H100 GPUs using FSDP/DeepSpeed ZeRO-3.
  • LoRA/PEFT memory profile ($r=16$, all linear layers $\approx 0.2%$ trainable parameters $\approx 14\text{M}$ params):
    • Frozen base weights: 14 GB (or 3.5 GB if 4-bit QLoRA using NF4)
    • Trainable adapter weights + gradients: $\approx 56\text{ MB}$
    • AdamW optimizer states for adapter: $14 \times 10^6 \times 8\text{ bytes} \approx 112\text{ MB}$
    • Static training footprint: $\approx 14.2\text{ GB}$ (or $\approx 3.7\text{ GB}$ in QLoRA), easily fitting onto a single 24GB consumer/datacenter GPU (e.g., RTX 4090 or A10G).

2. Catastrophic Forgetting and Regularization

MechanismFull Fine-Tuning (FFT)LoRA / PEFT
Weight Space DriftUnbounded $\Delta W$. Overparameterized updates shift general representation manifolds, degrading out-of-distribution reasoning and general benchmarks (e.g., MMLU).Constrained to low-rank subspace $\text{rank}(\Delta W) \le r$. Base model features remain locked in $W_0$.
Forgetting RiskHigh without explicit replay data, KL-divergence penalties, or weight decay regularization.Low. Base model capabilities are preserved because $W_0$ is mathematically frozen.
Capacity CapHigh: can learn novel tokens, vocabularies, and structural shifts.Moderate: excels at style, task alignment, and domain formatting; struggles if the target domain requires memorizing substantial new relational knowledge.

3. Multi-Task and Multi-Tenant Serving

  • FFT: Serving $N$ distinct fine-tuned tasks requires hosting $N$ distinct 14 GB base checkpoints in VRAM or spinning up independent GPU worker pools. Routing requests dynamically between tasks incurs massive cold-start latencies (10–30s to swap 14 GB from host memory).
  • PEFT / Multi-LoRA: A single shared base model $W_0$ is held in memory. Distinct task adapters ($A_i, B_i$, size 10–50 MB) are loaded into host RAM or pinned VRAM. For a mixed batch, execution can dynamically apply adapter matrices using segmented gathered matrix multiplies (e.g., S-LoRA/Punica) or per-request weight patching: $y = x W_0 + \frac{\alpha}{r} x A_i B_i$. Multi-task operational cost drops from $O(N \times \text{Base})$ VRAM to $O(\text{Base} + N \times \text{Adapter})$.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Define a fine-tuning evaluation scorecard.

Answer

The 90-second version. A fine-tuning scorecard is a frozen set of measurements with pre-registered gates, run on a held-out set the model never trained on, decided before you look at any result. It has three layers: capability, policy, and cost. Capability and cost feed a weighted composite you use to rank candidate checkpoints; policy and privacy are hard gates that no composite can outvote. Assumptions I'd state out loud: a 7B instruction-tuned model, LoRA or full SFT on ~50k domain examples, evaluated on 2,000 held-out tickets, plus fixed red-team and canary sets. If the interviewer wants a different base or task, the gates move but the structure doesn't.

The scorecard itself.

LayerMetricInstrumentGate
CapabilityExact-match on tool name + argument JSON2,000 held-out tickets≥ baseline + 2 pp
CapabilityPerplexity on held-out tokenssame setreport only, no gate
CalibrationECE over 10 bins500 items with a confidence token≤ 0.06
PolicyHarmful-compliance rate300-prompt red set≤ 2%
PolicyOver-refusal on benign prompts300 benign prompts≤ 5%
PrivacyCanary exact-match extraction200 canaries injected into training data≤ 1%
RetentionGeneral-set accuracy1,000 items held out from pretraining-era evals≥ baseline − 1 pp
Costp99 time-to-first-token; $ per 1,000 callsload test at batch 8p99 ≤ 700 ms; ≤ $1.00

Why each layer earns its slot. Loss and perplexity are cheap and catch training bugs, but token likelihood can improve while product behavior gets worse: the model learns the domain's phrasing without learning to emit valid argument JSON. So exact-match on the structured output is the capability gate, and perplexity is reported, not gated. Calibration is separate because an SFT run that overfits the training distribution typically gets more confident, not more accurate: I've seen accuracy rise 3 pp while ECE went 0.04 → 0.11, which means the model's own confidence stops being usable for routing or abstention. Safety and over-refusal are two gates, not one, because refusal is a dial: pushing harmful-compliance to 0% usually drags benign refusal up, and the scorecard has to show both sides of that trade.

The arithmetic that decides slice policy. At n = 2,000 and p = 0.8, the 95% Wilson interval is ±1.8 pp. At n = 150, a typical language or risk slice, it's ±6.4 pp. So a slice needs roughly 400 examples before a 3 pp move is distinguishable from noise, and I'd set the minimum slice size at 400 and report the interval next to every slice number. Aggregate-only reporting is how a −9 pp Spanish regression hides behind a +3 pp overall gain.

Failure modes and how I'd catch them. Loss down, task accuracy flat: track both curves per epoch, stop on the task metric. Judge drift: if an LLM judge scores the win/loss column, audit it against 100 human-labeled pairs and gate on Cohen's kappa ≥ 0.6; below that the judge column is noise. Contamination: hash the eval set and run 13-gram overlap against training data before trusting any number. Silent truncation: log the fraction of outputs hitting max tokens, because a truncated tool call scores as a wrong answer and looks like a capability regression.

Trade-offs and what changes the decision. Human pairwise judging costs roughly $8–15 per comparison; an LLM judge costs about a cent. I'd use the judge for the full sweep and humans for the 100-item audit, and only escalate to full human eval if the judge's kappa drops or the composite is within 1 pp of the gate. If the fine-tune is style-only (tone, formatting, no new tools) I'd drop the retention and calibration gates and keep safety, privacy, and cost, because there's no capability claim to defend. The decision the scorecard drives is binary: ship the checkpoint, or don't. A weighted composite that can average away a safety regression is the one design I'd refuse.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Prepare instruction data for supervised fine-tuning.

Answer

The short answer: make the training sequence byte-identical to what serving produces, and put loss only on tokens the model must generate. Everything else (packing, truncation, masking) is a trade-off you validate against that invariant.

Assume you're fine-tuning an instruct model (Llama 3 8B, Mistral 7B) with HuggingFace transformers and trl's SFTTrainer, and serving with vLLM or TGI. Pin the tokenizer revision and chat template. The template lives in tokenizer_config.json under chat_template; serving must load the same revision. If training uses meta-llama/Meta-Llama-3-8B-Instruct at commit a1b2c3 and serving uses main, a template change silently shifts every token ID.

Render each conversation with apply_chat_template(..., tokenize=True, return_assistant_tokens_mask=True). That gives input_ids and assistant_masks. Labels are input_ids where the mask is 1, and -100 elsewhere. -100 is the PyTorch cross-entropy ignore index, so user and system tokens contribute no gradient.

Python
# transformers >= 4.40
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", revision="main")
msgs = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is 2+2?"},
    {"role": "assistant", "content": "4"},
]
enc = tok.apply_chat_template(msgs, tokenize=True, return_assistant_tokens_mask=True, add_generation_prompt=False)
input_ids = enc["input_ids"]
assistant_mask = enc["assistant_masks"]
labels = [tid if m else -100 for tid, m in zip(input_ids, assistant_mask)]

Set max_seq_length. Llama 3 8B has an 8192-token context; SFT commonly uses 2048 or 4096. Truncate from the left for chat so the latest assistant turn survives, but never truncate the assistant response itself. If you truncate from the right, you can cut the answer and leave zero supervised tokens.

Packing is the biggest throughput lever. Take 10k examples, mean 350 tokens, max_seq_length=2048. Without packing, each example is padded to 2048: 10k × 2048 = 20.48M tokens processed, but only 3.5M are real. 17% utilization. With packing, the 3.5M real tokens are chunked into 2048-token blocks: about 1709 blocks, near 100% utilization. The cost: TRL's ConstantLengthDataset concatenates examples; unless your trainer resets attention or position IDs at boundaries, token i can attend to a different conversation. Check the version and inspect a packed batch.

ChoiceWhat it doesCostWhen to use
No packingPads each example to max_seq_lengthWastes compute on pad tokensSmall data, debugging, examples near max length
PackingConcatenates examples into fixed blocksRaises utilization; can leak attention across examplesLarge data, short examples, after verifying boundaries
Right truncationKeeps system + early turns, cuts latest assistantCan leave zero supervised tokensRarely for chat
Left truncationKeeps latest turns, cuts system/early historyLoses context; can cut system policyChat with long histories, after ensuring assistant turn survives
Mask all tokensLoss on user + assistantModel learns to generate user turnsNever for SFT
Mask assistant onlyLoss on assistant tokensCorrect objectiveStandard SFT

Failure modes to test. Double BOS: if the template adds BOS and you also pass add_special_tokens=True, you get two BOS. Check input_ids[:5]. Template drift: training uses add_generation_prompt=False; serving uses add_generation_prompt=True. The assistant header is present in training because the assistant message includes it, but if you manually format, you can omit it. Golden-test token IDs against the exact serving formatter, vLLM's tokenizer.apply_chat_template, on empty, long, Unicode, and tool conversations. Tool calls: if training encodes tool calls with a different JSON schema than serving, the model learns the wrong format. Unicode: check tok.decode(tok.encode("👋")) == "👋" and that labels align. Empty assistant: mask may be all zeros; drop or handle.

The invariant is simple: same tokenizer revision, same template, same special tokens, loss only on assistant tokens. Everything else is a measured trade-off.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

How do you curate, filter, and deduplicate synthetic instruction-tuning datasets generated via methods like Self-Instruct or Evol-Instruct?

Answer

Before I describe the pipeline, three things decide it: how much human-written data I already have, whether the constraints in the synthetic prompts are programmatically checkable, and whether I have GPU budget for a judge model. Those change the design more than the choice of dedup algorithm does.

My default is four passes in this order: generation hygiene, cheap rule filters, deduplication, then model-based scoring. Order matters because cost per example spans roughly four orders of magnitude: a regex pass over 100k pairs is seconds on CPU, embedding dedup is minutes, and judge-LLM scoring at 1–2 s/pair on one GPU is 30–60 hours. You only pay the expensive pass on what survives the cheap ones.

Generation hygiene. Enforce stop sequences so the generator doesn't start drafting the next instruction, and reject self-identification and refusal boilerplate ("As an AI model…"), unclosed code fences, unbalanced JSON, and degenerate repetition: I use a 4-gram repetition ratio above 0.20 as the cut. Length bounds: instructions under 10 or over 512 tokens, responses under 20. Language ID with fastText at >0.85 confidence if the corpus is meant to be monolingual.

Deduplication, and where it bites. Exact hashing first, then MinHash+LSH (128 permutations over character 5-grams, Jaccard ≥0.70), then dense-embedding cosine at ≥0.88 against accepted exemplars. The trap here is that Evol-Instruct deliberately produces variants of the same seed: that's the method working. Dedup at 0.70 Jaccard on the instruction alone will delete the evolved variants you paid to generate. So I dedup on instruction plus response, and within a cluster I keep the hardest variant, not the longest. MinHash is lexical and misses paraphrase; embeddings catch paraphrase but are threshold-sensitive, and dropping the threshold to 0.80 starts removing legitimate diversity. If I can only afford one, I take MinHash: it's deterministic and cheap to re-tune.

Scoring, and when to skip it. Three credible options. A reward model is fast and cheap but reward-hacks on length and confident phrasing. A strong judge LLM scores constraint satisfaction, groundedness and coherence better, but costs GPU time and shows self-preference bias when it's the same family as the generator. Programmatic verifiers are exact and free, but only exist for checkable constraints: valid JSON, exactly three bullets, a required key. My rule: if the constraint is checkable, write the test and skip the model; if it isn't and I have GPU budget, judge; if I have neither, don't score at all. Hand-label 200 pairs and use that to tune the rule filters instead.

I'd skip judge scoring outright when I already have a few thousand human-written pairs to anchor on (LIMA's 1,000 is the canonical case), when synthetic data is a small slice of the mix, or when the judge shares a family with the generator.

Typical yield from my own runs, labelled as such: 100k raw → rule filters drop 20–25% → dedup drops the majority, often half or more → judge scoring keeps roughly a third of what's left, landing near 12k pairs. Two failure modes I check for explicitly: contamination, where synthetic prompts leak eval benchmarks (I run n-gram overlap against the eval sets, not just within the corpus) and over-dedup, which shows up as a corpus whose prompts all start with the same three phrasings.

What would change the design: with 5k human pairs in hand I'd drop stage three entirely and spend the budget on human review of a stratified sample. If the target is a small model, I'd tighten dedup and cut volume harder: small models memorize duplicates faster, so the same 12k pairs buy less diversity there than they would for a 70B model.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Create leakage-resistant dataset splits.

Answer

If your eval scores look suspiciously good, the split is the first suspect. Leakage is any path by which information about a test example reaches training, and three paths bite in practice: near-duplicate text (a paraphrase, a template sibling), group structure (two chunks of one document, two turns of one conversation, two samples from one prompt), and time (training on the future, testing on the past). Assume you have provenance metadata (source doc id, timestamp, author or user id) and that you are building train/val/test for a number you will report.

The order that works: canonicalize, deduplicate, group, split, then augment. Splitting before augmentation matters because augmentation manufactures near-duplicates by construction; augment first and the same seed lands on both sides.

Why near-duplicates inflate scores

A model that has seen a near-copy of a test item answers by retrieval, not generalization. Suppose 20% of a 1,000-item test set has a near-duplicate in train, and the model scores 95% on those versus 60% on the rest: reported accuracy is 0.2·0.95 + 0.8·0.60 = 0.67, seven points above the 0.60 the model actually generalizes at. That gap is the number you would be defending in review.

Measuring overlap before you split

Python
def ngrams(s, n=3):
    return {s[i:i+n] for i in range(len(s) - n + 1)}

a = "the cat sat on the mat"
b = "the cat sat on a mat"
ga, gb = ngrams(a), ngrams(b)
print(len(ga & gb) / len(ga | gb))

Output: 0.7. Two sentences differing by one word share 70% of their 3-grams. At a 0.8 Jaccard threshold this pair survives dedup; at 0.5 it is caught. Pick the threshold from what your eval is sensitive to, not from a default.

At scale, exact hashing catches byte-identical rows; MinHash plus LSH (datasketch.MinHashLSH, 128 permutations, threshold 0.8) catches near-duplicates in near-linear time. For contamination against public benchmarks, the GPT-3 paper used 13-gram overlap between training and test sets: a 13-gram match is strong evidence of shared text.

Grouping keys

keyexamplewhy it leaks
source documentdoc_idchunks of one doc share phrasing
templateform-letter idsame skeleton, different slots
conversationsession_idadjacent turns are near-copies
user/entityuser_idone author's style repeats
generated familyprompt_idsamples from one prompt are siblings
timecreated_atdrift makes future items unrepresentative

Split on the key, not the row: GroupShuffleSplit(groups=df["doc_id"]), or a hash of the key. Then hold out a final test set you touch once.

Trade-offs

A random row split is fine when rows are genuinely independent: i.i.d. scraped sentences with no shared source. It is wrong the moment any key above exists. Temporal holdouts cost coverage: you train on less data and your test distribution is older, so scores drop and you cannot tell whether the drop is the model or the shift. That is the price of measuring what you will actually face. Domain holdouts cost more: a held-out domain may be so different that the number is uninformative.

Failure modes and detection

  • Eval scores that drop 5–15 points when you re-run after dedup: leakage was present.
  • Test items whose nearest train neighbor has Jaccard above 0.8: dedup threshold too loose.
  • A model that aces a public benchmark but fails your held-out set: benchmark contamination.
  • Repeated tuning on the final set: it stops being a test. Keep a third split or rotate.

You cannot prove absence of leakage, only bound it. Document the residual uncertainty and the threshold you chose.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Choose and configure LoRA adapters.

Answer

First I pin three things: the base model and its exact revision, the task (instruction tuning, domain adaptation, or bolting on a new head), and the hardware budget. Those decide everything else.

The core answer: freeze the base, attach low-rank matrices to a chosen set of linear layers, and train only those. In PEFT that is a LoraConfig:

Python
from peft import LoraConfig, get_peft_model

cfg = LoraConfig(
    r=16,
    lora_alpha=32,          # effective scaling = alpha / r = 2
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
)
model = get_peft_model(base, cfg)
model.print_trainable_parameters()

Why it works: each adapted layer computes W @ x + (alpha/r) * B @ A @ x. A is initialized from a Gaussian, B is zero, so at step 0 the model is bit-identical to the base: you can start from a pretrained checkpoint with no warmup mismatch. The alpha/r factor is the effective scale on the update. If you double r and leave alpha fixed, you double capacity but halve the scale, so the adapter's effective learning rate drops; that is why people set alpha = r or 2r and tune the LR separately rather than chasing alpha.

Target modules matter more than rank. The original LoRA paper adapted only q and v. On LLaMA-family models, adding all seven linear projections buys noticeably better quality per parameter at roughly 5x the trainable count. For a 7B model at r=16, q+v is about 8.4M trainable params (0.12%); all seven is about 40M (0.57%).

ralphascalingtypical use
4-88-161-2<10k examples, style or format
16-3216-641-2instruction tuning, domain shift
64-12864-2561-2100k+ diverse examples, near-full-FT quality

Memory is the reason LoRA exists. Full fine-tuning a 7B model with Adam in mixed precision needs about 16 bytes per parameter (fp16 weights and grads, fp32 master weights, and two fp32 moments) so roughly 112 GB of optimizer and gradient state on top of 14 GB of fp16 weights. LoRA at 0.12% trainable needs about 134 MB of optimizer state on the frozen 14 GB, which fits on a single 24 GB card.

Then compare against a frozen baseline with the adapter disabled on a held-out set, and against a full fine-tune if you have one. If train loss falls while eval loss rises, lower r or raise lora_dropout from 0.05 toward 0.1. Run a general benchmark too: LoRA still drifts the base if you train long enough, so retained-capability loss is real.

Validate the merge. W' = W + (alpha/r) * B @ A. Merge in fp32 and cast back: an fp16 merge accumulates error. Compare logits of merged versus unmerged on a fixed batch; they should agree to within a few 1e-3 in fp16.

Failure modes worth testing explicitly. Loading an adapter onto a different base revision: PEFT writes base_model_name_or_path into adapter_config.json but only warns on mismatch, so pin the revision and assert that a wrong-base load is rejected. If you resized the tokenizer, list embed_tokens and lm_head in modules_to_save or the adapter loads and produces garbage. Multiple adapters: set_adapter switches, add_weighted_adapter merges, and vLLM serves several with --enable-lora, --max-lora-rank, --max-loras. Rollback is trivial if you never merge: keep the adapter as a separate artifact and reload the base.

When not to use LoRA: if the task needs a genuinely new vocabulary or a different architecture, or if you have the budget for full fine-tuning and need maximum quality on a large diverse corpus.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design an SFT training run and stopping rule.

Answer

Core answer (first 90 seconds)

Assume a 7B base model, 50k instruction pairs, 8×A100 80GB, target is a chat assistant. I fix the base checkpoint, tokenizer, chat template and train/eval split before anything else, because a template mismatch silently changes the loss mask and makes every later comparison meaningless.

Starting config: full fine-tune at LR 1e-5, 3% warmup then cosine decay to 10% of peak; or LoRA r=16, alpha=32, LR 2e-4. Effective batch 64 (micro-batch 4 × grad-accum 2 × 8 GPUs), seq len 4096 with packing, bf16, grad clip 1.0, 2 epochs, seed fixed. Loss masked to completion tokens only.

Stopping rule: evaluate every 200 steps on a held-out 1k set. Predeclare three signals: validation loss, a task metric (exact-match on a held-out eval), and grad-norm p99. Keep the checkpoint that maximizes the task metric subject to val loss not rising more than 2% above its best; stop when the task metric hasn't improved for 3 consecutive evals (patience 3), or grad-norm p99 exceeds 10× its running median for 20 consecutive steps, or the step budget is hit.

Worked trace (hypothetical 7B LoRA run):

stepval losstask EMgrad p99action
2001.420.310.9keep
6001.180.441.1keep, best
10001.090.471.3keep, best
14001.050.461.6val loss still falling, EM flat
18001.030.442.1EM down 2 evals → stop, restore step 1000

Train loss kept falling to 0.6 by step 1800: classic SFT overfit: the model memorizes demonstration phrasing while the task metric decays.

Why val loss diverges from train loss in SFT: the dataset is small (tens of thousands of examples) and low-diversity, so the model can drive token likelihood to near-zero loss by memorizing exact completions, which doesn't generalize. Val loss is therefore a weak selector: it often keeps improving after the task metric peaks. That's why the stopping rule keys on the task metric and uses val loss only as a guardrail.

Trade-offs:

  • Early stop on val loss alone: cheap, no eval harness needed, but selects a later, worse checkpoint when val loss lags the task metric.
  • Early stop on task metric: matches the deployment objective, but needs a reliable eval set; noisy metrics (n<200) trigger false stops. Use patience ≥3 and a bootstrap CI.
  • Fixed budget: reproducible and simple, but wastes compute when the model converges early and can't catch divergence.

Failure modes:

  • Template mismatch → loss mask includes prompt tokens; detect by printing one decoded batch and checking the mask.
  • LR too high (≥5e-4 full FT) → grad-norm spikes, loss goes NaN; detect via grad-norm p99 and a NaN check each step.
  • Overfitting → train loss falls, task metric flat or declining; detect via the table above.
  • Eval leakage → task metric jumps unrealistically; check the eval set is disjoint from train.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Tune PEFT capacity systematically.

Answer

Assumptions. Single-task SFT of a 7B decoder (LLaMA-7B dims: d_model 4096, FFN 11008), LoRA adapters, one fixed dataset and packing order, bf16. I sweep with one seed, then re-run finalists on three seeds and two data subsets.

Core answer. Fix everything except capacity: data, order, LR schedule, batch size. Sweep rank on a log grid (4, 8, 16, 32, 64) and target modules ({q,v} → {q,k,v,o} → all linear), holding α/r constant so you measure capacity, not effective learning rate. Select on validation task slices plus general/safety retention; never on the final test split. Stop when validation stops improving.

Why it behaves this way. LoRA writes ΔW = (α/r)·BA. Rank r is the dimension of the update subspace; α/r is the scale applied to it. So r=16, α=16 and r=32, α=32 produce the same update magnitude: raise r and leave α fixed and you have changed the learning rate, confounding the sweep. Parameter cost per adapted linear layer is r(d_in+d_out).

Arithmetic for LLaMA-7B:

targetrparamsfp16 ckptAdamW states (fp32)
q,v8131,0720.25 MB1 MB
q,k,v,o16524,2881.0 MB4 MB
all linear16~1.25 M2.5 MB10 MB

All-linear at r=16 is ~0.018% of 7B. The memory argument for PEFT is real; the compute argument is not: you still backprop through the frozen base.

Sweep and saturation. (Hypothetical run, 10k steps.)

configval losstask sliceMMLU Δ
r=4, q,v1.4261.0-0.3
r=16, q,v1.3166.5-0.8
r=16, all1.2967.1-1.9
r=64, all1.2867.0-2.4

Gains saturate near r=16: r=64 buys 0.01 val loss for 4× the params and a larger retention hit. Saturation happens because the task's intrinsic update has bounded rank; past it you fit annotation noise. Detect it by train loss still falling while validation flattens.

Failure modes.

  • α/r confound: raising r without rescaling α. Detect: loss diverges in the first ~100 steps versus the r=8 run.
  • Test leakage: choosing the config by final test score. Detect: keep test untouched; if val and test rank configs differently, selection is overfit.
  • Retention regression: all-linear adapters cost ~2.4× the params of q,v and dropped MMLU 1.9 points here. Detect: fixed general/safety eval per config; treat >2 points as a stop.
  • Seed noise: single-seed deltas under ~0.5 points are noise. Re-run finalists on 3 seeds and 2 data subsets.
Python
from peft import LoraConfig
for r in [4, 8, 16, 32, 64]:
    for targets in [["q_proj", "v_proj"],
                    ["q_proj", "k_proj", "v_proj", "o_proj"],
                    ["q_proj", "k_proj", "v_proj", "o_proj",
                     "gate_proj", "up_proj", "down_proj"]]:
        cfg = LoraConfig(r=r, lora_alpha=r,      # keep alpha/r = 1
                         target_modules=targets,
                         lora_dropout=0.0, bias="none")

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Validate a QLoRA pipeline.

Answer

The 90-second version. Validating QLoRA is four questions in order: is the frozen base quantized the way I think, do the adapters train at the precision I think, does it beat a bf16 LoRA baseline on quality per gigabyte, and does the shipped artifact reproduce the numbers I measured. Checked against bitsandbytes 0.43, peft 0.11, transformers 4.44, on Llama-2-7B: an A100 80GB for the baseline, a 24GB 4090 for the QLoRA run.

Read the quantization config back off the loaded model, not the YAML. Three settings decide the run. bnb_4bit_quant_type="nf4" is the 4-bit NormalFloat codebook. bnb_4bit_compute_dtype=torch.bfloat16 is what each NF4 block is dequantized to before the matmul: leave it unset and you get fp32, which roughly doubles activation memory and gives back the speedup you were buying. bnb_4bit_use_double_quant=True quantizes the per-block absmax constants themselves, saving about 0.37 bits per parameter: ~3 GB on a 65B, ~0.3 GB on a 7B: for one extra dequant step.

Prove the base is frozen and the adapters are not. This catches the most common silent bug: skipping prepare_model_for_kbit_training, which casts LayerNorms to fp32, enables gradient-checkpointing input grads, and freezes the base.

Python
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

cfg = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                         bnb_4bit_compute_dtype=torch.bfloat16,
                         bnb_4bit_use_double_quant=True)
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-hf", quantization_config=cfg,
    torch_dtype=torch.bfloat16, device_map="auto")
model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, LoraConfig(
    r=64, lora_alpha=16, lora_dropout=0.05, bias="none",
    task_type="CAUSAL_LM",
    target_modules=["q_proj","k_proj","v_proj","o_proj",
                    "gate_proj","up_proj","down_proj"]))

q = model.base_model.model.model.layers[0].self_attn.q_proj
print(type(q.base_layer.weight).__name__, q.base_layer.weight.requires_grad,
      q.base_layer.weight.quant_state.quant_type)
print(q.lora_A["default"].weight.dtype, q.lora_A["default"].weight.requires_grad,
      tuple(q.lora_A["default"].weight.shape))
print(sum(p.numel() for p in model.parameters() if p.requires_grad))

That prints:

Params4bit False nf4
torch.bfloat16 True (64, 4096)
159907840

The first line is the point: the base weight is a Params4bit tensor, it does not require grad, and its quant state says nf4. The second says the adapter is bf16 and trainable. The third is arithmetic you can check by hand: r=64 over seven projections, each contributing 64×(in+out), summed over 32 layers: 32 × 64 × (4×8192 + 3×15104) = 159,907,840, about 2.4% of the 6.74B total. If that count is 6.7B you forgot to freeze; if it's zero, get_peft_model matched no module names.

Memory, with the arithmetic. For 7B at sequence length 2048, micro-batch 1, gradient checkpointing on:

weightsgradsAdam (fp32 m,v)floor
full FT, bf1613.5 GB13.5 GB54 GB~81 GB
LoRA, bf1613.5 GB0.32 GB1.28 GB~15 GB
QLoRA, NF43.4 GB0.32 GB1.28 GB~5 GB

NF4 stores 6.74B weights at 0.5 bytes plus ~0.1 GB of block constants. The 160M adapter costs 0.32 GB in bf16 and 1.28 GB of fp32 Adam moments. That ~5 GB floor is why a 7B fits on a 24GB card at all; the full-FT column is why you'd need two 80GB cards, plus 27 GB of fp32 master weights if you keep them.

Quality. Same data order, same effective batch, same LR schedule, three seeds, held-out eval. QLoRA's published result is that 4-bit NF4 with double quantization and paged optimizers matched 16-bit full fine-tuning on their benchmarks: that's their data, not yours. Run the bf16 LoRA baseline on your task; if QLoRA loses more than a point or two on your metric, the 4-bit error floor is showing, and you should check whether the loss is concentrated on numeric or long-context items.

Failure modes and how you'd see them. Merge into a 4-bit base: merge_and_unload() dequantizes to fp16 first, so peak memory jumps to the full-FT column. Watch torch.cuda.max_memory_allocated() during merge. Serve-time mismatch: training with double quant and serving without it changes the dequantized weights; hash the quantized state dict and re-run a fixed 32-prompt eval, comparing logits within tolerance. Long context: NF4 blocks dequantize to bf16, but at 8k+ tokens attention activations dominate; step 512→4096 and watch for a loss spike in the first 50 steps. fp16 compute dtype on long sequences overflows: same test catches it.

When QLoRA is the wrong call. If the model fits in bf16 with LoRA, use plain LoRA: the 4-bit step is slower per step because every weight block is dequantized before the matmul, and you're paying a quantization error floor for nothing. Paged optimizers only earn their host-device copies when you actually spike.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Detect and mitigate forgetting during fine-tuning.

Answer

What I'd say first. Two things decide this answer: is the base checkpoint available to compare against, and is the target task narrow (one domain, one output format) or broad? Forgetting is worst when the fine-tuning set is small, homogeneous, and trained for several epochs at a high learning rate. So: measure it with a fixed regression suite run on the base and on every checkpoint, then mitigate with lower-capacity updates, replay, and a KL anchor to the base model.

Why it happens. Fine-tuning moves every weight toward the target distribution. The same matrices that encode general capability also carry the target signal, so gradient steps that cut loss on 5k narrow examples drag general behaviour with them. How far the weights travel is what matters: more epochs, higher LR, and full-parameter updates move them further than low-rank ones. That is why LoRA (rank 8–64 with alpha scaling) forgets less, it restricts the update to a low-rank subspace, and why a KL penalty against the base model's logits bounds drift directly rather than hoping for it.

Detection. Run lm-evaluation-harness on base and checkpoint over MMLU, GSM8K, HellaSwag and TruthfulQA, plus your own domain and safety sets. Compare per-slice, not the average: a 2-point MMLU drop can hide a 15-point drop on one subject. Also compute mean KL divergence between base and tuned logits on ~2k held-out general prompts; I flag above 0.5 nats. A fixed 100-prompt human review catches style and refusal drift that benchmarks miss.

Worked example (illustrative numbers). 7B model, 5k domain examples, full fine-tune at LR 2e-5:

configtarget accMMLUGSM8Krefusal rate
full FT, 3 epochs91.055.131.082%
full FT, 1 epoch88.561.844.296%
LoRA r=16, 2 epochs, 10% replay88.062.446.597%
base—63.248.098%

Row one is the failure: target accuracy is highest, but 8 points of MMLU and 17 of GSM8K are gone and refusals fall 16 points. One epoch, or LoRA with replay, buys most of that back for about 3 points of target accuracy.

Failure modes and how to catch them. Refusal drift: fixed red-team set, alert if refusal rate drops more than 5 points. Calibration drift: expected calibration error on a held-out QA set rises while accuracy holds. Replay contamination: check replay examples do not overlap the target eval set. Adapter routing: if you serve separable adapters, log which one handled each request. Misrouting shows up as target-format answers on general prompts.

Trade-offs. Replay costs compute and dilutes the target signal; KL anchoring slows convergence; LoRA caps the target accuracy you can reach. Choose based on how much target accuracy you are willing to give up, and gate the release on the regression suite, not on the target metric alone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Build a preference dataset and DPO experiment.

Answer

Clarify, then assume. I'd ask: what's the base policy, is there a reward model already, what's the eval budget. Assume a 7B SFT'd policy, one A100 node, no reward model, and a goal of beating the SFT baseline on a held-out preference eval without regressing safety or general capability.

Core answer. Three phases: build the preference set, run DPO, evaluate against slices.

Phase 1: dataset. Sample prompts from production traffic or a public mix (UltraFeedback, HH-RLHF) stratified by task type, and hold out 10% of prompts before generating anything so no prompt appears in both train and eval. For each prompt, generate 4–8 candidates from the SFT policy at temperature 0.8–1.0, then have 3 raters label pairs on a 5-point rubric (correctness, helpfulness, safety, style) with an explicit tie/uncertain option. Keep pairs where ≥2 raters agree on direction; adjudicate the rest with a senior rater. Target 5k–20k pairs for a first run: below ~2k the DPO gradient is dominated by label noise, above ~50k you usually get more from better labels than more pairs. Store prompt, both responses, rater IDs, model version, sampling params, and template hash.

Phase 2: training. Pin the reference policy (frozen SFT checkpoint), tokenizer, chat template, and β. β=0.1 is the TRL default and a reasonable start; it sets how far the policy may drift from the reference. The loss is

L = -log σ(β[log π(y_w|x)/π_ref(y_w|x) − log π(y_l|x)/π_ref(y_l|x)])

Worked trace, β=0.1, one pair:

termvalue
log π(y_w|x)−12.0
log π_ref(y_w|x)−14.0
log π(y_l|x)−18.0
log π_ref(y_l|x)−15.0
implicit margin0.1·(2.0 − (−3.0)) = 0.5
loss−log σ(0.5) = 0.474

Phase 3: eval. Held-out win/tie/loss vs the SFT reference, plus factuality, calibration (ECE), safety, verbosity, and general retention (MMLU/GSM8K).

Failure modes.

  • Length exploitation: chosen responses longer than rejected by >20% tokens → the model learns verbosity. Detect by logging mean token delta per step; fix by length-matching pairs or adding a length penalty.
  • Likelihood displacement: chosen logprob falls while margin rises. Detect by tracking log π(y_w|x) on a fixed probe set.
  • Margin collapse: implicit margin → 0 early, meaning reference and policy are too close or labels are noisy.
  • Eval reward hacking: win rate up but MMLU down >2 points → over-optimization.

Trade-offs. DPO vs PPO: DPO needs no reward model and one training loop, but it's offline and sensitive to β and label noise; PPO can use online samples but needs a reward model and is far more fragile. Offline filtering (best-of-n rejection sampling + SFT) is cheaper and often within a point of DPO when labels are weak. β: 0.01 drifts fast and can degenerate; 0.5 barely moves. Dataset size vs quality: 5k clean pairs beat 50k noisy ones.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Audit preference-label quality.

Answer

If I'm asked to audit preference-label quality, I'd assume we're talking about human pairwise preferences used to train an RLHF reward model. First, clarify the scale and budget: are we auditing 1,000 pairs or 100,000? Is the model already deployed? That decides how heavy the audit should be.

The audit has three phases. Phase one is collection controls. Randomize the order of A and B, blind the model identity, and balance lengths and styles. Collect rater background and training, and get at least three labels per pair on a 10% sample. For 1,000 pairs, three expert labels at $2 each costs $6,000 and takes about a week.

Phase two is statistical reliability. Compute Krippendorff's alpha on the sample. Alpha above 0.8 is good; 0.667 to 0.8 is tentative; below 0.667 means the labels are too noisy to trust. Slice by length, style, and demographic framing. Here's a worked example. Suppose 100 pairs, two raters. Confusion matrix: both prefer A: 40, both prefer B: 30, rater1 A rater2 B: 15, rater1 B rater2 A: 15. Observed agreement is 0.70. Expected agreement is (0.55^2 + 0.45^2) = 0.505. Cohen's kappa is (0.70 - 0.505)/(1 - 0.505) = 0.394. That's poor. Now slice by length: when A is longer, 70% of labels prefer A; when B is longer, 65% prefer B. That's a length bias of 17.5 percentage points above chance. That's a red flag.

I'd track a few metrics with thresholds:

MetricThresholdAction if fail
Krippendorff's alpha>0.8 good; 0.667-0.8 tentative; <0.667 poorRetrain raters or discard noisy pairs
Length bias<10 percentage points above chanceAdd length-controlled pairs
Sycophancy bias<10 percentage points above chanceAdd adversarial pairs

Phase three is targeted counterexample validation. Create pairs where the correct answer is shorter, where the agreeable answer is wrong, and where demographic framing is irrelevant. Have experts label these and compare to the reward model's predictions. If the model's reward correlates with length more than with expert preference, the labels are the problem. Validate with real task outcomes, not reward score alone.

The trade-off: a full audit with expert raters and multiple labels is expensive. A lightweight audit on 500 pairs with two crowd raters costs about $1,000 and takes two days, but only detects biases larger than 10% with 80% power. So if the model is already deployed, do the full audit; if pre-training, start lightweight and escalate if kappa < 0.6 or length bias > 10%.

The main failure modes are verbosity bias, sycophancy, and demographic framing. Verbosity bias shows up as >60% preference for longer answers when quality is equal. Sycophancy shows up as >60% preference for answers that agree with the prompt's implied stance. Demographic framing shows up as preference differences across demographic slices. Each counterexample costs about $50 to expert-review.

Adjudicate high-risk conflicts with a third expert, retain ties and uncertainty, and document the audit's limitations. If the audit shows kappa below 0.6 or length bias above 10%, stop training and fix the labels before proceeding.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

You're running RLHF with PPO on top of an SFT model. Walk me through how you build the reward model, control the KL penalty, and keep the policy from reward hacking.

Answer

Pin the setup first: the SFT model frozen as the reference, a reward model trained on pairwise human preferences, and PPO optimizing the policy against that reward with a per-token KL leash. Everything else is detail.

Preference data. Prompts come from the distribution you'll deploy on: production traffic or the SFT prompt mix, not a clean academic set. For each prompt, sample 2–4 completions from the SFT policy at temperature 0.7–1.0 so the pairs are on-policy; off-policy pairs (say, GPT-4 outputs) teach the RM to score a distribution PPO never visits. Raters see blinded, order-randomized pairs and can pick a tie. InstructGPT collected ~33k comparisons from ~40 contractors for the RM and held out ~16k; held-out RM accuracy was around 72%, and that number is the ceiling on what PPO can learn: a 60% RM gives you noise.

Reward model. Initialize from the SFT checkpoint, replace the unembedding with a scalar head, train with the Bradley-Terry loss:

python

PyTorch 2.x, transformers 4.x

import torch.nn.functional as F

def bt_loss(r_chosen, r_rejected): return -F.logsigmoid(r_chosen - r_rejected).mean()

One epoch, LR ~1e-5 to 1e-6, and keep prompt groups intact across the train/val split so the same prompt never appears on both sides. Only the difference matters, so the RM is shift-invariant, which is also why it has no absolute scale and why PPO's advantage estimates need a critic.

Length bias. If raters prefer longer answers, the RM learns length as a proxy and PPO exploits it: response length climbs, reward climbs, human win rate does not. Guard by balancing pair lengths, adding a length penalty at scoring time, or training a length-controlled RM. Test with counterfactuals: take a winning pair, pad the loser, and check the RM doesn't flip.

KL control. Add a per-token penalty against the frozen SFT reference:

reward = r_θ(x, y) − β · Σ_t KL(π_θ(·|x, y_<t) ‖ π_ref(·|x, y_<t))

InstructGPT used β = 0.02 fixed, and also an adaptive controller targeting KL ≈ 6 nats. The arithmetic matters: a 200-token response with mean per-token KL of 0.03 nats sums to 6 nats, costing 0.02 × 6 = 0.12 reward units. Comparable to the RM's own spread, so β is a real budget, not a rounding term. Too small and the policy drifts off-distribution into RM blind spots; too large and it never moves.

PPO. Four models resident: policy, reference, reward, critic. Clip ratio 0.2, GAE for advantages, γ = 1.0. The critic is the usual source of instability, if value loss diverges, advantages go wild and the policy collapses to one high-reward string.

Reward hacking. The signature is reward up, human win rate flat or down. Track mean reward, mean KL, response length, and policy entropy every step, and run a held-out human or model-graded eval on a fixed prompt set. Common hacks: verbosity, sycophancy, bulleted list spam, refusal-shaped text that scores well on a safety-heavy RM. If you see it, the fix is usually more on-policy preference data near the hacked region, not a bigger β.

When not to do this. If you already have a static preference set and no need for online sampling, DPO fits the same objective in closed form with one model and no critic. RLHF earns its complexity when the reward is non-differentiable (a safety classifier, a unit test, a tool result) or when you need to sample on-policy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Distil a larger teacher model into a smaller fine-tuned student: how do you choose between logit matching, rationale/chain-of-thought distillation and rejection-sampled outputs, and how do you verify the student retains the teacher's behaviour without inheriting its hallucinations or verbosity?

Answer

First 90 seconds. Ask what the student is for. If it is a fixed task with a closed answer set (classification, extraction, routing), logit matching gives the most signal per token and is the cheapest to verify. If the difficulty is in the intermediate steps (math, multi-hop, code), the teacher's rationales carry information the final answer does not, so distil the rationales. If the teacher is API-only and you have a cheap automatic checker, rejection sampling is the only one of the three that works. Then state the assumption that decides everything: you need a ground-truth-anchored eval, not teacher agreement, because the teacher is both the ceiling and the source of the hallucinations you are trying to avoid.

Logit matching. Minimise forward KL between temperature-softened distributions:

Python
# PyTorch; teacher and student share a tokenizer
T = 2.0
loss = F.kl_div(F.log_softmax(student_logits / T, dim=-1),
                F.softmax(teacher_logits / T, dim=-1),
                reduction="batchmean") * T**2

The T**2 factor restores the gradient magnitude lost to the 1/T scaling. Worked numbers: teacher logits [2.0, 1.0, 0.0], student [1.0, 1.0, 0.0], T=2. Softmax gives teacher [0.506, 0.307, 0.186] and student [0.384, 0.384, 0.233]; KL(teacher‖student) ≈ 0.031, so the scaled loss is ≈ 0.124. The signal is in the 0.307 vs 0.186 gap: the teacher's ranking of the wrong tokens, which hard labels throw away. Use it when vocabularies match and outputs are short; it degrades on long generations because one tokenizer mismatch poisons every position.

Rationale distillation. Teacher generates CoT; student is SFT'd on it. Wins when the reasoning is the skill. Two failure modes: the student learns the teacher's style of reasoning (hedging, restating, "let me think step by step") rather than the computation, and it inherits confident-but-wrong chains. Mitigate by training only on rationales that end in a verified answer, and by truncating each rationale to the shortest chain that reaches it.

Rejection sampling. Sample N (typically 4–16) completions per prompt, keep those a verifier accepts, SFT on the survivors. Works with API-only teachers. The verifier is the whole game: a length-blind verifier selects verbose outputs, because longer chains have more chances to hit the right answer; a weak verifier amplifies its own bias. That is the mechanism behind the verbosity you are worried about: it is not the teacher, it is the filter.

Combining. Standard recipe: rejection-sample to build a clean dataset, SFT, then add logit matching if you have logits. On-policy variants (GKD) sample from the student and get teacher feedback on those, which fixes exposure bias.

Verification. Split held-out prompts into three buckets and score each separately:

BucketMetricTarget
Verifiable (known answers)exact match / pass@1within 2 points of teacher
Unverifiable-but-factualhallucination rate vs. a fact set with known answers≤ teacher's rate, abstention rate not lower
Open-endedlength-controlled win rate (AlpacaEval 2.0 LC) vs. teacher, mean output tokensLC win rate ≥ 50%, mean length within 10% of teacher

Teacher agreement is a diagnostic, not a target: high agreement on bucket 1 is good; high agreement on bucket 2 means you cloned the hallucinations. Calibration (ECE) catches a student that is confidently wrong where the teacher was uncertain.

Failure modes and detection. Hallucination inheritance → bucket-2 rate rises; fix by filtering with a verifier, not by more epochs. Verbosity → mean tokens up, LC win rate down; fix with a length penalty or a length-normalised verifier. Mode collapse → distinct-n or output entropy drops; usually N too small or a verifier that accepts one style. Catastrophic forgetting → a general-capability suite (e.g. an MMLU subset) drops; mix in a fraction of general SFT data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

When do you merge a LoRA adapter into the base weights, and how do you combine several fine-tunes into one model without them interfering?

Answer

First 90 seconds. Merging one LoRA is exact and cheap, so the default is to merge: LoRA learns ΔW = (α/r)·BA, and W₀ + (α/r)·BA computes the same function the unmerged adapter does. Merge when you serve a single adapter, want a plain checkpoint any runtime can load, or want to drop the extra matmul per layer. Keep it separate when one base serves many tenants, when the base is 4-bit and you can't materialize bf16, when you need to toggle or A/B the adapter, or while you're still iterating and re-merging every checkpoint is wasted work.

Merging several fine-tunes is a different problem. Each is a task vector τᵢ = θᵢ − θ₀. Naive task arithmetic, θ₀ + Σλᵢτᵢ, breaks because the vectors conflict: two adapters push the same weight in opposite directions, and most of each delta is noise. TIES and DARE are the standard repairs.

Mechanism. TIES does three things per tensor: trim to the top k% of |τ| (k = 20% in the paper), zeroing the rest; elect a sign per parameter by summing the signed values and taking the majority; then disjoint-merge, averaging only the values whose sign matches the elected one. That removes sign conflicts, the dominant source of interference. DARE attacks redundancy instead: randomly drop p% of the delta (p = 0.9 for 7B–13B in the paper), rescale survivors by 1/(1−p) so the expectation is preserved, then apply TIES or plain averaging. DARE+TIES is the usual combination.

Worked trace, one weight, two adapters:

stepwnote
base w₀0.100
τ_A+0.040
τ_B−0.030
linear sum0.110signs partly cancel
elect sign+Σ signed = +0.010
disjoint merge+0.040τ_B dropped, sign disagrees
merged0.140

The linear merge lands at 0.110, TIES at 0.140: the gap is exactly the parameter where the two tasks fought.

Single-adapter merge:

python

peft 0.11, transformers 4.44, bf16

base = AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.bfloat16) model = PeftModel.from_pretrained(base, adapter_id) model = model.merge_and_unload() # W0 + (alpha/r) * B @ A model.save_pretrained(out_dir)

Failure modes. (1) Numerics: the merge is exact in real arithmetic but not in bf16. Expect ~1e-3 relative drift, so re-run the eval suite on the merged checkpoint rather than assuming equivalence. (2) Quantized bases: PEFT dequantizes a 4-bit base to fp16/bf16 to perform the merge, so you end up with a full-precision model; if you need 4-bit serving, merge into an fp16 base and re-quantize with GPTQ/AWQ, then re-evaluate. Don't merge into the 4-bit weights in place. (3) Rank mismatch: the sum of two rank-r adapters is not rank r; to re-express it as one LoRA you need r ≥ r_A + r_B, otherwise store the merged full matrix. (4) Scaling mismatch: normalize by α/r before merging, or a high-α adapter silently dominates. (5) Different bases: τ is only meaningful against the same θ₀ revision; merging deltas from two base checkpoints produces garbage that still loads cleanly. (6) No per-task eval after merging: interference shows up as one task regressing while the aggregate looks fine.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Promote a LoRA adapter into serving.

Answer

Core answer

The adapter is only meaningful relative to one base checkpoint at one revision. Promotion is: prove the adapter's declared base matches the base you're about to serve, choose merge or dynamic load, gate on evals, then canary with a rollback that is a pointer flip.

In the first minute I'd say: read adapter_config.json and check base_model_name_or_path, r, lora_alpha, target_modules, peft_type. Confirm the base you serve is the same repo and revision: a re-uploaded base under the same name is a different tensor set. Confirm every name in target_modules exists in the base's module tree. Then pick the serving path.

Why the checks matter

LoRA computes W x + (alpha/r) * B A x. The alpha/r scaling is baked into the trained behavior: load the adapter with a different r or alpha and you silently rescale every adapted layer. Rank and alpha are part of the compatibility contract, not metadata. Same for target_modules: if the base fuses projections (qkv_proj) where the adapter expects separate q_proj/k_proj/v_proj, the A/B matrices attach to nothing or attach wrong. You get a load error, or worse a silent no-op that serves the base model.

Tokenizer and chat template live outside the weights and are the most common silent regression: the adapter was trained on a specific template and special-token set, and serving it under the base's default template shifts the prompt distribution.

Merge vs dynamic load

merge (merge_and_unload())dynamic (vLLM --enable-lora, --lora-modules name=path)
memoryfull model copy per adapterone shared base, small adapter tensors
per-request costnoneadapter matmul, grows with rank and adapter count
multi-adapternoyes
rollbackredeploy weightsflip the served name

Deciding criteria: one adapter, latency-critical, no rollback-by-name → merge. Several adapters or frequent promotion → dynamic. vLLM caps rank with --max-lora-rank (default 16), so a rank-32 adapter needs that raised before it will load.

Arithmetic (illustrative)

Base: 7B params, fp16 = 14 GB. Adapter at r=16 targeting q_proj and v_proj on 32 layers, hidden 4096: per module 4096*16 + 16*4096 = 131,072 params; two modules × 32 layers = 8.4M params ≈ 17 MB fp16. Dynamic load shares the 14 GB and adds ~17 MB per adapter: that is the whole argument for it. Target all seven linear modules and it is ~40M params ≈ 80 MB.

Failure modes and detection

  • Wrong base revision: adapter loads, loss looks plausible, outputs subtly off. Detect by hashing base weights against the revision recorded at training, and gate on golden outputs, not on load success.
  • Partial load / missing target module: silent no-op serving the base. Detect by asserting the injected LoRA layer count equals expected, and by a golden-output diff that must move.
  • Cache mixing: a KV/prefix cache keyed only by prompt returns another adapter's continuation. Detect by putting the adapter id in the cache key and canarying two adapters on identical prompts.
  • Rollback: keep the previous adapter registered; rollback is flipping the served name, not a redeploy.

Gate

Run a golden set of ~100–200 prompts with expected outputs, schema and tool calls on the packaged runtime (same dtype, quantization, PEFT and vLLM versions), shadow, then a 1–5% canary, comparing refusal/safety rates and p50/p99 latency against the base before full rollout.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design multi-adapter serving safely.

Answer

Core answer. One base model per replica; adapters are attached per request, and the client never names the adapter. The client authenticates, the gateway maps (tenant, task) to an adapter_id through a versioned policy, and the serving engine loads that adapter into a bounded slot pool. If the mapping is missing, revoked, or built against a different base revision, the request fails with 503: it never silently falls back to the base model, because a base-model answer is a wrong answer that looks like a right one.

Registry. Each adapter ships as a signed manifest: adapter_id, base_revision (the HF commit sha of the base weights), adapter_sha256, tokenizer_sha256, chat_template_hash, rank, target_modules, status, allowed_tenants. The signature covers canonical JSON and is verified on the serving node at load time, not just at publish time. base_revision and chat_template_hash are the two fields that catch the expensive mistakes: an adapter trained against a different base revision produces fluent garbage, and a template mismatch silently changes the prompt the adapter was tuned on.

Selection. Server-side, from authenticated context:

Python
def select_adapter(ctx, policy):
    entry = policy.get((ctx.tenant_id, ctx.task))   # versioned policy, loaded at boot
    if entry is None or entry.status != "active":
        raise NoAdapter(ctx.tenant_id, ctx.task)     # 503, never fall back to base
    if entry.base_revision != BASE_REVISION:
        raise BaseMismatch(entry.adapter_id, entry.base_revision, BASE_REVISION)
    return entry.adapter_id

Sizing. A rank-16 LoRA on a 7B model (hidden 4096, 32 layers, q/k/v/o) is 2 * 16 * 4096 * 4 * 32 ≈ 16.8M params, about 33 MB in fp16. Eight resident adapters cost ~264 MB against ~14 GB of fp16 base weights: the base is the expensive part, which is the whole argument for multi-adapter serving. vLLM's LoRA path exposes --enable-lora, --max-loras, --max-lora-rank, --lora-modules, --max-cpu-loras (as of vLLM 0.6, --max-loras defaults to 1 and --max-lora-rank to 16). Set --max-loras to your measured concurrent working set and --max-cpu-loras well above it. A 33 MB adapter moves from pinned CPU memory over PCIe at ~10 GB/s in ~3 ms; from NVMe at ~3 GB/s in ~11 ms plus safetensors parse. That gap is why eviction thrash shows up as a p99 TTFT cliff, not a gradual slope.

Trade-offs.

DecisionOption AOption BPick
PlacementDedicated replica per tenantShared base, adapters per requestDedicated when a tenant's traffic saturates a GPU or isolation is contractual; shared otherwise
Adapter namingClient sends adapter_idServer derives from auth contextServer-side; client-supplied needs an authorization check on every call and fails open when it is forgotten
Missing adapterFall back to baseFail closed (503)Fail closed for anything user-visible
BatchingOne adapter per batchMixed-adapter batch (S-LoRA-style unified paging)Mixed once working set > 1; the S-LoRA paper (MLSys 2024) reports thousands of adapters per GPU

Failure modes and detection.

FailureSymptomDetection
Wrong adapter servedTenant sees another tenant's style or dataLog (request_id, tenant, adapter_id, adapter_sha); assert tenant→adapter in the response path; canary tenant whose adapter emits a unique token
Eviction thrashp99 TTFT jumps from ~40 ms to ~300 msadapter_load_total rate and CPU-cache hit ratio; alert when loads/request > 0.1
Revoked adapter still residentCompliance breach after revocationRegistry TTL (30 s) plus push invalidation; compare served adapter_sha against registry each minute
Cross-tenant KV reuseLeaked prefixKey prefix cache on adapter_id, not token ids alone; disable prefix caching with LoRA until verified
Base/adapter driftFluent but wrong answersPin base_revision; block rollout when it differs

Rollout. Prewarm adapters on deploy, circuit-break a failing adapter after N consecutive load errors, and keep the previous policy version so rollback is a policy swap, not a redeploy. Test with a wrong-tenant request, a rapid swap loop, a concurrent mixed-adapter batch, and a revoked adapter mid-flight.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Operate a distributed fine-tuning job reliably.

Answer

Answer first. A distributed fine-tuning job is a stateful process spread across N ranks that must either finish with a correct model or fail loudly. Reliability reduces to one invariant: any restart resumes to the exact data order and optimizer state it would have had without the crash. Dashboards and alerts exist only to catch that invariant breaking before it costs you a week of GPU time.

Three failure classes kill these jobs: silent data divergence (ranks disagree on which examples they see), numerical instability (loss-scale overflow, NaN), and infrastructure churn (stragglers, preemption, storage). Watch one signal per class, not forty.

signalhealthybreach meansaction
fp16 loss scalehalves rarelyhalving every few stepsoverflow; inspect the batch, or move to bf16
grad normbelow clip value (1.0)10x spikeskip the step, log the batch id
per-rank step timewithin 5% of medianone rank 30% slowerstraggler: check NIC/thermal on that host
val losstracks trainrises while train fallsoverfit, or a train/val leak
consumed example idsunion == dataset, no dupesmissing or duplicate shardssampler seeding bug

Checkpoint and resume. The trap is restoring the model and optimizer but not the sampler and RNG state.

Python
# torch 2.3, one process per GPU under torchrun
def save_ckpt(path, model, opt, sched, sampler, step):
    if dist.get_rank() == 0:
        tmp = path + ".tmp"
        torch.save({
            "step": step,
            "model": model.state_dict(),
            "opt": opt.state_dict(),
            "sched": sched.state_dict(),
            "sampler_epoch": sampler.epoch,      # DistributedSampler
            "rng": torch.get_rng_state(),
            "cuda_rng": torch.cuda.get_rng_state(),
        }, tmp)
        os.replace(tmp, path)                    # atomic: never a half-written file
    dist.barrier()

On resume: load, call sampler.set_epoch(saved["sampler_epoch"]), restore both RNG states, then skip the first step batches. Skip the sampler epoch or RNG and rank r replays a different shard order: the loss curve looks normal while the model trains on a different data mix. Detect it by all-gathering the ids each rank consumed and asserting the union equals the dataset with no duplicates.

How often to checkpoint. Cost C is the barrier plus the write: a 7B model's weights and Adam state is roughly 100 GB, and at ~2 GB/s to shared storage that is ~50 s. Spot MTBF is ~8 h = 28,800 s. The Young/Daly optimum is sqrt(2 * C * MTBF) = sqrt(2 * 50 * 28,800) ~= 1,700 s, about 28 minutes. At a 30-minute interval you pay ~2.8% overhead; at 10 minutes, ~8.3%. Checkpointing more often than the optimum buys nothing.

Trade-offs. bf16 has fp32's exponent range, so it needs no loss scaling and no overflow-skip machinery, at the cost of 8 mantissa bits versus fp16's 10; on A100/H100 it is the default. Reach for fp16 only when you need the extra precision and can run the scaler. For the checkpoint target, local NVMe is fast but dies with the node; a shared object store survives preemption but is slower: write local, async-copy to S3, keep the last two.

Failure modes and detection. Preemption mid-write: atomic rename plus a checksum on load, falling back to the previous checkpoint. Straggler: per-rank step time, alert when max/median exceeds 1.2 for 10 consecutive steps. Loss-scale collapse: count skipped optimizer steps; more than 5% per 1,000 means switch precision. Before promotion, reconcile the final token count and dataset hash against the plan.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Assess and reduce fine-tuning privacy risk.

Answer

Core answer (first 90 seconds)

Assume you own the fine-tuning job and the base checkpoint, you can inspect the training corpus, and the threat model is an external user who can prompt the deployed model but cannot read weights. "Privacy risk" here means three different things: verbatim regurgitation of rare training strings, membership inference (did record X train this model?), and attribute/PII leakage, and each has its own test.

Answer: measure before you mitigate. Insert synthetic canaries, run extraction probes against base and tuned checkpoints, and only then choose between deduplication, PII scrubbing, DP-SGD, or not fine-tuning at all.

Why duplication drives memorization

Memorization is a function of how many times a sequence is seen, how unique it is, model size, and prompt length. Carlini et al.'s 2022 study found extractability grows roughly log-linearly with duplication count and model scale: a string seen once is rarely extractable, one seen dozens of times often is. That makes deduplication the highest-leverage reduction: more so than adding redaction rules.

Worked check

Canary design: 200 canaries, each a 32-char high-entropy token (CANARY-7f3a9c2e-...), inserted once each; plus 20 "duplicated" canaries inserted 50 times each. Probe by prompting with the first 8 tokens and greedy-decoding 32 tokens. Figures below are illustrative.

probebasetunedread
canary, 1× (n=200)0/2002/200borderline: inspect those 2
canary, 50× (n=20)0/2011/20duplication is the driver
real rare PII (n=50)0/503/50those 3 records are the retrain set

Threshold: any 1× canary extracted means near-duplicate leakage in the corpus; treat >5% extraction on duplicated canaries as a fail.

Reduction options and cost

  • Dedup: exact plus near-dup (MinHash, ~0.8 Jaccard). The C4 study found a few percent of examples duplicated; removing them cut memorization with no quality loss. Cheap.
  • PII scrub: Presidio/regex plus NER. Cheap, strong on structured PII, weak on names buried in prose.
  • DP-SGD (Opacus): gives a formal ε guarantee, but per-example clipping and noise cut throughput several-fold and usually cost accuracy. Start at ε ≤ 8 and report it.
  • Don't fine-tune: RAG over the sensitive corpus keeps data out of the weights. Often the right call.

Failure modes

  • Canaries pass but real data leaks: canaries are synthetic and may miss the real distribution. Always include held-out real rare strings.
  • Membership inference is noisy: one high-confidence hit is not proof. Use a calibrated attack (Shokri-style shadow models) and report AUC, not anecdotes.
  • Deletion: you cannot edit a weight. Verify lineage: retrain from the last clean checkpoint and confirm the canary or record is no longer extractable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Defend fine-tuning against poisoning and backdoors.

Answer

Threat model and assumptions. The attacker controls a slice of the fine-tuning corpus (a scraped set, a vendor's labels, a contributor's PR) and wants either a targeted backdoor (input contains trigger T → model emits the attacker's label) or a systematic bias. Assume they do not control the base model, the tokenizer, or the training code. If they do, data screening is the wrong layer; you are defending the pipeline, not the data.

Core answer. Defend in three layers, in this order: (1) provenance and access control so you know who contributed what and can revoke it; (2) statistical screening of the corpus before training; (3) post-training behavioural tests against a clean baseline, plus lineage so you can excise and retrain. Screening alone never certifies a dataset clean: it raises attacker cost and shrinks the blast radius.

Why backdoors survive screening. A trigger is a low-frequency pattern; a few hundred examples with a strong label signal carve a sharp region in weight space that ordinary gradient steps on the clean majority do not overwrite. That is why poison rates far below 1% work, and why "we deduplicated" is not a defence: dedup removes exact and near duplicates, not a semantically distinct poisoned example.

Worked arithmetic (hypothetical figures). Corpus 1,000,000 examples; poison rate 0.1% → 1,000 poisoned. Clean holdout of 500 examples: expected poisoned examples = 500 × 0.001 = 0.5, so P(at least one) = 1 − e^−0.5 ≈ 0.39. A holdout-based trigger test is a coin flip for even seeing the poison, and one example will not fire a trigger. Holdout testing alone cannot find a 0.1% backdoor: you need a targeted trigger suite built from the attack you fear, or a much larger holdout.

Screening that localises poison. Per-example loss outliers catch examples that are hard for the model in a way clean data is not. Modified z-score on loss, threshold 3.5:

Python
import numpy as np
losses = np.array([0.42, 0.39, 0.51, 0.44, 3.87, 0.47, 0.40, 4.12, 0.45])
med = np.median(losses)                      # 0.45
mad = np.median(np.abs(losses - med))        # 0.05
z = 0.6745 * (losses - med) / mad
flagged = np.where(np.abs(z) > 3.5)[0]
print(flagged)                               # [4 7]

Indices 4 and 7 (losses 3.87, 4.12) are the outliers. This is triage, not proof: high-loss examples are also mislabeled or genuinely hard. Pair it with influence functions or a small ablation: retrain with the flagged set removed and see whether the trigger still fires.

Layered defences, what each costs and misses.

LayerCatchesCostMisses
Provenance / signed contributionsUntraceable or revoked sourcesPipeline workA trusted source that was itself poisoned
Rare-token / n-gram frequency scanFixed triggers using rare tokensCheap, minutesAdaptive triggers built from common tokens
Loss / influence outlier triageExamples that shift the modelOne extra passMislabeled-but-honest data
Clean holdout + trigger suiteKnown trigger familiesHoldout must be large (see above)Novel triggers
Lineage + retrain from clean baseEverything, eventuallyFull retrainCost, and a poisoned base model

Trade-offs. Filtering is cheap and preserves most of the corpus; retraining from a clean base is the only move that bounds an unknown poison rate. Decide by whether you can bound the poison rate and whether the trigger is safety-critical. If a safety classifier can be flipped, retrain; if it is a style regression, filter and monitor.

Failure modes. A trigger that survives retraining because it lives in the base model or tokenizer: test the base model with the trigger before blaming the data. A clean holdout too small to catch the poison rate (the arithmetic above). Label-flipping that looks like ordinary noise. Detection that only works on the attack you imagined.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Respond to a fine-tuning safety regression.

Answer

First 90 seconds

Clarify two things before touching anything: is the regression user-visible (a policy-violating output already served to a customer) or only visible in the eval harness, and is the canary still taking traffic? Assume a fine-tuned model served behind a pinned ft: model ID, a 5% canary, moderation logging on every response, and a red-team suite that runs pre-promotion.

Then: kill the canary, route traffic back to the pinned previous model ID, freeze the new artifact so nothing else promotes it, and preserve the failing slice. Diagnose after exposure is zero, not before.

Why a fine-tune regresses safety

Refusal and policy behaviour are a small, low-probability part of the base model's output distribution, installed by post-training. SFT on a narrow task dataset moves the distribution toward that dataset. Refusals are rare in it, so they are the first thing gradient descent overwrites: catastrophic forgetting of refusal, and it happens even when every training example is clean. Two corollaries: a regression is usually a narrowness problem, not a toxicity problem; and if your training prompts carry system messages that grant capabilities, the model generalises the grant, not just the task.

Bisect by layer, one variable at a time

LayerHold fixedDetection signal
Base modeldata, template, filtersswap base under the same adapter recipe
Training database, templaterefusal rate on held-out red-team set
Prompt templatemodel, datasame prompt, old vs new template
Input/output filtermodel, promptraw model output vs post-filter output
Tool/permission configmodel, prompttool-call trace on a refusal-expected prompt

The filter row matters most in practice: a filter change can look like a model regression and vice versa. Compare raw model output against post-filter output before blaming the weights.

Worked check (illustrative numbers)

Canary at 5% of 40,000 requests/day = 2,000 requests. Safety-flag rate 0.6% on the canary vs 0.05% on the pinned baseline: 12 flagged vs 1, a 12x lift.

Python
# Python 3.11
from collections import Counter

def flag_rate(rows):
    c = Counter(r["label"] for r in rows)
    return c["flagged"] / len(rows)

base   = [{"label": "flagged"}] * 1  + [{"label": "ok"}] * 1999
canary = [{"label": "flagged"}] * 12 + [{"label": "ok"}] * 1988
print(f"{flag_rate(base):.4f} {flag_rate(canary):.4f}")

Trace: base holds 1 flagged and 1999 ok, len 2000, so 1/2000 = 0.0005 and it prints 0.0005. canary holds 12 flagged and 1988 ok, len 2000, so 12/2000 = 0.006 and it prints 0.0060. Output: 0.0005 0.0060.

That is the gate: a canary is promotable only if the flag rate's confidence interval overlaps the baseline's. One flagged request in 2,000 is noise; twelve is a signal.

Failure modes

  • Rolling back the model but leaving the new prompt template or tool config live. The regression persists, you bisect the wrong layer, and you burn a day. Detect by versioning template and tool config alongside the model ID and diffing all three at rollback.
  • Preserving evidence by dumping raw prompts and completions into a shared bucket. That is a second incident. Detect with a pre-incident check that the evidence path is access-controlled and PII-scrubbed.
  • Re-running the full eval suite instead of the failing slice. The signal dilutes and you cannot tell whether the fix worked. Detect by requiring the fix to move the specific slice metric, not the aggregate.

Trade-offs

Full rollback vs. keeping the canary at reduced traffic: rollback loses the live data you need to diagnose; keeping traffic collects more harm. The deciding criterion is whether the harm is user-visible and irreversible. If a customer already received a policy-violating output, roll back fully and diagnose offline.

Retrain from base vs. continue training the regressed adapter: retraining is a clean slate but costs a full run; continuing is cheaper but risks baking the regression in. Default to retraining from base unless the regression is isolated to a data slice you can excise.

Add a moderation filter in front vs. fix the model: the filter is fast, reversible, and buys time, but it masks the regression and adds a network hop. Use it as a stopgap with an expiry date, not as the fix.

Re-promotion

Re-canary at 1% with the safety suite as a hard gate, then 5%, then 25%, holding each step for a full traffic cycle. Add the failing prompts to the red-team suite so the next fine-tune is gated on them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Roll out a fine-tuned model safely.

Answer

What I'd say first

Assume the fine-tune is a LoRA/SFT variant of a pinned base model serving a task with a checkable output (structured extraction, classification, or a tool call) and that you have both a deterministic scorer and a human/user outcome signal. My answer: never flip a switch. Ramp exposure in stages, gate each stage on predeclared metrics against a pinned baseline, and make routing sticky and cache-safe.

Why each stage exists

Shadow first: mirror production requests to the fine-tune, log the output, never return it. This is the only stage that costs users nothing, and it catches the cheap failures (schema violations, malformed JSON, latency and token-cost drift) before anyone sees them. Its limit is real: users never see the output, so shadow cannot tell you whether quality improved. It only tells you the model isn't broken.

Canary next, at 1% of traffic, sticky per user or session. Stickiness matters because a user who sees the baseline on turn one and the fine-tune on turn two is measuring nothing and having a bad experience. Include the model version in the cache key, or cached baseline responses get served to the canary cohort and dilute every metric you're watching.

Compare by slice, not in aggregate. A fine-tune usually wins on the majority slice and loses on a minority one: long-context inputs, a non-English locale, a rare intent. Aggregate numbers hide that.

Trade-offs

Interleaved A/B (same user, alternating versions) gives tighter per-user variance and is the right call for stateless, single-turn tasks. It breaks anything stateful, so it's wrong for multi-turn agents. Shadow-only is safe but blind to outcome. Canary is the default. And staged rollout is the wrong shape when the fine-tune is a safety fix: leaving 99% of traffic on a baseline that emits a harmful behavior is worse than the risk of shipping fast, so you gate on safety alerts and roll in minutes, not days.

Failure modes and how you see them

  • Cache mixing: cache hit rate split by model version; assert the version is in the key.
  • Broken stickiness: fraction of sessions that saw more than one model version. Should be zero.
  • Length/cost drift: p95 completion tokens per request; fine-tunes often get chattier.
  • Delayed effects: a new input category arrives days later. Keep a rolling 7-day slice check after full rollout.
  • No rollback: if you can't revoke the adapter and route back in under a minute, you're not safe.

Worked gate

Illustrative: 50 req/s, canary at 1% = 0.5 req/s. To detect a success drop from 95% to 93% (2pp) at 80% power, α=0.05, you need about 2,200 requests per arm: roughly 73 minutes of canary. So a 10-minute canary tells you nothing about a 2pp regression; it only catches gross breakage.

stageexposuregate to advance
shadow100% mirrored, 0% servedschema pass ≥ baseline, p95 latency ≤ +10%, cost/req ≤ +5%
canary1% stickyno safety alerts, success within 2pp, ≥2,200 samples
ramp5% → 25%same gates, slice-level
full100%7-day rolling slice check

That's the shape. The numbers are illustrative; the gates are what you predeclare before you see the data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Turn production feedback into governed training data.

Answer

What I'd say first (60–120s)

Assume a production LLM feature with a thumbs up/down widget and a free-text correction box, and a team that wants to fine-tune or run DPO on what comes back. The trap is treating a rating as a label of correctness. It isn't: it's a label of this user, in this context, seeing this rendering. So the job splits in two: build a governed record, then decide which parts of it are allowed to become a training signal.

fieldwhy it has to be there
consent basis + timestampdecides whether the row is trainable at all
model, prompt template, tool, RAG index versionwithout it you can't attribute a regression to a change
rendered output + UI positionposition bias is a property of the widget, not the answer
task, context, user cohortlets you slice failures instead of averaging them
outcome (rating, correction, abandonment)nonresponse is data too

Redact PII at write time (Presidio or equivalent), not at read time, and give the raw text a shorter retention than the derived label.

Worked arithmetic (illustrative numbers)

1,000,000 sessions/month, 0.4% produce a rating → 4,000 ratings. 92% thumbs-up → 320 negatives. A safety slice needs roughly 2,000 adjudicated negatives to move a 1% failure rate with any confidence. So you cannot train on the stream; you deliberately sample: all corrections, all safety-flag hits, a random 1% of thumbs-up, and a matched sample of nonresponders.

Why exposure logging is the whole game

Feedback loop: the model only gets rated on what it emits. Train on that and you reinforce the current policy: the output distribution narrows. Detection: track rating distribution and output diversity against a frozen eval set; if thumbs-up rate rises while held-out accuracy is flat, you're fitting the widget, not the task.

Position bias: in a pairwise UI the first option wins more often than chance regardless of quality. Collect both orders and average, or use interleaving. Detection: swap-order agreement below ~0.7 means the preference label is mostly position.

Separating preference from correctness

Style preference ("I like this tone") is cheap and abundant; correctness and safety are expensive and rare. Keep them in separate tables with separate consent and separate eval sets. Preference data can go to DPO; correctness data needs adjudication. High-risk cases (safety, medical, legal, financial) go to two independent expert raters; keep items where Cohen's kappa ≥ 0.6 and route disagreements to a third adjudicator rather than averaging.

Trade-offs and when not to train

Adjudication runs roughly $5–20 per item at expert rates; 2,000 items is $10k–40k per slice. Usually cheaper than shipping a regression, but it means you adjudicate slices, not streams. Don't train on production feedback when consent coverage is below your threshold, when the slice is safety-critical and unadjudicated, or when the failure is a retrieval or tool bug: fix the pipeline, not the weights.

Holdouts and leakage

Random splits leak: the same user, session or near-duplicate prompt lands on both sides. Dedup with MinHash/LSH at ~0.9 Jaccard, split by time and cohort, hold out the last two weeks. Detection: if random-split eval beats temporal-split eval by more than a couple of points, you have leakage.

Then measure causal effect: add the targeted slice, retrain, and check the specific failure slice moved, not just the aggregate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Review and validate an LLM fine-tuning release end to end.

Answer

Before I validate anything I want three things pinned: the exact base checkpoint hash, the training config, and the acceptance bar. If this is a LoRA adapter on a frozen base (say r=16, alpha=32 on q_proj and v_proj, trained with trl's SFTTrainer) the validation surface is much smaller than a full fine-tune, because the base weights are byte-identical and I can diff the adapter. If the base changed, every cached eval is invalid and I re-run the whole suite. That's the first decision point, and it decides how much of the rest of this I have to do.

Data first, because it's the cheapest place to be wrong. I run MinHash LSH dedup at 0.8 Jaccard with 128 permutations, and a train/eval leakage check on 13-grams: any eval item sharing a near-duplicate with train gets dropped, not reworded. Contamination is worth 10-30 points of fake improvement on QA benchmarks, and it is invisible in the loss curve.

Python
from datasketch import MinHash, MinHashLSH

def leak(train, evalset, threshold=0.8):
    lsh = MinHashLSH(threshold=threshold, num_perm=128)
    for i, t in enumerate(train):
        m = MinHash(num_perm=128)
        for g in ngrams(t, 13):
            m.update(g.encode())
        lsh.insert(i, m)
    hits = []
    for j, e in enumerate(evalset):
        m = MinHash(num_perm=128)
        for g in ngrams(e, 13):
            m.update(g.encode())
        if lsh.query(m):
            hits.append(j)
    return hits

That returns the indices of eval items that share a near-duplicate with the training set. I fail the build on a non-empty result.

Then training diagnostics. Loss is a smoke test, not a gate. The gate is held-out task accuracy against a pinned baseline: same prompts, same decoding params, same seed set. I have seen loss fall while instruction-following got worse, because the model learned the template's formatting and not the task.

Artefacts: adapter in safetensors, SHA-256 recorded, signed with cosign, and the base model hash asserted at load time. The failure mode here is silent and nasty: serving an adapter trained against one base revision on another produces fluent garbage with no error. Assert the hash, fail the load.

Behaviour eval, and this is where the table matters:

gatethresholdwhy
task accuracy (holdout, n=1000)≥ baseline − 1 ptregression guard
no-answer / abstention≥ 95%hallucination on unanswerable
schema-valid tool calls≥ 99%downstream parser breaks
jailbreak set (300 prompts)≤ baseline + 2%safety regression
canary extraction0 of 100memorisation
p50 output tokenswithin 1.5× baselineverbosity hacking

The numbers are illustrative; the point is each gate has a threshold and a reason, and I set them before the run.

Canary arithmetic: to detect a 2-point drop from an 80% baseline at 95% confidence and 80% power I need about 6,300 requests per arm. 2 × (1.96+0.84)² × 0.16 / 0.02². So a 5% canary on 10k daily requests takes roughly a day and a half, not an hour. If I can't afford that, I say so and accept a wider interval rather than pretending the canary proved something.

Trade-offs: deterministic checks are cheap and reproducible but blind to tone and refusal quality; human judgment catches those but costs a few dollars per rated item and drifts between raters, so I blind the arm labels and use three raters with a majority. LoRA is cheap to train and cheap to roll back; a full fine-tune buys more capacity but makes rollback a full redeploy.

Failure modes I watch: reward hacking shows up as token-length p50 moving from 180 to 420 while win rate looks flat. Track length, not just preference. Backdoor or poison shows up only on trigger-conditioned evals, so I include a small trigger set. Serving an unmerged adapter adds per-token overhead; measure p99 before and after rather than assuming.

What I'd own as a gap: I can't fully rule out memorisation of training data outside the canary set, and I'd say that in the release note rather than claim privacy was validated.

Curated: · Written: · Reviewed:

Difficulty: Hard