07 / 16 · Training
Testing ML systems
How to test a system whose behaviour is learned rather than written: the ML Test Score rubric, tests of data, models and pipelines, behavioural tests of minimum functionality, invariance and direction, regressions on slices judged statistically, and where each test runs in CI.
On this page 8
Renaming an uploaded card must not change whether its preview needs repair. A classifier can pass an accuracy check while violating that requirement, especially if the evaluation data repeats the same accidental relationship between filenames and labels. A test must state the relationship directly.
An aggregate score leaves behaviour unspecified#
A held-out score estimates performance on the sampled population. It does not specify correct handling of malformed inputs, serialization, duplicate requests or future populations. Keep the evaluation set, but give each additional requirement its own observation and acceptance rule.
Our original fixture uses a deliberately simple score for a preview. Let be a blur indicator and indicate missing metadata. Define
A score of at least 0.6 requests review. This is a hand-specified test double, not a trained predictor or a calibrated probability. Its simplicity lets us determine expected behaviour exactly before testing a learned replacement.
Test both definite rules and uncertain quality#
A schema violation is a definite failure. An estimated accuracy difference is uncertain because a finite sample could have been different. Mixing those cases into one numerical threshold makes failures hard to interpret. Report invalid input, broken invariants and statistical evidence separately.
Some requirements can be checked without labels. If document identity is metadata only, changing it should preserve the score. If the declared score is monotone in blur, increasing blur should not reduce the score. These relations must come from the product or mathematical specification; they are not automatically true for every ML task.
A rubric is a prompt to examine missing evidence#
Breck and coauthors’ ML Test Score proposes 28 checks covering data, models, infrastructure and monitoring (2017). It is a production-readiness rubric, not a proof of generalization or a replacement for application requirements. Our checks below are derived from the preview contract; the paper’s tables and examples are not reproduced.
Validate the same inputs on both paths#
The blur value must be finite and inside ; the metadata flag must be binary. The fixture rejects , , NaN and positive infinity. Checking only a range can accidentally mishandle NaN, because comparisons with it do not behave like comparisons with ordinary numbers. State the finite-value check explicitly.
Test boundaries as well as ordinary values. Record whether a missing field is rejected, imputed or represented by its own indicator. Then use that definition in both training and serving. A schema passed by one path is weak evidence if the other path silently applies a different unit conversion.
Separate training health from model acceptance#
Does the optimization path work?#
A tiny deterministic calculation can check signs and serialization without evaluating product quality. For , use points and and mean squared error . At , and both derivatives are . A gradient step of size 0.1 gives , predictions and loss . The fixture checks that calculation and a JSON coefficient round trip.
A more complex training smoke test checks shape compatibility, finite losses and a suitable small optimization problem. One step need not lower loss for arbitrary learning rates or stochastic updates. Save/load equivalence requires a specified tolerance and environment; setting a seed alone does not promise bitwise determinism on every backend.
Does a candidate meet the decision requirement?#
Compare the candidate and current model on the same eligible items. For binary correctness, let count items fixed by the candidate and count newly broken items. The difference in accuracy is , where is the total item count. The shared successes and shared failures cancel. For independent, identically distributed paired items under the equal-marginal-accuracy null, the exact McNemar test conditions on and compares the split with a binomial probability of one half. This does not establish practical significance or safety on every slice.
Choose a permitted regression margin before seeing results. Preserve paired items when estimating uncertainty; if several rows belong to one document or user, resample at that dependency unit. A small interval around a trivial average improvement can still hide an unacceptable rare failure.
State a relation and try to break it#
CheckList formalizes tests of simple known cases, invariance under an irrelevant change, and expected directions of change (Ribeiro et al.). Apply those ideas to our declared preview contract:
| Requirement | Constructed check | Fixture result |
|---|---|---|
| Known boundary cases | Score at the ends of the input range | 0.1 and 1.0, checked |
| Blur cannot reduce the score | Increase each of six blur values by 0.05, capped at 1 | Six comparisons pass |
| Renaming cannot affect review | Append -export to the ID | Correct score: zero changed decisions |
Now introduce a deliberate bug: add 0.25 to the score when the identifier ends in -export. For blur values with , renaming changes two of six decisions. For example, moves from 0.46 to 0.71, crossing the review threshold. The test detects exactly the dependency that the specification forbids. The score is simple enough to explain each changed decision.
The following program makes the injected defect selectable. Keeping the same inputs for both implementations isolates the intended change. It uses only the standard library; the expected output below was obtained by executing this exact block.
import math
def score(blur, missing, document_id="", buggy=False):
if not math.isfinite(blur) or not 0 <= blur <= 1 or missing not in (0, 1):
raise ValueError("Input outside fixture schema")
value = 0.1 + 0.8 * blur + 0.1 * missing
if buggy and document_id.endswith("-export"):
value += 0.25
return min(1.0, value)
blurs = [0.1, 0.3, 0.45, 0.55, 0.7, 0.9]
for buggy in [True, False]:
changed = sum((score(b, 0, "card", buggy) >= 0.6) !=
(score(b, 0, "card-export", buggy) >= 0.6)
for b in blurs)
assert changed == (2 if buggy else 0)
print("buggy:", buggy, "changed:", changed)
assert math.isclose(score(0, 0), 0.1)
assert math.isclose(score(1, 1), 1.0)
assert all(score(b, 0) <= score(min(1, b + 0.05), 0) for b in blurs)
buggy: True changed: 2
buggy: False changed: 0
A regression test is useful only if a relevant defect can make it fail. Here, accepting the filename-dependent implementation would fail the requirement changed == 0; retaining the intentionally faulty branch in this demonstration proves that the fixture can observe the specified defect. This is a small mutation check, not evidence that every possible filename bug is covered. A real test suite would keep the repaired implementation in production and store the minimal failing cases as regression inputs.
The relation also has a boundary. If the application deliberately extracts a file extension to select a decoder, arbitrary renaming could change how bytes are interpreted. The requirement must then isolate the irrelevant portion of the name or compare normalized, already decoded content. A mechanically applied invariance test can enforce the wrong product behaviour when its transformation changes meaning. Similarly, monotonicity in our declared blur score is a mathematical contract, while changing pixels in a real image can affect several features at once.
To keep the test independent of the implementation, derive the expected scores from the written formula and simple boundary arithmetic. Do not obtain the expected array by calling the same function and then compare a second call against it. For the gradient check, compute the two derivatives on paper before exercising the update. Those independent expectations are the reason a sign error or a spurious filename term can be detected.
Look at the populations whose outcomes matter#
A slice could be scanner type, document language or metadata availability. Define it because a failure there has a consequence, not because it produces a favourable report. Report its sample size and uncertainty. Repeatedly searching many slices increases the chance of finding an apparent change by chance; distinguish exploratory findings from predeclared release gates.
Exercise artifact boundaries#
An integration test should follow a small permitted input through feature generation, scoring and output interpretation. Preserve the input’s identity through the join with its label. Exercise an empty batch and a malformed record. Verify that an artifact loaded in the serving path resolves to the version that was evaluated. A unit test of the estimator cannot observe a wrong feature order introduced by the packaging step.
For the fixture’s two coefficients, JSON serialization preserves the predictions exactly. Real model formats may need numerical tolerance, architecture metadata and trusted-loading rules. Do not load arbitrary pickle files merely to test a production endpoint.
Place checks where their evidence becomes available#
Run cheap schema and transformation checks when code changes. Evaluate a candidate after its training artifact exists. Run an end-to-end deployment check against the packaged artifact before exposure. Monitor delayed outcomes after release. Each gate should keep the failing input or a permitted minimal reproduction and explain whether the failure concerns a contract, a statistical estimate or infrastructure.
What changed#
The filename dependency is now an explicit failing test rather than an unexplained score change. The tiny gradient calculation checks implementation arithmetic separately from model quality, and the release comparison preserves item pairing.
Limits#
Six constructed values cannot establish reliability over all documents. A passing invariance test for one field does not establish fairness, and an idealized monotonic score is not evidence that a trained system learned the intended relationship. The fixture is an executable specification example; acceptance of a real model needs representative data and measured outputs.
What to retain#
Give deterministic contracts deterministic tests. Keep uncertain quality estimates separate. Test relations that follow from the task. Compare releases on paired items and meaningful slices. Exercise serialization and feature boundaries. Preserve a reproducible failure.
Run the fixture#
The testing function in Python source checks the four invalid inputs, six monotonic comparisons, the deliberate rename bug, repaired invariance, the loss decrease from 0.5 to 0.325 and the coefficient round trip. It uses no external package, dataset or trained weights. Saved outputs describe only those constructed cases.
Next#
Distributed training expands the execution boundary to several devices, where communication, partitioning and checkpoint recovery require additional tests.
References#
-
Eric Breck, Shanqing Cai, Eric Nielsen, Michael Salib and D. Sculley. The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction. IEEE Big Data, 2017. Scope of the readiness rubric; no rubric table copied.
-
Marco Tulio Ribeiro, Tongshuang Wu, Carlos Guestrin and Sameer Singh. Beyond Accuracy: Behavioral Testing of NLP Models with CheckList. ACL, 2020, section 2: test-type concepts. The preview formula, values and bug above are original.
-
Quinn McNemar. Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika 12, 153–157, 1947. Paired binary-outcome comparison.
-
Statsmodels contributors. McNemar test, documentation 0.15.0, checked 13 November 2026: exact binomial and approximate chi-square variants.