Debugging and Testing ML Systems Questions
Finding, diagnosing, and fixing problems in ML code, data, and models, and building tests that catch these problems before they reach users. Covers common ML pitfalls (data leakage, shape mismatches, silent training bugs, mis-specified loss or metrics), root-cause analysis of model regressions and production incidents (accuracy drops, calibration drift, intermittent or hard-to-reproduce failures), distributed-training-specific failures (multi-GPU divergence, intermittent OOM, precision-related instability), and the diagnostic tooling that supports it (reproducibility artifacts, structured logging, instrumentation). Also covers testing ML systems directly: unit tests for data and feature pipelines, validation checks for datasets and features, test oracles and acceptance criteria for probabilistic or non-deterministic model outputs, and integration and regression tests that catch model or pipeline regressions before deployment. Emphasizes the engineering rigor that keeps ML systems correct and maintainable.
After converting a model to a lower-precision or quantized format (fp16 or int8) for faster inference, some inputs now produce NaN, out-of-range, or systematically different predictions than the original model. Provide a step-by-step debugging plan to localize where in the quantization pipeline the issue is coming from. Propose a safe, staged rollout plan (with tests) for migrating production traffic to the quantized model.
Sample Answer
Direct answer
A quantized model producing NaN, out-of-range, or systematically different predictions on some inputs has two genuinely different failure modes that need to be told apart before you can fix either: hard numerical overflow (a value exceeds the reduced format's representable range and becomes infinity or NaN), and soft accumulation error (values stay in range but rounding at lower precision compounds across many operations into a meaningfully different result, with no crash at all). The debugging plan is to localize which of the two you have, layer by layer, before deciding on a fix, because the fixes are different: overflow needs range management, accumulation error needs either more precision in the reduction step or a numerically-aware requantization (requantization being the step that re-derives the scale and zero-point after an operation so its result lands back inside the target integer range instead of clipping, which is defined properly in step 5).
Structured elaboration
Step 1: reproduce deterministically. Fix all seeds, disable non-deterministic kernel selection, and run the exact same inputs through the full-precision (fp32, 32-bit IEEE 754 floating point) model and the quantized model on the same hardware. Confirm the anomaly reproduces reliably before doing anything else; a genuinely intermittent quantization bug (rather than one that reproduces on specific inputs) usually points at a race in how batches are dispatched to quantized kernels rather than at the numerics themselves.
Step 2: capture per-layer activations for both versions. Add hooks (or run in a debugger/interactive session) that record each layer's output for both the reference and quantized model on the same input, so you can compute a per-layer divergence metric (absolute or relative error, and specifically flag any NaN or infinite values) rather than only comparing final outputs. This turns "predictions are wrong somewhere" into "layer 14's output diverges but layers 1 through 13 agree," which is a dramatically smaller search space.
Step 3: binary-search to the first divergent layer. Once you know a layer where activations diverge, check whether an earlier layer already diverges; the first layer where the quantized and reference paths disagree beyond a small tolerance is where the root cause lives, not necessarily the layer where a NaN first becomes visible (a NaN can propagate silently through several downstream layers before a difference becomes obvious in the final output).
Step 4: at that layer, distinguish overflow from accumulation error. Check whether any intermediate value at that layer, in the target lower-precision format, exceeds the format's representable range: half-precision floating point (fp16) has a maximum finite value of 65504; 8-bit integer (int8) quantization has a fixed integer range (typically -128 to 127) determined by the calibration scale and zero-point chosen for that layer. If a pre-activation sum (the weighted sum a layer computes for a unit before its activation function is applied) legitimately exceeds that range, you have overflow, and the fix is either range-aware handling (clipping, or keeping that specific operation in higher precision) or fixing the calibration that chose too aggressive a scale. If values stay in range but outputs still differ meaningfully, you have accumulation error, and the fix is either accumulating in higher precision internally (a common pattern: multiply in low precision, sum in fp32) or recalibrating.
Step 5: for int8 specifically, audit the calibration. Int8 quantization depends on a calibration step that chooses a scale and zero-point per tensor (or per channel) from a representative calibration dataset (see Case C in the worked example for what those two quantities are, with numbers). A calibration dataset that does not cover the actual production input range (for example, calibrated on typical-magnitude inputs but production occasionally sees much larger values) will systematically clip or misrepresent the tail, producing exactly the "some inputs" pattern described in the question: most inputs are fine, specific ones are not. Check whether the failing inputs are outliers relative to the calibration set's observed range for the relevant tensors.
Step 6: check fused-kernel and operator-order differences. Quantized inference commonly uses fused kernels (a single optimized operation replacing what was several separate operations in the reference implementation) that can compute results in a different order, and floating-point addition and multiplication are not strictly associative, so reordering operations changes rounding behavior even at the same nominal precision. If per-layer activations diverge even where you would expect exact agreement, toggling kernel fusion on and off (most inference runtimes expose this as an option) isolates whether the fused kernel's specific implementation is the source.
Worked example
The snippet below demonstrates both failure modes concretely and separately, which is exactly the distinction the debugging plan above depends on: Case A shows a value that genuinely exceeds fp16's range producing infinity and then NaN, and Case B shows accumulation error in a large reduction producing a meaningfully wrong result with no NaN anywhere.
"""
Localizes where in a quantization pipeline a fp16 (IEEE 754 half-precision)
conversion produces NaN/Inf vs where it just adds rounding error, by
comparing a fp32 reference computation against the same computation done
in fp16 at two different scales.
Pinned: numpy Generator seed=3, vector length 4096 for the accumulation
case, dtype comparisons are exact (no sampling variance in the conclusion).
Run with: python3 fp16_localize.py
"""
import numpy as np
rng = np.random.default_rng(seed=3)
# --- Case A: a single activation value near the fp16 dynamic-range edge ---
# fp16 max finite value is 65504. A pre-activation sum that would be
# unremarkable in fp32 silently becomes +inf, then NaN after a subsequent
# subtraction, once cast to fp16.
value_fp32 = np.float32(70000.0)
value_fp16 = value_fp32.astype(np.float16)
print("=== Case A: single value near fp16 max range (65504) ===")
print(f"fp32 value: {value_fp32}")
print(f"cast to fp16: {value_fp16} (is_inf={np.isinf(value_fp16)})")
print(f"fp16 value minus itself: {value_fp16 - value_fp16} "
f"(NaN only appears once inf meets a conflicting op, e.g. inf - inf)")
inf_minus_inf = value_fp16 - np.float16(np.inf)
print(f"fp16 inf - inf: {inf_minus_inf} (is_nan={np.isnan(inf_minus_inf)})")
# --- Case B: accumulation error in a large dot product (no overflow, just
# rounding) so predictions are "systematically different" without any NaN ---
n = 4096
a = rng.normal(loc=0.0, scale=1.0, size=n).astype(np.float32)
b = rng.normal(loc=0.0, scale=1.0, size=n).astype(np.float32)
dot_fp32 = np.float64(a.astype(np.float64) @ b.astype(np.float64)) # reference
dot_fp16_accum = np.float16(0.0)
for x, y in zip(a.astype(np.float16), b.astype(np.float16)):
dot_fp16_accum = np.float16(dot_fp16_accum + x * y) # accumulate IN fp16
print("\n=== Case B: dot product, fp32 reference vs fp16-accumulated ===")
print(f"reference (fp64) dot product: {dot_fp32:.6f}")
print(f"fp16-accumulated dot product: {float(dot_fp16_accum):.6f}")
rel_err = abs(float(dot_fp16_accum) - dot_fp32) / abs(dot_fp32)
print(f"relative error from fp16 accumulation: {rel_err:.2%}")
Actual output from running this script (stdout and stderr together, in order):
/private/tmp/mlrepro_s41/fp16_localize.py:20: RuntimeWarning: overflow encountered in cast
value_fp16 = value_fp32.astype(np.float16)
/private/tmp/mlrepro_s41/fp16_localize.py:24: RuntimeWarning: invalid value encountered in scalar subtract
print(f"fp16 value minus itself: {value_fp16 - value_fp16} "
/private/tmp/mlrepro_s41/fp16_localize.py:26: RuntimeWarning: invalid value encountered in scalar subtract
inf_minus_inf = value_fp16 - np.float16(np.inf)
=== Case A: single value near fp16 max range (65504) ===
fp32 value: 70000.0
cast to fp16: inf (is_inf=True)
fp16 value minus itself: nan (NaN only appears once inf meets a conflicting op, e.g. inf - inf)
fp16 inf - inf: nan (is_nan=True)
=== Case B: dot product, fp32 reference vs fp16-accumulated ===
reference (fp64) dot product: 12.331923
fp16-accumulated dot product: 11.882812
relative error from fp16 accumulation: 3.64%
Case A confirms the overflow mechanism precisely: 70000 exceeds fp16's 65504 maximum, casting silently produces infinity (numpy raises a RuntimeWarning rather than an exception, which is itself worth noting, since a pipeline that does not surface warnings as errors will not notice this happening), and the NaN only appears once that infinity meets a conflicting operation (inf - inf), which is why a NaN can appear to originate several operations downstream of where the actual overflow happened, exactly why step 3's per-layer binary search matters more than looking only at where the NaN first prints. Case B confirms the second, quieter failure mode: with no overflow anywhere (all 4096 pairwise products are small, well within fp16's range), accumulating the running sum in fp16 instead of a higher-precision accumulator still produces a 3.64 percent relative error against the fp64 reference, purely from rounding compounding across many additions. That is a concrete, honest demonstration of why "systematically different predictions... on some inputs" does not require a single dramatic bug: it can be pure accumulation drift, and the fix (accumulate in fp32 even if the individual multiplies are in fp16, a standard mixed-precision pattern) is different from the fix for Case A.
Case C: int8 calibration, where "some inputs only" actually comes from. The two cases above are fp16, but the int8 story is the one that explains why most inputs are fine and specific ones are not, so it deserves its own arithmetic. Int8 stores a real value as a small integer through real = scale * (q - zero_point): the scale is how much real-number range one integer step covers, and the zero_point is the integer that represents real zero. Calibration picks both from the range of activations it observed.
"""
Case C: int8 calibration, showing what `scale` and `zero_point` are and how a
calibration range chosen from typical inputs clips an outlier input.
int8 stores a real value as a small integer via real = scale * (q - zero_point).
Pinned: no randomness. Calibration range [0.0, 6.0], target integer range
[-128, 127]. Run with: python3 int8_calibration.py
"""
lo, hi = 0.0, 6.0 # activation range observed on the calibration set
qmin, qmax = -128, 127 # int8
scale = (hi - lo) / (qmax - qmin)
zero_point = round(qmin - lo / scale)
print(f"calibration range [{lo}, {hi}] -> scale = {scale:.6f}, zero_point = {zero_point}")
print(f"(one integer step covers {scale:.6f} of real range; "
f"integer {zero_point} represents real 0.0)")
print(f"\n{'real input':>10} {'q (raw)':>9} {'q (clipped)':>12} {'dequantized':>12} {'error':>9}")
for real in (2.5, 6.0, 9.2):
q_raw = round(real / scale) + zero_point
q = min(max(q_raw, qmin), qmax)
deq = scale * (q - zero_point)
print(f"{real:>10.2f} {q_raw:>9d} {q:>12d} {deq:>12.4f} {deq - real:>+9.4f}")
Actual output from running this script:
calibration range [0.0, 6.0] -> scale = 0.023529, zero_point = -128
(one integer step covers 0.023529 of real range; integer -128 represents real 0.0)
real input q (raw) q (clipped) dequantized error
2.50 -22 -22 2.4941 -0.0059
6.00 127 127 6.0000 +0.0000
9.20 263 127 6.0000 -3.2000
This is the "some inputs" pattern made mechanical. A typical activation of 2.5 round-trips with an error of 0.006, about a quarter of one integer step, which is exactly the quantization noise you signed up for. An activation of 9.2, which simply never appeared in the calibration set, wants integer 263, and 263 does not exist in int8, so it is clamped to 127 and comes back as 6.0000: an error of 3.2, more than five hundred times the typical one, silently, on that input only. "Too aggressive a scale" means precisely this, a scale derived from a range narrower than production actually produces, and it is why step 5's check is whether the FAILING inputs are outliers relative to the calibration set's observed range rather than whether the calibration set was large.
Safe, staged rollout plan, with tests. Once localized and fixed:
- Regression test suite: a fixed golden set of inputs, including deliberately extreme-magnitude ones sized to probe the target format's range boundary, with per-layer and final-output tolerances that the quantized model must meet against the fp32 reference. Run on every change to the quantization pipeline, not just before the first launch.
- Shadow mode: run the quantized model alongside the current production model on live traffic without affecting responses, logging the divergence rate and the specific magnitude of disagreement, to see the real-world NaN and large-divergence rate before any user is exposed.
- Automatic instability detection with fallback: at serving time, detect NaN, infinite, or out-of-expected-range outputs on individual requests and automatically fall back to the fp32 model for that request, rather than serving a broken prediction or a hard error, while alerting so the rate is visible operationally.
- Staged canary: ramp traffic in small, monitored steps (for example 1 percent, then 5 percent, then progressively higher), with an explicit stop condition on the fallback-trigger rate and on downstream business metrics, and a fast, pre-built path back to serving fp32 for all traffic if any stage regresses.
Trade-offs and pitfalls
The most common wrong turn is treating every quantization anomaly as an overflow problem and reaching straight for clipping. Clipping fixes Case A's failure mode but does nothing for Case B's; applied to an accumulation-error case, clipping can even make things quietly worse by truncating legitimate large-but-in-range values while leaving the actual rounding-compounding mechanism untouched.
A second pitfall is validating only against aggregate metrics (overall accuracy, average error) rather than per-example and per-layer checks. Case A's failure mode is rare and input-specific by nature (only inputs that push a particular pre-activation near the format's range boundary trigger it), so it can hide inside an aggregate metric that looks acceptable while still causing a real, occasionally-severe production failure for the specific users who hit it.
A third pitfall in the rollout plan specifically: an automatic fallback-to-fp32 mechanism is a safety net, not a fix, and a rollout that ships with fallback but never drives the underlying fallback-trigger rate to near zero is quietly running two models in production indefinitely, which doubles serving cost for exactly the traffic where you most need the latency or memory benefit that motivated quantization in the first place.
You observe a gap between training and validation performance for a model and need to determine whether it is caused by ordinary overfitting or by data leakage. Design an experiment and validation plan that distinguishes the two, what results would point to leakage versus genuine overfitting, and how your conclusion would change if training loss were near zero but validation accuracy were also unstable (not just low) across runs.
Sample Answer
Direct answer. Overfitting and leakage can produce the exact same symptom (a gap between training and validation performance), but they need genuinely different fixes, so the investigation has to isolate WHICH one is happening before touching regularization or feature engineering. The discriminator is not the direction the gap moves, it is how much the ABSOLUTE validation number moves when you change how the split is built, and you have to read the training score and the validation score separately to see it.
Experiment and validation plan.
- Rebuild the evaluation as a strict time-based split, with the held-out slice's features recomputed as of prediction time, retrain, and record training score and validation score SEPARATELY, before and after. Overfitting is a property of model capacity against data volume, so it is essentially insensitive to how the split was drawn: both numbers land where they landed before. Leakage is a property of how the evaluation slice was constructed relative to the label, so it is extremely sensitive: the training score barely moves (the leak is still in the training rows) while the validation score falls off a cliff, which means the gap GROWS rather than shrinks. Note the trap this rules out: under the original random split a leaky model often shows a suspiciously SMALL gap, because the leak inflates validation just as much as it inflates training.
- Remove suspect features one at a time and retrain, inside the corrected evaluation from step 1. If validation performance actually IMPROVES when a specific feature is removed (not just training performance getting worse, which is expected when you remove any useful feature), that's a strong leakage signal. The mechanism, which is worth being able to state rather than memorize: in the corrected setup the leaky feature still carries the label in the training rows but carries nothing in the held-out slice, because a point-in-time read of it returns a value computed before the outcome existed. The model therefore spends real capacity learning to lean on a signal that is simply not present at evaluation time, and its predictions are actively worse than those of a model that never saw the feature at all. Dropping it does not just stop helping, it stops hurting.
- Check feature availability timestamps for every feature the model with high suspicion currently uses, documenting exactly when in the real pipeline each one becomes known, relative to the label's outcome time.
How steps 1 and 2 fit together rather than contradicting each other. They assume different evaluation setups, and that is the point of doing them in order. Step 1 operates on the ORIGINAL random split, where the leak is present in both slices, which is exactly why validation looks so good there and why the gap is small. Step 2 operates INSIDE the corrected setup step 1 produces, where the leak is present in training but absent from the held-out slice. Same feature, two different evaluations, two different tells. Run step 1 first to build the honest evaluation, then run step 2 inside it.
What each result implies, with numbers you can reproduce. The setup: 4,000 rows, 10 standard-normal features with the label drawn from a logistic model of them, plus one extra feature built from an aggregate that is only complete once the outcome has settled (so for settled rows it carries the label plus noise, and a point-in-time read of an unsettled row returns noise alone). Model is a gradient-boosted classifier, 80/20 split, seed pinned.
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(0) # pinned, so these numbers are reproducible
n, n_tr = 4000, 3200
X = rng.normal(size=(n, 10)) # 10 honest standard-normal features
beta = rng.normal(size=10)
y = (rng.random(n) < 1 / (1 + np.exp(-(X @ beta)))).astype(int) # label from a logistic model
# The leaky feature: an aggregate that is only complete once the outcome has settled.
# Settled rows carry the label plus noise; a point-in-time read of an unsettled row is noise alone.
settled = 2.0 * (2 * y - 1) + rng.normal(0, 0.5, n)
as_of = rng.normal(0, 0.5, n)
X_leak = np.column_stack([X, settled]) # leak as the training pipeline sees it
X_pointin = np.column_stack([X, as_of]) # leak as production would actually read it
def aucs(Xtr, ytr, Xte, yte, high_capacity=False):
kw = dict(random_state=0)
if high_capacity:
kw.update(max_iter=500, max_leaf_nodes=63, min_samples_leaf=1,
l2_regularization=0.0, early_stopping=False, learning_rate=0.3)
m = HistGradientBoostingClassifier(**kw).fit(Xtr, ytr)
return (roc_auc_score(ytr, m.predict_proba(Xtr)[:, 1]),
roc_auc_score(yte, m.predict_proba(Xte)[:, 1]))
perm = rng.permutation(n)
r_tr, r_te = perm[:n_tr], perm[n_tr:] # random 80/20
t_tr, t_te = np.arange(n_tr), np.arange(n_tr, n) # chronological 80/20
def show(label, a, b):
print(" %-48s train %.3f val %.3f gap %.3f" % (label, a, b, a - b))
print("LEAKAGE")
show("random split, leak present in both slices",
*aucs(X_leak[r_tr], y[r_tr], X_leak[r_te], y[r_te]))
show("time split, held-out slice rebuilt point-in-time",
*aucs(X_leak[t_tr], y[t_tr], X_pointin[t_te], y[t_te]))
show("same time split, leaky feature DROPPED",
*aucs(X[t_tr], y[t_tr], X[t_te], y[t_te]))
print("\nOVERFITTING (no leaky feature, high-capacity model)")
show("random split", *aucs(X[r_tr], y[r_tr], X[r_te], y[r_te], high_capacity=True))
show("chronological split", *aucs(X[t_tr], y[t_tr], X[t_te], y[t_te], high_capacity=True))
LEAKAGE
random split, leak present in both slices train 1.000 val 1.000 gap 0.000
time split, held-out slice rebuilt point-in-time train 1.000 val 0.569 gap 0.431
same time split, leaky feature DROPPED train 0.999 val 0.872 gap 0.127
OVERFITTING (no leaky feature, high-capacity model)
random split train 1.000 val 0.884 gap 0.116
chronological split train 1.000 val 0.865 gap 0.135
Read the leakage block left to right: validation moved 0.431 (1.000 down to 0.569) purely from changing how the split was built, while training moved 0.000. Note also the first row, where the gap is 0.000: under the original random split this leaky model looks flawless and shows no gap at all, which is the trap. Read the overfitting block: validation moved 0.019 across the same change (0.884 down to 0.865), which is inside the sampling noise of an 800-row holdout, and the gap barely budged (0.116 to 0.135). That contrast, four tenths of an AUC point versus two hundredths, is the whole diagnosis. Then read the third leakage row: dropping the leaky feature RAISED validation from 0.569 to 0.872, which is step 2's tell in its clearest form and something no honest feature ever does.
So: if the validation score collapses when the split is rebuilt correctly, and a specific feature's removal then raises it, that's leakage, and the fix is removing or correctly re-deriving that feature, not more regularization. If both scores are roughly where they were under either split methodology, and removing individual features only ever makes validation worse (never better), that's genuine overfitting, and the fix is standard: more regularization, more data, or a smaller model.
If training loss is near zero AND validation accuracy is ALSO unstable across runs (not just low). This is a distinct signal from a persistently low-but-stable validation number, instability run-to-run suggests either high variance in a small validation set (the validation set itself is too small to give a stable estimate, an easy thing to check by just re-splitting validation data multiple times and looking at the spread of the resulting accuracy) or genuine sensitivity to initialization/data order interacting with a model that has memorized rather than generalized (near-zero training loss with essentially no learned structure to fall back on when the exact memorized examples aren't being tested). Both point toward the same practical next step, get a larger or more stable validation set before drawing any further conclusion, since an unstable metric can't reliably distinguish between competing hypotheses in the first place. It also invalidates the step-1 comparison above until it is fixed: a 0.02 move in validation means nothing if re-splitting alone moves it by 0.05.
A large model-training run fails with a GPU out-of-memory error when you increase the batch size. List the practical mitigation strategies available to you, and describe the trade-off each one makes (extra compute time, implementation complexity, or a change in effective batch-size semantics).
Sample Answer
Direct answer. When a larger batch size pushes training past available GPU memory, the available fixes trade off differently between compute time, implementation complexity, and whether they change the actual math of what "batch size" means, so the right choice depends on which of those you can afford to spend.
The mitigation menu.
- Gradient accumulation: run several smaller micro-batches, summing their gradients before a single optimizer step, simulating a larger effective batch size without ever holding the full batch in memory at once. Trade-off: nearly free in implementation complexity and mathematically equivalent to true large-batch training for most loss functions, but costs extra wall-clock time since you're doing more forward/backward passes for the same effective batch. The exception is the batch-size-semantics one, and it is worth knowing by name: any layer that computes statistics over the batch, batch normalization above all, sees only the micro-batch, not the full effective batch, so a network containing batch normalization is NOT equivalent under accumulation and needs synchronized batch normalization across micro-batches or a normalization layer that does not depend on the batch at all.
- Mixed precision: store activations (the intermediate outputs each layer produces during the forward pass, which are kept in memory because the backward pass needs them, and which usually dominate memory during training) and weights in fp16 or bf16 (bf16 being a 16-bit format with fp32's exponent range but fewer mantissa bits, so it trades precision for far less overflow risk) instead of fp32, roughly halving memory footprint. Trade-off: often a "free" win in both memory and speed on modern hardware, but introduces its own numerical-stability considerations (dynamic loss scaling, meaning the loss is multiplied by a large factor before backward and the gradients divided by it afterwards, so that small gradient values do not vanish to zero in fp16, with the factor adjusted automatically when it causes an overflow; plus watching for NaNs from fp16 underflow and overflow), so it is not entirely free of engineering cost.
- Model or pipeline parallelism: split the model itself (not just the data) across multiple devices, so no single device needs to hold the full model or full activations. Trade-off: the most memory-scalable option but the most complex to implement correctly, and introduces communication overhead between devices.
- Activation checkpointing: don't store intermediate activations from the forward pass, recompute them during the backward pass instead. Trade-off: significantly reduces memory (often the single biggest lever for very deep networks) at the direct cost of extra compute, since the forward pass effectively runs twice for the checkpointed segments.
- Reducing sequence length: for sequence models, truncating or bucketing to a shorter maximum length directly reduces the memory footprint of attention and activations. Trade-off: free in implementation cost, but changes what the model actually sees, potentially losing information for the fraction of examples whose true length exceeds the new cap.
- Reducing the batch size itself, with the learning rate re-tuned to match: the option that is easy to forget precisely because it looks like giving up. Trade-off: free in both compute and implementation complexity, and the one option on this list whose cost lands squarely on effective batch-size semantics. A smaller batch means noisier gradient estimates and a different effective noise scale, so the learning rate and schedule usually need re-tuning (often downward), and the run's convergence path, and sometimes its final quality, genuinely changes rather than merely being reorganized.
- Parameter sharding (splitting optimizer state and/or parameters themselves across devices, as in ZeRO-style approaches, ZeRO being a family of techniques that partitions optimizer state, gradients and eventually parameters across devices instead of replicating them on every one): substantially reduces per-device memory for the optimizer state specifically (which is often larger than the model weights themselves for adaptive optimizers, that is, optimizers such as Adam that keep one or two running statistics per parameter and therefore carry several times the model's own size in state). Trade-off: adds communication overhead to gather sharded parameters when needed, and is more complex to set up than gradient accumulation or mixed precision.
How to choose. The two to know cold are mixed precision and gradient accumulation: both are close to free in engineering cost and, batch-normalization layers aside, neither changes what the model learns. Activation checkpointing is the third to reach for, since it is a pure compute-for-memory trade with no semantic change at all. Only then reach for model or pipeline parallelism, sharding, reducing sequence length, or simply shrinking the batch, since each of those trades away something the first three do not: implementation complexity and communication overhead for parallelism and sharding, information in the input for a shorter sequence, and effective batch-size semantics for a smaller batch with a re-tuned learning rate.
Design a chaos-engineering (failure-injection) plan to test an ML system's resilience: injecting feature corruption, missing upstream data, a spike in a particular label, and delayed inputs. Describe the specific tests you would run, how you would capture and interpret the system's response, the safety controls you would put in place so the experiment can't cause real user harm, and what you would do after a test reveals a real weakness.
Sample Answer
Direct answer
A chaos-engineering plan for an ML system deliberately injects a specific, named failure, feature corruption, missing upstream data, a sudden spike in one label's frequency, or delayed inputs, into a small, capped slice of real or shadow traffic, then measures how the system actually degrades against a hypothesis stated before the experiment runs. The two disciplines that separate this from just breaking things in production are a hard blast-radius cap with an automatic abort if the observed error rate crosses a threshold, and a mandatory follow-up step: every experiment that reveals a real weakness produces a tracked fix, not just a finding written down and forgotten.
Structured elaboration
The four failure injections and what each one tests.
- Feature corruption: replace a feature's value with an out-of-distribution or garbage value (large-magnitude noise, a wrong-typed value) for a fraction of requests, simulating an upstream bug that silently mangles a field rather than failing loudly. This tests whether the model (or the pipeline wrapping it) has any input-sanity check at all, or whether it will confidently score garbage.
- Missing upstream data: force a feature to fall back to its default (null, zero, or a mean-imputation value), simulating an upstream service outage or a schema field that stopped being populated. This specifically tests the fallback path, which in a healthy system runs rarely and is therefore the least-exercised code path in the whole pipeline.
- A spike in one label's frequency: flood the system with requests that skew heavily toward one predicted class or one input segment, simulating a real-world event that shifts the traffic mix suddenly (a fraud ring probing one product category, a viral post driving one query type). This tests capacity and downstream-system assumptions that were tuned for an average traffic mix, a fraud-review queue sized for a steady 2% flag rate will behave very differently if flags briefly spike to 40%.
- Delayed inputs: hold back a feature's arrival past its normal latency budget, simulating a slow upstream dependency. This tests the timeout and fallback logic specifically, does the system wait indefinitely (a latency failure), serve a stale cached value (a correctness failure), or fail the request outright (an availability failure), and which of those three is actually the intended, chosen behavior versus an accident of how the code happens to be written.
Capturing and interpreting the system's response. Before running anything, write down the falsifiable hypothesis the experiment tests ("if feature X is corrupted for 10% of traffic, end-to-end accuracy on that slice stays within Y of baseline, because the input-validation layer should catch and reject it"), then measure the actual metric on the actual injected slice against a same-window, non-injected control group, not against a historical average that could be confounded by unrelated factors. Interpretation is comparing the observed result to the hypothesis, not just reporting a number: a result that matches the hypothesis exactly is informative in a different way than one that badly misses it, both are useful, but they call for different follow-ups.
Safety controls so the experiment cannot cause real user harm. Three layers, from least to most severe:
- A hard blast-radius cap: the experiment is only allowed to touch a small, pre-approved percentage of traffic (single digits for a first run of any new experiment type), enforced in code before the experiment starts, not as a policy someone is trusted to follow.
- An automatic abort trigger: monitor the injected slice's error rate (or a business metric like conversion) in real time during the experiment, and kill it automatically the moment it crosses a pre-set threshold, rather than waiting for a human to notice.
- A kill switch and rollback path tested in advance: the mechanism that stops the experiment must itself be tested before the experiment runs, an abort trigger that has never been exercised is not a safety control, it is an unverified assumption.
After a test reveals a real weakness. Treat the finding the same way a production incident would be treated: file it as a tracked issue with an owner and a severity, not just a note in a doc; prioritize the fix by the same criteria as any other production risk (how likely is this failure to occur outside of an experiment, and how bad is it if it does); and, once fixed, re-run the exact same experiment to confirm the fix actually closes the gap, rather than assuming the fix worked because it looks correct in code review.
Worked example
Training a small classifier and measuring the actual impact of the first two injection types on a genuinely held-out test set. The setup is shipped in full rather than assumed, because the accuracy drops below only mean something if you can see how strongly the label depends on the feature being corrupted (here feature 0 carries most of the signal, which is why injecting into it moves the numbers at all):
import torch
import torch.nn as nn
def make_dataset(n, seed):
gen = torch.Generator().manual_seed(seed)
X = torch.randn(n, 4, generator=gen)
logits = 2.5 * X[:, 0] + 0.6 * X[:, 1] - 0.4 * X[:, 2]
y = (logits > 0).long()
return X, y
def accuracy(model, X, y):
with torch.no_grad():
return (model(X).argmax(dim=1) == y).float().mean().item()
torch.manual_seed(0)
X_train, y_train = make_dataset(2000, seed=1)
model = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 2))
opt = torch.optim.Adam(model.parameters(), lr=0.02)
for _ in range(400):
opt.zero_grad()
nn.functional.cross_entropy(model(X_train), y_train).backward()
opt.step()
model.eval()
g = torch.Generator().manual_seed(3) # separate seeded generator for injection sampling
X_test, y_test = make_dataset(300, seed=2)
baseline_acc = accuracy(model, X_test, y_test)
print(f"baseline accuracy (no injection): {baseline_acc:.3f}")
def corrupt(frac): # Experiment A: garbage value
X = X_test.clone()
idx = torch.randperm(len(X_test), generator=g)[:int(frac * len(X_test))]
X[idx, 0] = torch.randn(len(idx), generator=g) * 10
return X
def drop_to_default(frac): # Experiment B: fallback to the default 0.0
X = X_test.clone()
idx = torch.randperm(len(X_test), generator=g)[:int(frac * len(X_test))]
X[idx, 0] = 0.0
return X
for title, inject in [("Experiment A: feature corruption (feature 0 replaced with noise)", corrupt),
("Experiment B: missing upstream data (feature 0 falls back to 0.0)", drop_to_default)]:
print()
print(title)
for frac in [0.1, 0.5, 1.0]:
acc = accuracy(model, inject(frac), y_test)
print(f" injected fraction={frac:.0%}: accuracy={acc:.3f} (drop={baseline_acc - acc:.3f})")
Actual output:
baseline accuracy (no injection): 0.993
Experiment A: feature corruption (feature 0 replaced with noise)
injected fraction=10%: accuracy=0.943 (drop=0.050)
injected fraction=50%: accuracy=0.753 (drop=0.240)
injected fraction=100%: accuracy=0.547 (drop=0.447)
Experiment B: missing upstream data (feature 0 falls back to 0.0)
injected fraction=10%: accuracy=0.953 (drop=0.040)
At every injected fraction, garbage-value corruption hurts accuracy more than a sane zero-fallback (0.050 against 0.040 at 10%, 0.240 against 0.207 at 50%, and 0.447 against 0.423 at 100%), a concrete, falsifiable version of the intuition that a defined default is safer than an undefined one, and exactly the kind of result a chaos experiment is supposed to produce: a number to argue from instead of an assumption. Note how small the gap is at 100% injection, 0.447 against 0.423. Both injections destroy the feature's signal; the defined default is better, but only slightly, which is a more useful finding than the intuition alone, since it says the real mitigation is not a better default value but detecting that the feature is broken at all.
The blast-radius safety control, exercised on all three of its outcomes: a request that violates the cap, one that respects it and completes, and one that respects the cap but trips the abort threshold mid-experiment. The third case matters most and is the one usually left untested, because an abort trigger that has never fired is an assumption rather than a control:
def run_capped_experiment(inject_fn, frac, max_blast_radius=0.05, abort_error_rate=0.5):
if frac > max_blast_radius:
return {"status": "REJECTED_BEFORE_START",
"reason": f"requested {frac:.0%} exceeds blast-radius cap {max_blast_radius:.0%}"}
error_rate = 1 - accuracy(model, inject_fn(frac), y_test)
if error_rate > abort_error_rate:
return {"status": "ABORTED_MID_EXPERIMENT", "error_rate": round(error_rate, 3)}
return {"status": "COMPLETED", "error_rate": round(error_rate, 3)}
print("requesting a 50% blast radius (should be rejected before it ever runs):")
print(run_capped_experiment(corrupt, 0.50))
print("requesting a 3% blast radius (within cap, should run):")
print(run_capped_experiment(corrupt, 0.03))
print("a 4% experiment whose injected slice errors past the abort threshold:")
print(run_capped_experiment(corrupt, 0.04, abort_error_rate=0.01))
Output:
injected fraction=50%: accuracy=0.787 (drop=0.207)
injected fraction=100%: accuracy=0.570 (drop=0.423)
requesting a 50% blast radius (should be rejected before it ever runs):
{'status': 'REJECTED_BEFORE_START', 'reason': 'requested 50% exceeds blast-radius cap 5%'}
requesting a 3% blast radius (within cap, should run):
{'status': 'COMPLETED', 'error_rate': 0.023}
a 4% experiment whose injected slice errors past the abort threshold:
{'status': 'ABORTED_MID_EXPERIMENT', 'error_rate': 0.02}
Trade-offs and pitfalls
- A capped blast radius trades statistical power for safety, and that is the correct trade. A 3% slice gives a noisier estimate of the true impact than 50% would, but the entire point of the cap is that you are not yet confident enough in the outcome to accept the larger slice's risk; run small first, and only widen the blast radius once the small run's result matches the hypothesis.
- Injecting on shadow or synthetic traffic first, and only later on a capped slice of real traffic, catches a different class of bug than either alone. Shadow traffic is safe but might not reproduce real timing and concurrency conditions; a real capped slice is realistic but risks a real (small) user impact, so a mature program runs both, in that order, rather than picking one.
- The 'spike in one label' injection is the easiest of the four to get wrong by testing the model instead of the system. The model itself usually handles a skewed prediction mix without complaint; the actual fragile point is almost always a downstream system (a review queue, a rate limiter, a notification budget) that was capacity-planned around the normal mix, so point this experiment at the whole pipeline, not just at the model's own accuracy.
- A finding that reveals no weakness is not a wasted experiment. It is tempting to only report and act on experiments that find a problem; a clean result that matches the stated hypothesis is evidence the system's fallback behavior works as designed, which is exactly what justifies the next experiment's larger blast radius.
A model performs well in aggregate but is consistently wrong for a specific, business-relevant slice of the data (for example a particular subpopulation or a narrow input domain). Describe the set of analyses you would run to confirm and localize the issue. Explain how you would distinguish whether the failure is due to sparse data for that slice, a genuinely biased input distribution, or a relationship that only holds within that slice, and what you would try before deciding to build a separate model. Describe briefly how you would present your findings and a remediation plan to a non-technical audience in a short meeting.
Sample Answer
Direct answer
A model that looks good in aggregate but is consistently wrong on one business-relevant slice needs two separate questions answered, not one: first, is the gap real (not just a small, noisy sample), and second, once confirmed, is it caused by that slice being underrepresented in training data, by that slice's inputs being genuinely different from what the model was trained to handle, or by the feature-label relationship itself working differently within that slice than it does overall. Each cause has a different fix, and jumping to "build a separate model" without distinguishing them usually means solving the wrong problem at the highest possible cost.
Structured elaboration
Step 1: confirm the gap is real. Compute the slice's metric with a confidence interval (a normal approximation or bootstrap resampling both work for this) rather than a single point estimate, and check whether that interval excludes the overall population's metric. A slice that looks 5 points worse on a small sample can easily be noise; a slice whose confidence interval clearly excludes the aggregate metric is a real, actionable finding, not just an artifact of looking at enough slices that one was bound to look bad by chance.
Step 2: localize with three specific comparisons, one per candidate cause.
- Sparse data: compare the slice's representation in the TRAINING set (not just the evaluation set) against its representation in the overall population the model serves. A slice that is rare in training relative to how often it appears in production is a strong, direct signal that the model simply has not seen enough of it to learn it well.
- Biased input distribution: compare the slice's feature distributions against the OVERALL training distribution using a two-sample test such as Kolmogorov-Smirnov (KS) for continuous features or chi-square for categorical ones. If the slice's typical feature values sit in a region the training data barely covers at all (not just underrepresented, but genuinely out of the range the model learned from), that points at a coverage gap in what the model was trained to generalize over, which is a related but distinct problem from simple sparsity: more of the SAME kind of data would help sparsity; here you may need different data entirely.
- A relationship that only holds within the slice: fit a lightweight, slice-only model (same features, but trained and evaluated only on that slice's data) and compare its performance to the shared global model's performance on the same slice. If the slice-only model does meaningfully better with roughly the SAME amount of data the global model already had access to for that slice, the shared model's parameters are being pulled toward the majority pattern and the slice needs its own representation, not just more data of the same shape.
Step 3: before deciding to build a separate model, try things that address each cause without the cost of a second model.
- For sparse data: reweight or oversample the slice during training so its effective training influence better matches its business importance, or add slice-specific synthetic or supplementary data if it exists.
- For a distribution gap: expand the training distribution to genuinely cover the slice's typical input range (targeted data collection is often the only real fix here; reweighting existing data cannot manufacture coverage that never existed).
- For a slice-specific relationship: add an explicit slice indicator as a feature so the model has the CAPACITY to learn a different function for that slice without a fully separate model, or move to a lightweight multi-task or hierarchical structure (a shared trunk with a small slice-specific adjustment layer) that gives the slice-specific pattern room to be learned while still sharing what generalizes across slices.
- Recalibration: if the underlying ranking or relative ordering of predictions is fine but the slice's predicted probabilities are systematically miscalibrated, a slice-specific calibration layer (recalibrating output probabilities per slice) can close much of the gap far more cheaply than any retraining.
Only escalate to a genuinely separate model if the slice is large and important enough to justify the ongoing maintenance cost of two training and monitoring pipelines, AND the cheaper interventions above still leave a meaningful, confirmed gap after being tried.
One vocabulary note before the next paragraph, because the word "bias" is about to change meaning. Above, "biased input distribution" meant the slice's feature values are skewed relative to training. In the sentence that follows, "bias" is the bias-variance sense: bias means the model systematically misses in one direction because it is too constrained to fit this region (underfitting), and variance means how much the fitted function swings depending on which training sample it happened to see. The part that is easy to get backwards is that both terms are REGIONAL here, not global. In those terms this pattern is low bias on the majority of the population, which the model fits well, and high bias on this one segment, which it systematically underfits; and in the sparse-data case specifically, high variance on that same segment as well, because a region the training set barely covers is a region where the fitted function depends heavily on which few examples happened to be drawn. It is not the model's aggregate error that carries the variance, it is the thinly-covered slice. That decomposition is consistent with the sparse-data and distribution-gap causes above (both are forms of underfitting a specific region) rather than with random measurement noise, which the confidence-interval check in step 1 already ruled out.
Worked example
Suppose the overall accuracy is 92 percent and the slice's measured accuracy is 81 percent on n=800 examples. Using a normal-approximation confidence interval for the slice's proportion:
SE=8000.81×0.19≈0.0139 95% CI=0.81±1.96×0.0139≈[0.783, 0.837]The overall 92 percent accuracy falls well outside this interval, so the gap is confirmed real, not sampling noise, even at a moderate slice size. Moving to localization: checking training-set composition shows this slice made up only about 2 percent of training examples despite being roughly 9 percent of served production traffic, a clear sparse-data signal on its own. The distribution comparison is a separate check and has to be run on its own rather than inferred from that ratio: comparing this slice's feature distributions against the overall TRAINING distribution with a two-sample KS test returns a statistic of about 0.04 on the largest-moving feature, which sits inside the noise band for these sample sizes (800 slice rows against a 200,000-row training sample gives roughly 0.03 typically and 0.05 at the 95th percentile even when both samples come from the same distribution), and a support check confirms no region of the slice's feature values falls outside the range the training data actually covers. So the training data does reach into this slice's input range, it simply does not contain much of it: a coverage gap is ruled out, on evidence, and underrepresentation is what remains. The two are genuinely different things and a slice can be both, which is exactly why the composition ratio cannot stand in for this check: rare in training is sparsity, outside the range training covers is a coverage gap, and only the second one means more of the same data will not help. A slice-only model trained on just that slice's existing data, meanwhile, performs only marginally better than the global model on the same held-out slice examples, which argues against "the relationship is fundamentally different here" as the dominant cause, since a model with no access to any OTHER slice's data still could not do much better with the same amount of slice-specific data. Together, this localizes the primary cause to sparse representation in training rather than a distribution gap or a genuinely different relationship, and the recommended fix is oversampling or upweighting this slice in the training objective, with a slice-specific calibration check afterward, before considering anything more structurally invasive.
Presenting findings and a remediation plan to a non-technical audience in a short meeting. Lead with the business framing, not the statistics: state plainly which segment is affected and its business weight (for example, "the model underperforms specifically for this customer segment, which is about 9 percent of volume but underrepresented in what the model was trained on"), then the plain-language cause ("the model simply has not seen enough examples from this group to learn its pattern well, not that the group behaves unpredictably"), then the concrete plan and timeline ("we are rebalancing the training data to fix this, expect a validated fix within two weeks, and are adding a short-term safeguard in the meantime"), and finally name the interim mitigation if the gap is costly enough to need one before the retrain ships (a manual review threshold or a fallback rule specifically for this slice). Keep it to those four beats and be ready to go one level deeper only if asked; a 15-minute readout is not the place to walk through the confidence-interval arithmetic.
Trade-offs and pitfalls
The most common wrong turn is treating "the slice looks worse" as sufficient evidence on its own, without the confidence-interval check in step 1. Slicing a large evaluation set into enough narrow segments virtually guarantees a few will look meaningfully worse by chance alone, and chasing every such segment as a real finding both wastes engineering effort and erodes stakeholder trust when a "fixed" segment's metric was never actually broken.
A second pitfall is defaulting to oversampling as the fix for every slice gap, regardless of which cause step 2 actually points to. Oversampling helps sparse data; it does little for a genuine distribution gap (there is nothing new to oversample) and can actively hurt a slice-specific-relationship case, since simply showing the model more of the same existing slice examples does not give it the capacity to learn a genuinely different function for that slice.
A third pitfall in the communication step: presenting a slice-performance gap using aggregate metrics or statistical language a non-technical stakeholder has to take on faith, rather than a concrete business-impact framing. "Accuracy on that segment dropped by 11 points" lands very differently from "roughly 1 in 5 customers in this segment are being misclassified, affecting about 9 percent of volume," even though they can describe the same underlying number; the latter is what actually enables a non-technical audience to weigh in on prioritization and interim mitigation decisions.
Unlock Full Question Bank
Get access to all Debugging and Testing ML Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.