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.
List and briefly define at least five common failure modes in production ML/AI systems (for example poor data quality, label errors, data leakage, training instability such as vanishing or exploding gradients, numerical-precision problems, overfitting/underfitting, and hardware failures). For each, give a concrete one-to-two-sentence production example, one quick detection signal you would monitor to catch it early, and how you would feed the lesson back into your development process to prevent recurrence.
Sample Answer
Direct answer. Production ML systems fail in a recurring, learnable set of ways, and knowing the list ahead of time turns "something is wrong" into "check these first" instead of an open-ended search.
Seven of them, each with what it actually is, what it looks like in production, the cheapest signal that catches it early, and the process change that stops it coming back.
| Failure mode and what it is | Concrete production example | Early detection signal | Prevention step that closes the loop |
|---|---|---|---|
| Poor data quality. Inputs that violate the assumptions the model was trained under: wrong types, out-of-range values, malformed or missing fields arriving from upstream. | A source system starts sending malformed timestamps after an upstream schema change. Every record from that source silently loses its time-based features, and the model keeps scoring them without complaint. | Automated schema and type validation failing on ingest, counted per source rather than swallowed. | Make the ingest validation a blocking gate instead of a warning, and add a contract test for the exact field and type that broke so the next producer-side schema change fails in the producer's own build. |
| Label errors. The training targets themselves are wrong, so the model faithfully learns a mislabeled version of the task and its ceiling is set by the label quality, not the architecture. | A labeling vendor systematically mislabels a rare class because the guideline for it is ambiguous. Accuracy on that class collapses while overall accuracy barely moves, so nobody notices for a quarter. | Per-class loss distribution (the loss broken out by true class instead of averaged into one number) shows unusually high loss concentrated on one class. | A gold-standard re-labeling audit of a fixed sample from every vendor batch, wired into the vendor acceptance gate so a batch below an agreement threshold is rejected before anything trains on it, plus a rewrite of the guideline for the class that failed. |
| Data leakage. A feature carries information that would not exist at prediction time, so offline evaluation measures something the model can never actually do in production. | A churn feature is derived from a support-ticket table that is only written after a cancellation is processed, so the model "predicts" churn from a record that exists only once churn has already happened. Offline metrics look superb and production performance is ordinary. | Offline metrics implausibly high; one feature's importance dominates all others. | Require a point-in-time availability field on every new feature (when is this value knowable, relative to the prediction timestamp) and check it in review, and build training features with a point-in-time-correct join rather than a plain one. |
| Training instability (vanishing / exploding gradients). The gradient is the correction signal that flows backwards through the network's layers. Exploding means it grows multiplicatively layer over layer until the weights jump to unusable values; vanishing means it shrinks toward zero, so the early layers stop learning at all. | A deeper variant of a working model trains fine at 12 layers but diverges within a few hundred steps at 48 layers. Depth was the only change. | Per-layer gradient-norm logging (the size of the gradient at each layer, recorded every N steps) shows norms trending toward zero or toward infinity instead of holding a stable range. | Turn per-layer gradient-norm logging on by default for every new architecture, and add a training-time assertion that fails the run at the first step a layer's norm leaves a configured range, so instability shows up in the first minutes rather than three weeks in. |
| Numerical-precision problems. Arithmetic that is correct on paper returns a wrong or undefined answer at the precision the hardware actually uses. Mixed-precision training does most of its arithmetic in 16-bit floating point (fp16) for speed and memory, and fp16 cannot represent very small magnitudes, so a small intermediate value can underflow, meaning it rounds all the way to zero. | Mixed-precision training silently underflows a small denominator to zero, the division then returns NaN (not-a-number, what a floating-point operation produces when it has no valid answer) or Inf (infinity), and that NaN propagates through every later computation until the loss itself is NaN. | NaN or Inf appears in loss or activations, often only under fp16 and not when the same run is repeated in 32-bit. | A NaN and Inf assertion on loss and activations that fails the run at the first bad step instead of at the end, plus loss scaling (or pinning the specific fragile operation to 32-bit) as the standing default for new mixed-precision runs. |
| Overfitting / underfitting. Overfitting is memorizing the training set instead of learning the pattern, so performance is far better on training data than on anything new. Underfitting is the mirror image: a model too simple to capture the pattern, mediocre on both. | A model with far more parameters than training examples memorizes the training set. Training loss keeps falling while validation loss flattens and then rises, and the deployed model is worse than the simpler one it replaced. | Growing gap between training and validation loss over epochs. | Put an automatic train-versus-validation gap threshold in the training report and make exceeding it block automatic promotion, so the run has to be explained by a human before it can ship. |
| Hardware failures. The compute itself returns a wrong answer, with no error raised, because a physical component is degrading. | A GPU with a failing memory module produces occasional silent bit flips, so roughly one run in twenty has a slightly wrong loss curve or a corrupted checkpoint, and nothing in the logs says anything went wrong. | Sporadic, non-reproducible output corruption that a rerun on different hardware does not reproduce. | Automatically re-run any anomalous result on a different node before anyone investigates it as a code bug, and stamp the node identifier on every run so a bad node surfaces as a cluster of anomalies rather than a string of unrelated mysteries. |
Why the fourth column looks the way it does. Every entry in it is the same move applied to a different failure: the fastest long-term improvement is never a better dashboard for that specific symptom, it is moving the check earlier, to the point where the failure is cheap to catch and impossible to ignore. Read across the column and the pattern is visible, a producer-side contract test, a vendor acceptance gate, a review-time availability field, an assertion that kills the run at step one, a promotion gate, an automatic re-run on different hardware: in each case the check moved from after the damage to before it. Two worked all the way through: a data-quality check that runs at ingest catches poor data quality before it reaches training, not after a model trained on it starts failing in production; a per-layer gradient-norm log added by default to every new architecture catches training instability during initial experimentation, not three weeks into a long training run. The single highest-leverage habit is a lightweight postmortem after every one of these that ends with "what automated check, if it had existed, would have caught this in minutes instead of days," and then actually adding that check, since the same failure mode recurring without a new safeguard is a sign the lesson was learned but not institutionalized.
A model's offline validation metrics stay stable, but production performance drops. Propose a prioritized diagnostic framework that distinguishes between a genuine change in the relationship between features and the label, a bug that corrupted values somewhere in the data pipeline, a change in how or when ground truth is generated, and a change in a feature's meaning or format upstream. For each candidate cause you identify, name one statistical method or check that would specifically implicate it and rule out the others.
Sample Answer
Direct answer
When offline metrics are stable but production performance drops, the four usual suspects are: the pipeline corrupted values somewhere between source and model, a feature's meaning or format changed upstream without the schema noticing, how or when ground truth is generated changed, or the true relationship between the features and the label genuinely moved (concept drift). I would check them roughly cheapest-and-most-common first, and for each one I want a check whose result pattern specifically fingerprints that cause rather than just being "another metric that also moved."
Structured elaboration
The trap in this kind of investigation is running four vague checks that all move together and still not knowing which one caused it. The fix is to pick, for each candidate, a check whose OTHER three candidates would not produce the same signature.
1. Data-pipeline corruption (check first: fast, and if found, it usually explains everything else).
Method: schema and range validation assertions against hard, verifiable invariants, not statistical ones: null-rate spikes, values outside a physically valid domain (negative ages, timestamps before the epoch, probabilities outside [0,1]), a sudden cardinality explosion in a categorical column, or a column that became constant. These are binary pass/fail checks, not distributional comparisons.
Why it specifically implicates corruption and rules out the others: a genuinely valid upstream schema or ground-truth change does not produce values that are physically impossible. If you find negative ages or a column that is suddenly 40 percent null, that is not "the relationship between features and the label changed," it is broken data, full stop.
2. Feature meaning or format change upstream.
Method: a value-scale and category-vocabulary check. Compare the ratio of the recent-window median to the baseline median for continuous features against "clean" conversion factors (10, 100, 1000), and compare the categorical vocabulary (the set of distinct values seen) between windows for new or vanished categories. Cross-reference against the upstream schema or data-contract version for that feature if one is tracked.
Why it specifically implicates a format change and rules out the others: a clean multiplicative jump (values roughly 100x larger, consistent with a cents-versus-dollars change) or a discrete vocabulary change (a categorical encoding switched from string labels to integer codes) is a structural signature, not a smooth statistical drift. Corruption tends to look like garbage (nulls, out-of-range junk); a format change tends to look like clean, consistently-transformed values, just the wrong ones. Neither a ground-truth change nor genuine concept drift touches the feature values at all, so this check would come back clean under those two causes.
3. Change in how or when ground truth is generated.
Method: a label-generation backtest plus a label-latency check. First, compare the distribution of time-to-label (how long after the event the label became available) between the baseline and recent windows with a Kolmogorov-Smirnov (KS) test, a standard two-sample test for whether two distributions differ; a shift here (for example, a conversion-attribution window that used to be 30 days and is now 7) is a strong tell on its own. Second, if you can replay recent raw events through the PRIOR label-generation logic, recompute the metric using old-style labels on the same model predictions; if the metric recovers, the labels moved, not the model.
Why it specifically implicates a ground-truth change and rules out the others: this is the only check in the set that holds the model and the input features completely fixed and only varies how the label was assigned. If performance recovers purely from relabeling, neither the features (ruled out by check 2 and by a stable feature-distribution check) nor the true feature-label relationship (the model was never touched) can be the cause.
4. Genuine concept drift (check last, since it takes the most work to positively confirm).
Method: a refit-recovery test. Once you have a batch of fresh, correctly-generated labels for the recent window, fit a new model using the SAME features and same recent data, and compare its cross-validated performance to the frozen production model's performance on that same window.
Why it specifically implicates concept drift and rules out the others: if a freshly-fit model on the same features and same window recovers close to baseline performance while the frozen model does not, the features still carry the signal, so it cannot be a format or corruption problem (those would degrade the fresh fit too), and the labels are known-good from check 3, so the remaining explanation is that the mapping from features to label itself moved and the OLD model's learned mapping is now stale. This is the positive test for concept drift, not just "we ruled out the other three so it must be this."
Feature-distribution stability as a cross-cutting checkpoint. Independent of which specific cause you land on, running a population stability index (PSI) or KS test on each feature's distribution between the baseline and recent window is worth doing early because it tells you whether P(X) moved at all:
PSI=i=1∑k(qi−pi)ln(piqi)where pi and qi are the proportion of examples falling into bucket i of a fixed binning, for the baseline and recent windows respectively. P(X) here means the distribution of the input features themselves: what the incoming data looks like, ignoring the labels entirely.
A three-bucket instance, so the formula is usable rather than decorative. Bin a feature into low, medium and high, and suppose the baseline window's proportions are p=[0.50, 0.30, 0.20] and the recent window's are q=[0.35, 0.35, 0.30]. Term by term:
(0.35−0.50)ln0.500.35=(−0.15)(−0.3567)=0.0535 (0.35−0.30)ln0.300.35=(0.05)(0.1542)=0.0077 (0.30−0.20)ln0.200.30=(0.10)(0.4055)=0.0405summing to PSI=0.102. The conventional reading bands are: below about 0.1 is no meaningful shift, 0.1 to 0.25 is a moderate shift worth looking at, and above 0.25 is a major shift. So 0.102 sits right at the lower boundary, which is the honest reading of a bucket mix that moved noticeably but not dramatically. Two properties worth knowing before you rely on it: every term is non-negative by construction (the two factors always share a sign), and the sum grows with the number of buckets, so PSI values are only comparable across windows that use the SAME fixed binning, and an empty bucket in either window makes the term undefined and has to be floored rather than dropped.
A stable P(X) (PSI under roughly 0.1 on every feature) with a performance drop points you toward causes 3 and 4 (which do not require X to move); a shifted P(X) (PSI above roughly 0.25 on at least one feature) points you toward causes 1 and 2, with the 0.1 to 0.25 middle band meaning the signal is not decisive on its own and you fall back on the four specific checks. It is a triage signal, not by itself a specific-cause test, which is why it complements rather than replaces the four checks above.
Worked example
Say the model is a churn classifier and offline validation area under the receiver operating characteristic curve (AUC) held at 0.81 on the standard holdout set, but the live precision at the deployed threshold dropped from around 70 percent to 55 percent over two weeks. Running the four checks in order: schema validation on the input features comes back clean (no nulls, no out-of-range values), so corruption is ruled out. The value-scale check on an "average order amount" feature shows its median jumped from about 12 to about 1200, a clean 100x, and the upstream team confirms they switched that column from dollars to cents in a pipeline refactor two weeks prior without updating the schema contract. That is the fingerprint from check 2 alone: a clean multiplicative jump matching a plausible unit conversion, on one specific feature, everything else stable. You do not even need to run checks 3 and 4 once this is confirmed, since the fix (dividing the column by 100 to get back to dollars) is a one-line pipeline change, and you would expect precision to recover once redeployed, which you would then verify against the same live metric.
Trade-offs and pitfalls
The most common wrong turn is running a single omnibus "did anything change" test (comparing an aggregate score distribution, or an adversarial-validation classifier trained to distinguish old data from new) and treating a positive result as a diagnosis. An adversarial-validation classifier with high accuracy tells you SOMETHING about P(X) changed; it does not tell you whether that is corruption, a format change, or legitimate covariate shift from a real change in the user population, and it says nothing about causes 3 and 4 at all, since neither necessarily touches P(X).
A second pitfall is skipping straight to retraining as the fix once any drop is observed. Retraining papers over corruption and format bugs instead of fixing them: if a feature's unit silently changed, retraining on the new unit will often "work" numerically but leaves the schema contract broken and the next similar bug undetected, and it burns a training cycle on a problem that was actually a one-line fix.
A third pitfall specific to the refit-recovery test for concept drift: make sure the fresh fit uses a comparably-sized, comparably-recent training window and the same features, not a bigger or differently-processed dataset, or a performance recovery could be an artifact of more data rather than evidence the relationship moved. Match the experimental conditions of the frozen model as closely as possible so the comparison is actually diagnostic.
Review this simplified training script and identify the bug(s):
# train.py (simplified)
X, y = load_all_data()
X = (X - X.mean(axis=0)) / X.std(axis=0) # normalization on full dataset
model.fit(X, y)
print('val_score', model.score(X_val, y_val))
Explain why each issue causes a problem in practice, propose a fix, and describe a unit test that would have caught it before it shipped.
Sample Answer
Direct answer. There are two defects in these four lines, not one.
Bug 1: normalization constants are fit on the whole dataset. X = (X - X.mean(axis=0)) / X.std(axis=0) # normalization on full dataset computes the mean and standard deviation from X (the WHOLE dataset) before any train/validation split, so the normalization constants are contaminated with information from the validation set. That is a form of leakage even though no explicit label information crossed the boundary.
Bug 2: the script never splits, and X_val is never produced or normalized. model.fit(X, y) trains on every row that exists, and then model.score(X_val, y_val) scores against an X_val that no line of this script creates. Whatever X_val is, one of two things is true and both are bad. If it came from the same X (a slice taken elsewhere), the model is being scored on rows it was directly trained on, so val_score is a training score wearing a validation label and will be optimistically high by however much the model memorized. If it came from somewhere else, it never went through the normalization step at all, so the model is receiving raw, unscaled inputs at scoring time while it was trained on standardized ones, and the score will be meaninglessly bad for reasons that have nothing to do with the model's quality. There is no third possibility in which this line is correct.
Why bug 1 causes a real problem, not just a style issue. The validation set is supposed to simulate "data the model has never seen." If the normalization constants used to preprocess the training data were computed partly from the validation set's own values, the validation set has, in a small but real way, already influenced what the model was trained on, which can inflate the model's apparent validation performance (and, more importantly, means the model won't behave identically on genuinely new data in production, where it obviously never had access to a preview of the future data's statistics).
Why bug 2 causes a real problem. Bug 1 biases the estimate; bug 2 destroys it. A model scored on its own training rows tells you nothing about generalization, and the failure is silent: the script prints a number, the number looks plausible, and nothing raises. This is also the bug that survives every fix to bug 1, which is why it needs naming separately rather than being folded into "split earlier."
Bug 1, measured. Run this and you get the block below it. 1,000 rows and 3 features; feature 0 is a pure linear ramp with no noise (simulating a feature that trends over time, like a growing user count or an inflation-adjusted price); features 1 and 2 are standard normal draws. The split is CHRONOLOGICAL, first 800 rows to train and last 200 to validation, because that is what makes the effect visible and reproducible. Both random seeds are pinned so the sweep at the end is not a story about one lucky draw.
import numpy as np
n, k, s = 1000, 800, 0.05
f0 = np.arange(n) * s # pure linear ramp, no noise
rng = np.random.default_rng(0)
X = np.column_stack([f0, rng.normal(size=n), rng.normal(size=n)])
tr, va = slice(0, k), slice(k, n) # CHRONOLOGICAL split, no shuffle
full_m, full_s = X.mean(axis=0), X.std(axis=0) # BUGGY: fit on everything
tr_m, tr_s = X[tr].mean(axis=0), X[tr].std(axis=0) # CORRECT: fit on train only
buggy = (X[va] - full_m) / full_s
correct = (X[va] - tr_m) / tr_s
print("feature-0 mean full = %.4f train-only = %.4f gap = %.4f"
% (full_m[0], tr_m[0], full_m[0] - tr_m[0]))
print("feature-0 std full = %.4f train-only = %.4f" % (full_s[0], tr_s[0]))
print("mean |buggy - correct| on feature 0, 200 val rows = %.4f"
% np.abs(buggy[:, 0] - correct[:, 0]).mean())
print("correct feature-0 val values span %.4f .. %.4f"
% (correct[:, 0].min(), correct[:, 0].max()))
sweep = np.random.default_rng(1) # seed pinned so the sweep is reproducible
gaps = np.array([abs(f0.mean() - f0[sweep.permutation(n)[:k]].mean())
for _ in range(5000)])
print("5000 random 800/200 splits: mean gap = %.4f max gap = %.4f"
% (gaps.mean(), gaps.max()))
feature-0 mean full = 24.9750 train-only = 19.9750 gap = 5.0000
feature-0 std full = 14.4337 train-only = 11.5470
mean |buggy - correct| on feature 0, 200 val rows = 0.7794
correct feature-0 val values span 1.7342 .. 2.5959
5000 random 800/200 splits: mean gap = 0.1793 max gap = 0.9068
The gap of exactly 5.0 is not a coincidence, it is arithmetic. For a linear ramp with step s over n points, the mean of the first k points is s*(k-1)/2 and the mean of all n is s*(n-1)/2, so the difference is s*(n-k)/2 = 0.05 * 200 / 2 = 5.0 exactly. And the downstream consequence is real, not rounding: on the leaking feature, every normalized validation value is off by 0.7794 on average, while the correct values for those same rows only span 1.7342 to 2.5959, a range of 0.8617. The error is nearly as wide as the entire spread of the correct values, so the buggy transform has effectively compressed the validation slice into a different region of feature space than the model was trained to expect. Features 1 and 2 have no trend, so they barely move; the damage is concentrated entirely on the feature that drifts.
One caveat that matters for reading this result: the size of the effect depends entirely on the split being time-ordered. Over 5,000 random 800/200 splits of the same ramp (seed pinned above), the mean-versus-train-mean gap averaged 0.1793 and the worst of the 5,000 was 0.9068, against exactly 5.0000 for the chronological split. Bug 1 is still a bug under a random split, it is just quantitatively small when train and validation are drawn from the same distribution, and quantitatively large exactly when you have the distribution shift that makes honest validation matter.
Fix. Each line is annotated with the bug it addresses.
# BUG 2: a split has to exist, and it has to be time-ordered to match the demo above.
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, shuffle=False)
# BUG 1: fit the normalization statistics on TRAIN ONLY.
mean, std = X_train.mean(axis=0), X_train.std(axis=0)
X_train = (X_train - mean) / std
# BUG 2: X_val now exists and goes through the SAME transform,
# BUG 1: using train's statistics, never refit on validation.
X_val = (X_val - mean) / std
model.fit(X_train, y_train)
print('val_score', model.score(X_val, y_val))
shuffle=False is doing real work here: train_test_split shuffles by default, and a shuffled split would reproduce neither the 5.0 mean gap nor the 0.7794 normalized difference above. Use shuffle=False when the data has a time order you care about, and a random split only when rows are genuinely exchangeable.
The unit tests that would have caught these.
For bug 1: assert that the normalization statistics the training pipeline actually used are IDENTICAL to the statistics computed from the training split alone. That is the assertion that holds under any split methodology and is the one to write first. The complementary assertion, that those statistics are explicitly DIFFERENT from the statistics computed on the full dataset, is a sharper regression detector but it only bites when the two splits have different underlying distributions. Under the chronological split above the two means are 19.9750 and 24.9750, so any tolerance below 5.0 catches the regression; under a random split they would be about 0.18 apart on average, which is inside ordinary sampling noise and would make the assertion flaky. So: use the "differs from full-dataset stats" assertion when your split is time-ordered or otherwise deliberately shifted, and when the split is random, replace it with a provenance assertion instead, that the validation transform reused the already-fitted statistics object rather than calling a fit method a second time.
For bug 2: assert that the index sets of the training rows and the scored rows are non-empty and disjoint, and that the scored feature matrix went through the same transform object as the training matrix. This is the test that fails loudly the moment someone scores against an array the pipeline never touched, which is the exact failure the original script has and the one no statistics-comparison test can see.
Write a SQL query to find duplicate primary keys and NULL values in critical columns of a feature table features(user_id, feature_a, feature_b, event_time). Explain concretely how duplicates and unexpected NULLs in this table can cause bugs during training or serving, and suggest a database constraint or an ETL-level check that would prevent them from ever reaching this table.
Sample Answer
Direct answer. Two separate queries: one groups by the primary key and filters to groups with more than one row (duplicates), the other filters directly on IS NULL for the critical columns.
-- duplicate primary keys
SELECT user_id, COUNT(*) AS cnt
FROM features
GROUP BY user_id
HAVING COUNT(*) > 1;
-- NULLs in critical columns
SELECT user_id, feature_a, feature_b
FROM features
WHERE feature_a IS NULL OR feature_b IS NULL;
The fixture both queries were run against, five rows carrying one of each defect plus a clean control:
CREATE TABLE features (
user_id TEXT,
feature_a REAL,
feature_b REAL,
event_time TEXT
);
INSERT INTO features VALUES
('u1', 1.0, 2.0, '2026-07-01T10:00:00Z'),
('u1', 1.0, 2.0, '2026-07-01T10:00:00Z'), -- exact duplicate primary key
('u2', NULL, 3.0, '2026-07-01T10:05:00Z'), -- NULL in feature_a
('u3', 5.0, NULL, '2026-07-01T10:10:00Z'), -- NULL in feature_b
('u4', 7.0, 8.0, '2026-07-01T10:15:00Z'); -- clean control row
Running the two queries above against that fixture (SQLite via Python's sqlite3, so each row comes back as a tuple) returns exactly:
duplicate user_ids: [('u1', 2)]
rows with NULLs in critical columns: [('u2', None, 3.0), ('u3', 5.0, None)]
which matches the injected fixture exactly, confirming both queries catch what they're meant to catch and nothing else: u1's individual rows are not listed separately by the duplicate query (only the grouped count is), and the clean control row u4 appears in neither result.
Why these two bugs matter for training and serving. A duplicate user_id silently gives that user extra weight in any aggregation or training-set statistic (their pattern is counted twice), and if the duplicates have any small inconsistency between them (a slightly stale second copy), the model effectively trains on conflicting signal for the same entity. A NULL in a feature that the model's preprocessing code doesn't explicitly expect will either crash at training time (a TypeError deep in a library, unhelpful to debug) or, worse, get silently coerced into 0.0 or some other default by a permissive preprocessing step, which is functionally a data-corruption bug that produces a plausible-looking but wrong number instead of an error.
Preventing recurrence. A UNIQUE constraint on user_id (or, if legitimate multiple rows per user are expected via a compound key like (user_id, event_time), a unique constraint on that compound key) makes duplicates impossible to insert rather than something you find after the fact. For NULLs, a NOT NULL constraint on feature_a/feature_b at the database level is the strongest guarantee, but if some legitimate rows really can have missing features, the right fix is an ETL-level check instead: a pipeline step that explicitly quarantines or flags rows with unexpected NULLs before they reach the feature table, rather than either silently dropping them or letting them through as if they were valid.
Name three lightweight tools or techniques you would use to profile latency, memory, or compute usage for deep-learning workloads, covering both the training side and the inference/serving side. For each, give a one-sentence description of what it measures and one clear trade-off it makes.
Sample Answer
Direct answer. Three tools cover most of what's needed on the training side and the inference side: a GPU utilization monitor for the cheap, always-on signal; a framework-native profiler for detailed per-operation timing; and a trace visualizer for understanding how time is spent across a whole distributed step, not just one process.
Training side.
nvidia-smi(or a continuous variant likenvidia-smi dmon): measures GPU utilization, memory usage, and power draw in near-real-time. Trade-off: essentially zero overhead and always available, but it only tells you THAT the GPU is busy or idle, not WHY, so it's a first-alarm tool, not a diagnostic one.- A framework-native profiler (PyTorch Profiler, TensorBoard Profiler): measures per-operation time breakdown (which specific op, kernel, or Python function is consuming time) across CPU and GPU. Trade-off: much more detailed and precise than a utilization monitor, but adds meaningful overhead while active, so it's typically run for a short, targeted window rather than continuously.
Inference/serving side.
- A distributed trace visualizer (for example built on OpenTelemetry or Nsight Systems for lower-level GPU traces): measures how time is spent across a whole request or a whole distributed training step, including gaps and cross-process/cross-GPU dependencies, not just one process's internal breakdown. Trade-off: gives you the whole-system picture a single-process profiler structurally cannot, but requires trace instrumentation to already be in place, which is an upfront cost, and traces at scale can themselves become expensive to store and query, so they're often sampled rather than captured for every request.
One-sentence scenario each. nvidia-smi dmon running continuously in a dashboard tells an on-call engineer within seconds whether a training job's low throughput is "GPU idle" (a data-pipeline problem) or "GPU busy" (a genuinely slow compute path), before anyone opens a heavier profiler. The PyTorch Profiler, run for 20-30 steps of a job that's suspected to be slow, tells you exactly which layer or operation is consuming the most time, the next step after nvidia-smi narrows the problem to "the model itself." A trace visualizer, attached to a specific slow production request, shows you exactly how a total 800ms latency budget was actually spent across the feature service, the model server, and any downstream calls, the tool you reach for once you've ruled out "it's the model's raw compute" and need to know where in the surrounding system the time actually went.
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.