Sub topic 11
CI/CD for machine learning: code, data and model checks
This chapter assumes you can write Python tests with pytest, use Git branches and pull requests, and know what a training run and a test-set metric are. It also assumes you have seen the experiment tracking and model registry chapters. Here we put those pieces behind automation.
Why ML needs more than code CI/CD
In ordinary software, behavior is determined by code. A pipeline builds the code, runs tests, and ships the artifact. In a machine learning system, behavior is determined by three things: code, data, and the trained model. Any of them can change without the others, and any of them can break production.
- A code change, such as a refactored preprocessing function, can silently alter the features the model sees.
- A data change, such as a new upstream column format, can degrade the model with no commit at all.
- A model change, such as retraining on newer data, can produce a model that passes every unit test and is still worse than the one in production.
So CI/CD for ML extends the usual loop with data checks and model checks. Continuous integration (CI) is the automatic validation of every change. Continuous delivery (CD) is the automatic, controlled movement of a validated artifact toward production. Some teams also name a third idea, continuous training (CT), where the pipeline retrains the model automatically. That topic is covered in the retraining chapter.
The three layers of checks
Layer 1: code checks
These are the familiar ones, and they run on every pull request:
- Linting and type checking.
- Unit tests for feature functions, for example "a missing age is imputed with the median" or "the one-hot encoder keeps the same column order".
- A small smoke test that trains on a tiny sample for a few iterations. It proves the training script runs end to end without needing hours of compute.
The most valuable unit tests in ML code cover the transformation functions that are shared between training and serving. If training and serving use different code for a feature, the model sees different inputs in production than it saw in training (training-serving skew). A test that runs the shared function on fixed inputs and compares the output with known values catches many of these bugs.
Layer 2: data checks
Data checks run before training and often again before serving. They answer: is this data fit to learn from?
Typical checks:
- Schema: expected columns, types, and allowed categories.
- Completeness: the share of nulls per column is under a limit.
- Range and distribution: values fall in plausible ranges, and summary statistics have not jumped.
- Volume: the row count is not suddenly 10 times smaller.
- Label sanity: class balance is within the expected band.
Here is a data check written as a plain function plus pytest tests. It runs without any extra validation library.
import pandas as pd
EXPECTED_COLUMNS = {
"sepal_length": "float64",
"sepal_width": "float64",
"label": "int64",
}
MAX_NULL_FRACTION = 0.01
MIN_ROWS = 100
def validate_batch(df):
"""Return a list of problems. An empty list means the batch passes."""
problems = []
for column, dtype in EXPECTED_COLUMNS.items():
if column not in df.columns:
problems.append(f"missing column: {column}")
elif str(df[column].dtype) != dtype:
problems.append(f"{column} has dtype {df[column].dtype}, expected {dtype}")
if len(df) < MIN_ROWS:
problems.append(f"only {len(df)} rows, need at least {MIN_ROWS}")
for column in df.columns.intersection(list(EXPECTED_COLUMNS)):
null_fraction = df[column].isna().mean()
if null_fraction > MAX_NULL_FRACTION:
problems.append(f"{column} is {null_fraction:.1%} null")
return problems
def make_good_batch(rows=200):
return pd.DataFrame(
{
"sepal_length": [5.0 + (i % 10) / 10 for i in range(rows)],
"sepal_width": [3.0 + (i % 5) / 10 for i in range(rows)],
"label": [i % 3 for i in range(rows)],
}
)
def test_good_batch_passes():
assert validate_batch(make_good_batch()) == []
def test_missing_column_is_reported():
df = make_good_batch().drop(columns=["label"])
assert "missing column: label" in validate_batch(df)
def test_null_heavy_column_is_reported():
df = make_good_batch()
df.loc[:50, "sepal_width"] = None
assert any("sepal_width" in p and "null" in p for p in validate_batch(df))Save this as test_data.py and run pytest test_data.py. In a real pipeline the same validate_batch function runs on each new data snapshot, and a non-empty list fails the job.
Layer 3: model checks
After training, the pipeline decides whether the new model may move forward. This is the release gate from the evaluation chapter, now automated. The gate compares a candidate against both an absolute floor and the current production model:
import sys
def should_promote(candidate_accuracy, production_accuracy, min_gain=0.0, floor=0.90):
"""Release gate: the candidate must clear an absolute floor and not be worse than production."""
if candidate_accuracy < floor:
return False
return candidate_accuracy >= production_accuracy + min_gain
if __name__ == "__main__":
candidate, production = float(sys.argv[1]), float(sys.argv[2])
ok = should_promote(candidate, production)
print("promote" if ok else "reject")
sys.exit(0 if ok else 1)Running python gate.py 0.94 0.92 prints promote and exits with status 0. Running python gate.py 0.93 0.95 prints reject and exits with status 1. CI systems treat a nonzero exit status as a failed step, so the gate stops the pipeline without any special integration.
Beyond a single headline metric, mature gates also check:
- Slice metrics: accuracy on important subgroups, such as new customers or one region, not only overall.
- Latency and size: the model meets the serving time and memory budget.
- Behavioral tests: fixed inputs with known expected outputs, such as "a clearly fraudulent example must score above 0.9".
- Comparison on the same data: candidate and production are scored on the same frozen test set, otherwise the numbers are not comparable.
What triggers the pipeline
| Trigger | Typical checks that run | Notes |
|---|---|---|
| Pull request to training code | Code checks, smoke training | Keep it fast, minutes not hours |
| Merge to main | Full training on a pinned data version, model gate | Logs the run to the experiment tracker |
| New data snapshot | Data checks, optional retraining | Triggered by a schedule or data arrival |
| Model registered | Deployment checks, staged rollout | Promotion is a registry stage change |
Pinning the data version in the merge-triggered run matters. If the pipeline reads "latest data", two runs of the same commit give different models, and a failed gate cannot be reproduced.
From passing gate to production
A model that passes the gate is registered as a new version with the run ID, data version, and metrics attached. Delivery then uses the staged patterns from the deployment chapter, such as shadow mode, a canary release, or A/B testing. The CD step should be able to roll back by pointing serving at the previous registry version. Rollback is only reliable if old versions are kept and their dependencies are recorded.
Common errors
- Testing only code. The pipeline is green while the data has changed. Add data checks before training.
- Gating on one number. An overall accuracy gain can hide a large drop on one segment. Add slice metrics.
- Comparing against a stale baseline. If the production figure in the gate is hard-coded, it goes out of date. Read it from the registry.
- Flaky model tests. Unseeded training makes metrics vary between runs, so the gate sometimes fails for no reason. Fix random seeds and allow a small tolerance through
min_gainor a confidence margin. - Slow CI. Full training on every pull request makes developers bypass the pipeline. Use smoke tests on pull requests and full runs on merge.
- Training-serving skew left untested. Test the shared feature code, not only the model.
Exercise
A pull request changes only a preprocessing function. All code tests pass and the model gate is not run because no training was triggered. Two weeks later, production accuracy drops. Which check was missing, and where should it have run?
Show answer
The pipeline should have run a training-serving consistency test on the changed feature function, and should have retrained or at least re-evaluated the model on a pinned data version to run the model gate. A change to preprocessing alters model inputs, so it can change behavior just as a data or model change can. Path-based triggers should start the model checks whenever feature code changes, not only when training code changes.
Exercise
Using the should_promote function with its default floor of 0.90, what does it return for a candidate with 0.91 accuracy and a production model with 0.93, and why?
Show answer
It returns False. The candidate clears the 0.90 floor, but its accuracy is below the production accuracy plus min_gain (0.93 + 0.0), so it is worse than production.