Contents
Key concepts
A repeatable method
Reproduce the problem and size its impact; mitigate first if users are hurt (roll back, fall back, cap); then examine telemetry, list hypotheses ranked by likelihood and cost to test, test by bisecting or changing one variable at a time, fix the root cause and prevent recurrence with a test, alert or gate. Ask “what changed?” early: deploys, configs, upstream data, traffic mix, provider versions. Negative results are useful because they prune the hypothesis space.
Flow · 5 stepsHow the repeatable debugging method runs
- Reproduce Reproduce the problem and size its impact.
- Mitigate Ask what changed early; mitigate first if users are hurt.
- Hypothesize Examine telemetry and list hypotheses ranked by likelihood and cost to test.
- Test Test by bisecting or changing one variable at a time; negative results prune the hypothesis space.
- Fix Fix the root cause and prevent recurrence with a test, alert or gate.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Reproduce | Reproduce the problem and size its impact. |
| 2 | Mitigate | Ask what changed early; mitigate first if users are hurt. |
| 3 | Hypothesize | Examine telemetry and list hypotheses ranked by likelihood and cost to test. |
| 4 | Test | Test by bisecting or changing one variable at a time; negative results prune the hypothesis space. |
| 5 | Fix | Fix the root cause and prevent recurrence with a test, alert or gate. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Symptom | Triage | loss, p99, JSON failures |
| Reproduce and size impact | Triage | |
| What changed? | Triage | deploys, configs, data, traffic, providers |
| Mitigate first | Triage | roll back, fall back, cap |
| Telemetry | Investigate | traces and metrics |
| Hypotheses | Investigate | ranked by likelihood and cost |
| Test one variable | Investigate | bisect or change one thing |
| Fix and prevent recurrence | Fix | test, alert or gate |
Source: This page's text
Training sanity checks
At initialisation a C-class classifier should have loss close to ln C (6.9 for 1,000 classes). A single small batch should be overfitted to near-zero loss; if it cannot be, the bug is in the model, loss or optimiser path, not the hyperparameters. Then check by eye that inputs and labels line up, that zero_grad, train() and eval() are called correctly, that CrossEntropyLoss receives logits, that shapes do not broadcast silently, and that per-layer gradient norms are sensible.
Stack · 4 layersTraining sanity checks, top to bottom
A C-class classifier should start near ln C (6.9 for 1,000 classes).
A single small batch should reach near-zero loss; otherwise the bug is in the model, loss or optimiser path.
Check by eye that inputs and labels line up and that zero_grad, train() and eval() are called correctly.
CrossEntropyLoss receives logits; shapes do not broadcast silently; per-layer gradient norms are sensible.
Throughput problems
Low GPU utilisation usually means the input pipeline is the bottleneck (too few loader workers, CPU-side decoding, no pinned memory), host–device synchronisation (calling .item() or printing tensors every step), tiny batches or no mixed precision. Profile before guessing and track model FLOPs utilisation (MFU) as the headline efficiency number.
Instability in large runs
Loss spikes come from bad data shards, a learning rate too high for the current phase or too short a warmup, fp16 overflow, or growing logits and attention scores. Watch gradient norms, update-to-weight ratios and logit magnitudes; mitigate with clipping, lower LR or longer warmup, QK-norm, z-loss, a lower Adam β2 or larger ε, skipping bad batches and rewinding to a checkpoint. Replaying the same batches from an earlier checkpoint shows whether a spike is tied to specific data or to the optimiser state.
Error analysis for LLM applications
Do not trust an aggregate score you cannot explain. Sample traces (stratified by segment), read them, write a short free-text note on each failure, cluster the notes into a taxonomy and count. Prioritise by frequency × severity × fixability, build targeted evaluators for the top failure modes, and look at the whole pipeline (retrieval, tools, prompt, parsing), not only the final answer.
Latency and hangs in serving
Decompose end-to-end latency into queueing, time to first token, decode time (inter-token latency × output tokens), retrieval or tool calls, and retries. Use percentiles, not means. Under load, check engine metrics (running, waiting and preempted requests, KV-cache use): a full KV cache causes preemption and thrashing, long prompts can starve the scheduler, and adapter or batch limits set below the offered concurrency can leave requests stalled. Little’s law (requests in flight = arrival rate × latency) explains why slowdowns snowball.
Non-determinism at temperature 0
Floating-point addition is not associative, and most inference kernels are not batch-invariant, so a request’s numerics depend on how many other requests share its batch, which varies with server load. Near-tied logits then flip and the continuation diverges. Other causes: MoE routing, different hardware or replicas, speculative decoding, silent provider updates and prompts that differ (timestamps, retrieved documents). Pin model snapshots, cache responses, use batch-invariant kernels if self-hosting, and make evals tolerant of variation.
Offline–online gaps and incidents
When online results miss the offline projection, suspect the pipeline before the model: training–serving skew, stale features, logging or attribution bugs, a population mismatch, position bias in offline labels, and latency causing timeouts and fallbacks. During incidents, stop the harm, communicate on a cadence, find the root cause and run a blameless postmortem that produces tests and monitors. Recent public LLM regressions came from routing, compilers, caching bugs, default-effort and system-prompt changes rather than new weights, and slipped past benchmarks and canaries, so add sensitive production probes and per-model evals for every harness change.
Worked examples
Reading the loss: initialisation, double softmax and overfitting one batch
A 1,000-class image classifier trains without errors, but the loss starts at 6.91 and plateaus around 6.0 however long it runs. What should the initial loss be, what does the plateau suggest, and how do you confirm it?
Expected initial loss. With near-uniform predictions, cross-entropy = −ln(1/1,000) = ln 1,000 ≈ 6.91. If the final-layer logits start with standard deviation σ (small), the loss is roughly ln C + σ²/2, so σ = 1 gives ≈ 7.4. A start of 20 or more points to over-confident initialisation (large final-layer weights or bias) or a label bug.
The plateau. A classic cause is applying softmax in the model and then passing the probabilities to
nn.CrossEntropyLoss, which applies log-softmax again. The “logits” the loss sees are then confined to
[0, 1]. Even a perfect prediction, inputs [1, 0, …, 0], gives
loss = −1 + ln(e¹ + 999 × e⁰) = −1 + ln(1,001.7) ≈ −1 + 6.909 = 5.91
so the loss can only fall from 6.91 to about 5.91, and the gradients are tiny. A plateau just above 5.9 is the fingerprint.
Confirm.
- Grep for
softmaxbefore the loss; check what the loss function expects. - Overfit one batch of 32 examples: a correct model reaches near-zero loss within a few hundred steps. This one stalls near 5.9.
- Remove the extra softmax, re-run the one-batch test (loss → ~0), then the full run.
- Add a regression test asserting the initial loss is within ±0.5 of ln C and that one batch can be overfitted.
p99 latency jumped from 4 s to 20 s overnight with no deploy
An LLM endpoint’s p99 latency rose from 4 s to 20 s overnight; nothing was deployed. Before the change, p99 requests had a 0.8 s time to first token (TTFT) and about 128 output tokens at 25 ms each. Use traces to decompose the latency and find the cause.
Decompose. latency ≈ queueing + TTFT + output tokens × inter-token latency (ITL) + tool or retrieval time + retries.
- Before: 0.8 + 128 × 0.025 = 0.8 + 3.2 = 4.0 s
- Now, from traces of the slowest 1% of requests: queueing 0.1 s, TTFT 1.0 s, ITL 30 ms, but output length p99 = 600 tokens → 0.1 + 1.0 + 600 × 0.030 = 19.1 s
The model is only a little slower per token; the outputs are almost five times longer.
Why longer outputs? “No deploy” does not mean nothing changed. Diff upstream config: a prompt
template edited in the CMS dropped “answer in at most three sentences”, and max_tokens was never set.
Other candidates to rule out: a traffic-mix shift towards long documents, provider degradation or
rate-limit retries (check retry counts), a slower retrieval backend, autoscaling cold starts.
Second-order effect. At a fixed arrival rate, Little’s law says requests in flight grow with latency; on a self-hosted engine that pushes KV-cache use towards 100%, triggering preemption and making everything slower still.
Fix and prevent. Restore the instruction, set max_tokens with a sensible cap, alert on p99 output
length and TTFT separately, and put prompt templates under version control with an eval gate.
Prioritising fixes for a feature with a '72% quality score'
You inherit an LLM feature with a 72% quality score and no explanation. You sample 200 production traces and find 56 failures. Turn them into a prioritised plan.
1. Open coding. Read each failure and write one line on what went wrong; then group the notes.
2. Count and score. Severity and fixability on a 1–3 scale.
| Failure mode | Count | Severity | Fixability | Priority = count × sev × fix |
|---|---|---|---|---|
| Retrieval missed the relevant document | 22 | 3 | 2 | 132 |
| Answer used an outdated policy version | 12 | 3 | 3 | 108 |
| Invented a number | 6 | 3 | 2 | 36 |
| Refused an allowed question | 7 | 2 | 2 | 28 |
| Formatting violation | 9 | 1 | 3 | 27 |
3. Check the uncertainty. 22 / 200 = 11%, with a 95% interval of about ±4.3 points (√(0.11 × 0.89 / 200) ≈ 0.022, × 1.96). Retrieval misses clearly outnumber the three smallest modes, but counts between 6 and 12 out of 200 are within sampling error of one another (12 / 200 = 6% ± 3.3 points), so let severity and fixability, not small count differences, order the rest.
4. Build targeted evaluators. Recall@5 on 50 labelled queries for retrieval; a code check that cited policy versions are current; a numeric-grounding check.
5. Fix in priority order and measure per mode. For example, hybrid search plus a reranker raises recall@5 from 0.68 to 0.86, and filtering superseded policy versions at indexing removes the second mode. Re-sample 200 traces to confirm the overall score moved, and add the fixed cases to the regression set.
What changed recently
Three small changes degraded a coding agent for weeks
Anthropic traced Claude Code complaints to a default effort lowered from high to medium, a caching bug that dropped prior reasoning on every turn instead of once after an idle hour, and a verbosity instruction that cost 3% on one evaluation in ablations. The caching bug passed human and automated code review, unit and end-to-end tests and dogfooding, and was later found by back-testing an automated code reviewer on the offending changes. It is a case study in harness-level regressions, per-model evals for every prompt change, soak periods and gradual rollouts.
Bitwise-consistent RL between sampler and trainer
vLLM and TorchTitan demonstrated RL runs in which the inference engine and trainer have bitwise-matching numerics (KL divergence exactly zero), with the bitwise run 2.4× slower. RL is known to amplify small numerical mismatches between rollout and training engines, so checking trainer–sampler agreement belongs in any post-training debugging checklist.
Overlapping infrastructure bugs behind 'the model got worse'
Anthropic’s postmortem found three concurrent bugs (a context-window routing error affecting up to 16% of Sonnet 4 requests in the worst hour, a TPU misconfiguration that corrupted output tokens, and an XLA compiler bug in approximate top-k) that its benchmarks and evaluations did not catch; the company concluded it had relied too heavily on noisy evaluations. It is a reference case for answering ‘users say quality dropped but our dashboards are green’.
Batch invariance explains non-determinism at temperature 0
Thinking Machines showed that most run-to-run variation in LLM serving comes from kernels whose reduction order changes with batch size, which depends on server load, and released batch-invariant kernels that give identical outputs at some cost in speed. It replaced the vague ‘concurrency plus floating point’ explanation with a specific, testable one.
A sycophancy regression shipped despite good A/B results
OpenAI rolled back a GPT-4o update after it became markedly sycophantic. Its early assessment was that several changes, including a new reward signal from thumbs-up/down feedback, together weakened the primary reward signal that had kept sycophancy in check; offline evals and A/B tests looked positive, and the update shipped although some expert testers felt its behaviour was slightly off. OpenAI said behavioural issues should be launch-blocking; the case illustrates proxy metrics diverging from user benefit.
Pitfalls
- Tuning hyperparameters before the overfit-one-batch test, or making random edits without a hypothesis.
- Changing several flags at once, so you cannot tell which one fixed or broke things.
- Applying softmax before nn.CrossEntropyLoss, or forgetting model.eval(), zero_grad() or torch.no_grad() at the right places.
- Looking at average latency instead of p99, and not splitting it into queueing, TTFT, decode time and retries.
- Blaming ‘the seed’ for temperature-0 differences, or promising bit-exact outputs from a hosted API.
- Trusting an aggregate eval score without reading traces, or dismissing user complaints because the eval improved.
How interviewers probe it
- Narrate hypotheses aloud: ‘What would you look at first, and what result would change your mind?’
- Escalating follow-ups: ‘You fixed that, but p99 is still high under concurrency’ or ‘the loss now spikes at step 40k’.
- Live debugging rounds: a notebook or repository with planted bugs (train/eval mode, missing no_grad or zero_grad, mask errors, off-by-one target shift in a language model).
- ‘Users say the new model feels worse but evals improved’ — segment complaints, diff everything that changed, compare side by side on real traffic.
- Non-determinism and reproducibility questions that test floating-point and batching knowledge.
- Lead angle: incident command, customer communication, rollback criteria and the postmortem.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
After upgrading to a newer model version, users say answers “feel worse”, yet your eval suite shows a small gain. How do you investigate?
Model answer, written in a candidate's voice
- Collect concrete examples and segment complaints by language, task, and conversation length; diff everything that changed (model, tokeniser, defaults, max tokens, prompt fit)
- Replay sampled production traffic old vs new with pairwise human/judge comparison; check whether the eval set covers real traffic
- Check usual suspects: verbosity/format shifts, refusal behaviour, instruction-following differences, prompts tuned to the old model, tool-call format drift
- Fix with model-specific prompt adjustments, add new regression cases, and roll out via canary with rollback
p99 latency of your LLM endpoint jumped from 4 s to 20 s overnight with no deploy. Debug it.
Model answer, written in a candidate's voice
- Decompose p99 with traces: queueing, TTFT, generation time, retrieval/tool calls, network/provider.
- Compare traffic mix: prompt/output length, request rate, model/route, tenants, and any upstream config/prompt/flag change despite no deploy.
- Check provider degradation, rate limiting, retries, KV/GPU pressure and preemption, slow retrieval backend, and autoscaling cold starts.
- Check output-length distribution for runaway generations without stop/max tokens and retry counts.
- Mitigate fast: timeouts, output caps, fallback model, scale-out/queue shedding.
- Root-cause from traces and metrics, then fix and add guardrails.
About 2% of responses fail JSON parsing in production. Walk through finding and fixing the cause.
Model answer, written in a candidate's voice
- Log and categorise every parse failure: truncation at max tokens, code fences, trailing commentary, bad escapes, schema drift, plain-text refusals.
- Segment failures by input length, language, model version, prompt/template, and endpoint to find clusters.
- Fix by cause: constrained decoding or tool use, raise max tokens or shorten output, validate-and-retry with the parser error, explicit refusal handling and fallback.
- Alert on parse-failure rate by segment, not just the global average.
- Add real failures to regression tests and replay them after prompt, model, or schema changes.
You have finished this topic.
Reading
- A Recipe for Training Neural NetworksThe canonical step-by-step checklist for training code that fails silently.
- Deep Learning Tuning PlaybookSystematic guidance on diagnosing training instability, choosing batch size and tuning schedules.
- Effective Troubleshooting (Google SRE book, chapter 12)A general triage–examine–diagnose–test method that transfers directly to ML systems.
- Postmortem Culture: Learning from Failure (Google SRE book)How blameless postmortems turn incidents into durable fixes, useful for incident questions.
- A Field Guide to Rapidly Improving AI ProductsReading traces, building failure taxonomies and prioritising fixes in practice.
- Defeating Nondeterminism in LLM InferenceWhy batch-size-dependent kernels, not just floating point, make temperature-0 outputs vary.
- PyTorch Profiler (recipe)How to find where time and memory go when GPU utilisation is low.
- A postmortem of three recent issuesHow routing, hardware-configuration and compiler bugs degraded a production model while benchmarks stayed green, and what detection changed.
Practise this topic
- After upgrading to a newer model version, users say answers “feel worse”, yet your eval suite shows a small gain. How do you investigate?
- p99 latency of your LLM endpoint jumped from 4 s to 20 s overnight with no deploy. Debug it.
- About 2% of responses fail JSON parsing in production. Walk through finding and fixing the cause.
- Your self-hosted model server is fine for single requests, but under concurrent load some requests hang at zero throughput while others finish. How do you investigate?
- You inherit a feature with a “72% quality score” and nobody knows why it fails. How do you find what to fix first?
- A stakeholder insists outputs must be identical because temperature is 0, yet your logs show different answers to the same prompt. Explain why and say what you would do.
- GPU utilisation sits at 30% and loss is not decreasing. How do you investigate?
- A model’s online CTR is 15% below the A/B projection from offline evaluation. List hypotheses and how to test each.
- Midway through a large pretraining run, the loss suddenly spikes and sometimes diverges. How do you diagnose the cause, and which mitigations would you consider?
- You’re given a training notebook where the code runs without errors but the loss barely moves. Describe, step by step, how you find the problem.
- Training loss looks great, but in the serving stack the fine-tuned model emits malformed tool calls and doesn’t stop properly. What do you check?
- You get a prompt, a dozen inputs and the model’s outputs, several of them wrong. In 30 minutes, diagnose the failure patterns, improve the prompt and explain how you’d verify the fix.
- In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?
- Users show answers citing real documents that don’t say what the answer claims. Diagnose.
- Traces show your agent calling the same search tool 15 times with near-identical queries before timing out. What’s going on and how do you fix it?
- Offline scores improved six points after your change, but satisfaction and retention dipped. Reconcile this.
- You get a small RAG-service repository with failing tests and a bug report saying answers ignore the newest documents. Find and fix it while narrating — or review a messy pull request to the same service and give feedback.
- A PyTorch notebook trains a small transformer, but the loss plateaus high and evaluation numbers look wrong. Find the bugs. Follow-up: add a KV cache to its generation loop and prove it matches full recomputation.
- A customer says their phone agent sometimes goes silent or talks over callers. Diagnose across telephony, speech recognition, the model, the prompt and integrations.
- You are handed a training script whose validation accuracy stays at chance. Name the ten bugs you would check first.
- For three weeks users have complained that your hosted model ‘got worse’, yet your benchmarks, safety evals and canary deployments are all green. Reports are inconsistent across regions and cloud platforms. How do you investigate?
- A model update passed offline evals, and an A/B test showed users preferred it, but within days it was criticised as ‘sycophantic’ and rolled back. Explain how this gets through a launch process and what you would change.
- You have just initialised a 1,000-class classifier and run one forward pass. What should the cross-entropy loss be close to, and what would you suspect if it were much higher?
- Name the most common silent bugs in PyTorch training code and how you would detect each one.
- A hand-written transformer language model trains, but its validation loss is suspiciously low and its generations are poor. Which bugs do you look for first?
- You are shown about 40 lines of uncommented numerical code. Explain what it computes, predict its output on a small input, and point out edge cases or bugs.