Foundations to Frontier
Tests

Testing ML Systems

A learned model has no specification line by line, so testing it means checking properties: that the training code computes what it claims, that accuracy holds on every important slice of the operating conditions, that predictions are invariant to what should not matter and move in the right direction with what should, that a new version does not break what the old one got right, and that serving inputs look like training inputs. The exercises build such a test suite, inject eight realistic bugs into a training and serving pipeline, and measure which tests catch which bugs, how many test points a reliable test needs, and what neuron coverage and metamorphic relations can and cannot reveal.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Exams for a model

A teacher who checks only the average mark of a class may miss that one group of students failed everything. Testing a machine-learning model is similar: overall accuracy can look fine while the model fails in a rare situation, depends on something irrelevant, or was quietly fed data in the wrong units. Good tests check many specific things: the rare situations, things that should not change the answer, things that should change it in a known direction, and whether a new version broke anything that used to work.

🎮 Reliability lab

Test “accuracy ≥ 0.9330” (midway) on 1000 random test points: the good model fails it with probability 17.6% and the buggy model passes with probability 19.9% (normal approximation).

Which test catches which bug (M3-4 study, seed 0; red = test fails)

injected bugaccuracy ≥ 0.90every slice: upper 95% bound ≥ 0.85invariance flips ≤ 0.08directional violations ≤ 0.01negative flips ≤ 0.04
no bug0.9460.9420.0200.0000.007
20% of training labels flipped0.8830.8590.0970.2120.083
x1 served in other units (×10)0.6940.6190.0110.0000.276
label leaks into nuisance x4 in training0.8680.8350.1560.0000.101
rare regime dropped from training0.9300.6700.0210.0000.025
training stopped after 30 steps0.9320.6960.0180.0000.026
x0 and x2 swapped at serving0.3750.3590.0290.3020.598
abs() applied to x0 in preprocessing0.6730.6870.1790.4340.293
regime flag lost at serving0.9280.6530.0190.0000.025

Three bugs pass the accuracy test and are caught only by the slice test; every bug fails at least one test, and five clean retrains raised no false alarm.

Why engineers care

Google’s “ML Test Score” rubric (2017) lists 28 tests for production ML systems, covering data, model, infrastructure and monitoring, because most failures it saw came from outside the model code.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Overall accuracy can hide…
  2. 2. An invariance test checks that…
  3. 3. A regression test between versions checks…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Unit tests for ML code: shapes, gradient checks against finite differences, overfitting a tiny batch, deterministic seeds.
  • Slice-based evaluation: accuracy per subgroup or operating condition, with confidence intervals, so a weak rare slice is not averaged away (hidden stratification).
  • Behavioural tests (CheckList): minimum-functionality tests, invariance tests (a change that should not matter), and directional expectation tests (a change that should move the output one way).
  • Metamorphic testing: when the correct output is unknown (no oracle), check relations between outputs of related inputs, such as invariance to the order of training data.
  • Coverage criteria: neuron coverage and its variants, which measure how much of the network the tests activate, but correlate poorly with finding faults.
  • Regression tests between versions: negative flips, the share of inputs the old model got right and the new one gets wrong.
  • Data validation: schema, range and distribution checks on training and serving inputs, catching training/serving skew before the model runs.
  • Mutation testing: inject known bugs to measure which ones a test suite detects.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Testing without an oracle uses…
  2. 2. A negative flip is an input that…
  3. 3. Mutation testing measures…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

A test suite for a model

Exercise 1.

  • Six inputs: four informative, one nuisance input the label ignores, and a 0/1 flag for a rare regime (5%) with a different decision rule.
  • A one-hidden-layer network trained with Adam; a gradient check compares backpropagation with central finite differences.
  • Tests: accuracy, per-slice accuracy with Wilson intervals, invariance to resampling the nuisance input, the directional expectation that raising x0 never lowers P(y = 1), and negative flips against a previous model.

Practice.

  • Test the pipeline, not only the model: apply tests through the same preprocessing as serving.
  • Slice by operating condition and report intervals; small slices need many examples or wide margins.
  • Write behavioural tests from requirements: what must not matter, what must move the output and which way.
  • Size test sets for the regression you need to detect; a fixed threshold on a small test set is a flaky test.
  • Validate inputs at serving against the training data, and keep labelled golden examples for bugs that leave input distributions unchanged.
  • Track negative flips when replacing a model, not only the change in accuracy.
def suite(model, serve, previous, X, y):
    P = predict(model, serve(X)) > 0.5
    return dict(accuracy=mean(P == y) >= 0.90,
                slices=all(wilson_upper(slice) >= 0.85 for each regime),
                invariance=mean(P != predict(serve(X with x4 resampled))) <= 0.08,
                directional=mean(P(x0 + 0.5) < P(x) - 0.01) <= 0.01,
                regression=mean(previous right and P wrong) <= 0.04)
🐍 Exercise 1: tests for a learned model
Implement a gradient check, slice reports with Wilson intervals, invariance and directional tests, and the negative-flip rate between two model versions.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Tests should be applied…
  2. 2. A small test set makes a fixed-threshold test…
  3. 3. Swapped columns with the same distribution are caught by…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Gradient checks. For a smooth loss f, the central difference (f(θ + ε) − f(θ − ε)) / 2ε differs from f′(θ) by f‴(ξ)ε²/6, so with ε = 10⁻⁵ the truncation error is about 10⁻¹⁰ and a correct backpropagation agrees to roughly seven digits or better, while a wrong one disagrees in the first digit. Comparing relative errors on random parameters is a cheap unit test for training code.

How many test points. A test set of n points estimates accuracy p with standard error √(p(1 − p)/n). To separate a good model (accuracy p_g) from a buggy one (p_b) with a threshold midway, each error probability is about Φ(−Δ√n / 2σ) with Δ = p_g − p_b and σ ≈ √(p(1 − p)). Both fall below β when n ≥ (2 z_β σ / Δ)². For Δ = 0.014 and p ≈ 0.93, β = 5% needs about 3,600 points; a few hundred points make the test a coin toss. Slices are smaller still, so slice tests need either many examples or wide margins, which is why intervals (Wilson’s score interval behaves well for small n and extreme p) are reported instead of point estimates.

Metamorphic relations. For Euclidean k-nearest neighbours, distances are unchanged by adding a constant vector to every point and scale by c when every point is scaled by c > 0, so neighbour rankings, and predictions, must not change; nor may they depend on the order of training points or on which other queries are in the batch. Duplicating the training set and using 2k + 1 neighbours gives each of the k nearest points two votes and the next one a single vote, which reproduces the original majority for odd k. A bug that violates none of the relations (such as using k + 1 neighbours) needs an oracle. A mutant that cannot change any output (squared instead of plain distance) is equivalent and should not be caught.

Coverage. Neuron coverage counts units activated by at least one test input. With ReLU units, a handful of random inputs activates nearly all of them, so coverage measures the test inputs’ spread in activation space, not whether they include the operating conditions where the model fails; empirical studies found it correlates weakly or negatively with fault detection.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Central-difference truncation error scales as…
  2. 2. To halve the margin you can resolve, the test set must grow…
  3. 3. Duplicating the training set preserves k-NN votes when using…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Which tests catch which realistic bugs in a training and serving pipeline, and which bugs pass a plain accuracy test?

History.

  • T. Y. Chen, S. C. Cheung and S. M. Yiu (1998) introduced metamorphic testing; X. Xie and colleagues (2011) applied it to machine-learning classifiers.
  • D. Sculley and colleagues (2015) described hidden technical debt in ML systems; E. Breck and colleagues (2017) proposed the ML Test Score rubric, and (2019) data validation for ML at Google.
  • K. Pei and colleagues (2017) introduced neuron coverage in DeepXplore; F. Harel-Canada and colleagues (2020) found it a poor measure of test quality.
  • M. T. Ribeiro and colleagues (2020) introduced CheckList behavioural testing; L. Oakden-Rayner and colleagues (2020) described hidden stratification in medical imaging.
  • J. M. Zhang, M. Harman, L. Ma and Y. Liu (2020) surveyed ML testing; S. Yan and colleagues (2021) studied negative flips between model versions.

Exercise 2.

  • 2,000 training points, 4,000 held-out points. A previous model (clean pipeline, another seed) serves as the regression baseline.
  • Eight bugs are injected one at a time into the training or serving pipeline, and the five-test suite is run through the serving path.
  • Five clean retrains with other seeds measure false alarms.

Seed 0 (values; failing tests in bold):

injected bug accuracy ≥ 0.90 lowest slice upper bound ≥ 0.85 invariance flips ≤ 0.08 directional violations ≤ 0.01 negative flips ≤ 0.04
none 0.946 0.942 0.020 0.000 0.007
20% of training labels flipped 0.883 0.859 0.097 0.212 0.083
x1 served in other units (×10) 0.694 0.619 0.011 0.000 0.276
label leaks into nuisance x4 in training 0.868 0.835 0.156 0.000 0.101
rare regime dropped from training 0.930 0.670 0.021 0.000 0.025
training stopped after 30 steps 0.932 0.696 0.018 0.000 0.026
x0 and x2 swapped at serving 0.375 0.359 0.029 0.302 0.598
abs() applied to x0 in preprocessing 0.673 0.687 0.179 0.434 0.293
regime flag lost at serving 0.928 0.653 0.019 0.000 0.025

Seeds 1 and 2: the same three bugs (rare regime dropped, training stopped early, regime flag lost) passed the accuracy test, and in seed 2 the label leak passed it as well (0.906). The slice test missed the label leak in both (0.852, 0.858) and the flipped labels in seed 2 (0.874). The five clean retrains raised no false alarm in any seed (75 tests).

Findings.

  • Every injected bug failed at least one test in every seed, and no clean retrain failed any test.
  • The accuracy test alone missed three of eight bugs in seeds 0 and 1 and four in seed 2; for the three bugs missed in every seed, overall accuracy fell by only 1.3 to 2.2 points, while the upper bound of the rare-regime slice fell to 0.60 to 0.74.
  • No single test caught everything: the slice test missed the label leak in two seeds and flipped labels in two, which the invariance, directional and regression tests caught.
  • The directional test caught only flipped labels, the column swap and abs(), and the invariance test only flipped labels, the label leak and abs(): each behavioural test targets one kind of fault.
🐍 Exercise 2 (research): which tests catch which realistic bugs in a training and serving pipeline, and which bugs pass a plain accuracy test?
Inject eight bugs into a training and serving pipeline and measure which tests of a five-test suite catch each, with false alarms on clean retrains.

Testing ML systems in practice

  • Production ML platforms run data validation (TensorFlow Data Validation, Great Expectations), slice-based evaluation (TensorFlow Model Analysis) and behavioural test suites in continuous integration, gating model releases on them (topic N3).
  • Safety-critical systems combine these with scenario-based testing and simulation, requirements-based test coverage of the operational design domain, and statistical arguments for the number of test cases (topics M2-5 and M2-6).
  • Model updates are checked for negative flips and slice regressions, and rolled out gradually with monitoring (topic N4).

References

  1. T. Y. Chen, S. C. Cheung and S. M. Yiu (1998). “Metamorphic testing: a new approach for generating next test cases.” Technical report, Hong Kong University of Science and Technology.
  2. E. Breck, S. Cai, E. Nielsen, M. Salib and D. Sculley (2017). “The ML test score: a rubric for ML production readiness and technical debt reduction.” IEEE Big Data.
  3. K. Pei, Y. Cao, J. Yang and S. Jana (2017). “DeepXplore: automated whitebox testing of deep learning systems.” SOSP.
  4. M. T. Ribeiro, T. Wu, C. Guestrin and S. Singh (2020). “Beyond accuracy: behavioral testing of NLP models with CheckList.” ACL.
  5. F. Harel-Canada, L. Wang, M. A. Gulzar, Q. Gu and M. Kim (2020). “Is neuron coverage a meaningful measure for testing deep neural networks?” ESEC/FSE.
  6. J. M. Zhang, M. Harman, L. Ma and Y. Liu (2020). “Machine learning testing: survey, landscapes and horizons.” IEEE Transactions on Software Engineering.
  7. S. Yan, Y. Xiong, K. Kundu and colleagues (2021). “Positive-congruent training: towards regression-free model updates.” CVPR.