CI/CD and Continuous Training
CI/CD for ordinary software rests on one idea: every change goes through the same automated path (build, test, package, deploy) so that releasing is routine and safe. ML systems change in three ways rather than one. The code changes (a new feature, a bug fix), the data changes (new rows every day, a schema change upstream) and the model changes (retrained on new data, even with unchanged code). So ML adds a third loop to CI and CD: continuous training (CT), which retrains and re-evaluates the model when data or performance says so, and feeds the result into the same release path.
Three loops
CI (on every pull request, minutes): everything that can be checked without the full data and a full training run.
- lint and type checks (
ruff,mypy), as for any Python project; - unit tests for transforms and behaviour tests on a small saved model (Testing ML Code and Models);
- data tests on a committed sample: schema and validator logic (Data Validation);
- a training smoke test: run the real training entry point on a few hundred rows for a few iterations; the loss decreases, the model saves, loads and predicts with the right shape. This catches most broken pipelines in a minute.
CD (on merge to main, or on a release tag): produce, check and ship a model.
- validate the full training data snapshot; run the training pipeline;
- the evaluation gate: the candidate against the current champion on a fixed, versioned evaluation set, with slice checks; a failing gate ends the run (and is not an error to "retry until green");
- register the version with its lineage (Model Registry), build the serving image (Docker for models), scan it (image scanning);
- deploy as a canary or in shadow mode (deployment strategies), watch online metrics, then move the
championalias; for high-risk models a human approves in a protected environment.
CT (continuous training): the same pipeline and the same gate, triggered by data or monitoring instead of a code change. A retrained model gets no shortcut to production: it must pass the gate like any other candidate.
Two ML-specific rules run through all three loops. Separate code changes from model changes where you can: a pull request that changes feature code should show its effect on the model (CI can train on a sample and post the metric difference as a comment). And pin what the pipeline consumes: data snapshot, evaluation set and environment, so that a CD run is reproducible.
A workflow in GitHub Actions
A sketch of the CI and CD parts as a GitHub Actions workflow (YAML not executed here; GitHub Actions basics and a full pipeline explain the syntax). The scripts it calls are the project's own: scripts/gate.py is the evaluation gate below, and the data comes from a DVC remote (DVC).
name: risk-model
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "0 3 * * 1" # continuous training: every Monday 03:00 UTC
workflow_dispatch: # manual, or triggered by a drift alert via the API
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install -r requirements.lock
- run: ruff check . && mypy src
- run: pytest -m "not slow" tests/ # units, behaviour, data tests on the sample
- run: python -m src.train --sample 500 --max-iter 5 --out /tmp/smoke # training smoke test
train-and-gate:
if: github.event_name != 'pull_request'
needs: ci
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install -r requirements.lock
- run: dvc pull data/train.parquet.dvc data/eval.parquet.dvc
env: { AWS_ROLE_ARN: "${{ secrets.DATA_ROLE }}" }
- run: dvc repro # validate -> prepare -> train -> evaluate
- run: python scripts/gate.py --champion models:/risk-model@champion --candidate model.pkl
- run: python scripts/register.py --alias challenger # only reached when the gate exits 0
- uses: actions/upload-artifact@v7
with: { name: gate-report, path: gate_report.json }
deploy-canary:
needs: train-and-gate
runs-on: ubuntu-latest
environment: production # required reviewers approve here
steps:
- uses: actions/checkout@v7
- run: ./deploy/canary.sh risk-model@challenger 5 # 5 % of traffic; promotion after watching metricsThings to notice: the same workflow handles pull requests (only ci), merges and the weekly schedule (CT); the training job needs credentials for the data (passed as a secret, never printed), but pull requests from forks do not get secrets, which is one more reason to keep CI on committed samples; the gate is an ordinary step whose exit code decides whether the run continues; and production deployment waits for a reviewer through a protected environment. Larger trainings run on an orchestrator or a training cluster, and the workflow only triggers them and waits.
The evaluation gate as a script
A gate must answer "is the candidate better than the champion by more than the noise, and worse for no one important?" On a fixed evaluation set, a paired bootstrap of the AUC difference gives a confidence interval: resample the evaluation rows with replacement, compute both models' AUC on the same resample, and take percentiles of the difference. The gate passes if the interval's lower bound is above the required gain and no segment drops by more than a tolerance. The example uses 3,000 synthetic rows (2,100 to train, 900 to evaluate), the logistic champion of the running example, and two candidates.
import json
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
def gate(champion, candidate, X, y, segments, min_gain=0.0, max_segment_drop=0.02, n_boot=1000, seed=0):
"""Compare candidate and champion on the same fixed evaluation set. Returns (exit_code, report)."""
pc, pn = champion.predict_proba(X)[:, 1], candidate.predict_proba(X)[:, 1]
rng = np.random.default_rng(seed)
diffs = []
for _ in range(n_boot): # paired bootstrap of the AUC difference
i = rng.integers(0, len(y), len(y))
if y[i].min() == y[i].max():
continue
diffs.append(roc_auc_score(y[i], pn[i]) - roc_auc_score(y[i], pc[i]))
lo, hi = np.percentile(diffs, [2.5, 97.5])
report = {"n_eval": int(len(y)), "auc_champion": round(roc_auc_score(y, pc), 4),
"auc_candidate": round(roc_auc_score(y, pn), 4),
"diff_95ci": [round(float(lo), 4), round(float(hi), 4)], "checks": {}}
report["checks"]["gain: CI lower bound > min_gain"] = bool(lo > min_gain)
for name, mask in segments.items():
drop = roc_auc_score(y[mask], pc[mask]) - roc_auc_score(y[mask], pn[mask])
report["checks"][f"segment {name} (n={int(mask.sum())}) drop <= {max_segment_drop}"] = bool(drop <= max_segment_drop)
report["decision"] = "promote" if all(report["checks"].values()) else "keep champion"
return (0 if report["decision"] == "promote" else 1), report
X, y = make_classification(n_samples=3000, n_features=8, n_informative=5, random_state=0)
X_tr, X_ev, y_tr, y_ev = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
segments = {"f0>1": X_ev[:, 0] > 1.0, "f0<=1": X_ev[:, 0] <= 1.0}
champion = make_pipeline(StandardScaler(), LogisticRegression(C=0.1)).fit(X_tr, y_tr)
candidates = {
"forest": RandomForestClassifier(n_estimators=200, min_samples_leaf=2, random_state=0).fit(X_tr, y_tr),
"logreg C=1": make_pipeline(StandardScaler(), LogisticRegression(C=1.0)).fit(X_tr, y_tr),
}
for name, cand in candidates.items():
code, report = gate(champion, cand, X_ev, y_ev, segments)
print(f"candidate {name}: AUC {report['auc_candidate']} vs champion {report['auc_champion']} "
f"on {report['n_eval']} rows, 95% CI of difference {report['diff_95ci']}")
for check, ok in report["checks"].items():
print(f" {'PASS' if ok else 'FAIL'} {check}")
print(f" decision: {report['decision']}, exit code {code}")
# in CI: json.dump(report, open("gate_report.json", "w")); sys.exit(code)candidate forest: AUC 0.9751 vs champion 0.9532 on 900 rows, 95% CI of difference [0.0135, 0.0317]
PASS gain: CI lower bound > min_gain
PASS segment f0>1 (n=134) drop <= 0.02
PASS segment f0<=1 (n=766) drop <= 0.02
decision: promote, exit code 0
candidate logreg C=1: AUC 0.9533 vs champion 0.9532 on 900 rows, 95% CI of difference [-0.0003, 0.0005]
FAIL gain: CI lower bound > min_gain
PASS segment f0>1 (n=134) drop <= 0.02
PASS segment f0<=1 (n=766) drop <= 0.02
decision: keep champion, exit code 1
The forest's AUC is 0.9751 against the champion's 0.9532 on 900 rows, and the 95 % bootstrap interval of the difference, [0.0135, 0.0317], is clearly above zero; neither segment (134 and 766 rows) gets worse, so the gate promotes it with exit code 0. The second candidate, the same logistic regression with C = 1, scores 0.9533: "higher" by 0.0001, but the interval [-0.0003, 0.0005] contains zero, so the gate keeps the champion and exits with code 1, which stops the workflow. A gate that compared point estimates would have shipped a model change with no evidence of benefit, and every such change carries risk.
The bootstrap here is paired (both models scored on the same resampled rows), which removes most of the noise shared by the two models; for comparing proportions, see testing two proportions. In a real gate add the checks from earlier lessons: behaviour tests, latency and size budgets, calibration, and a minimum segment size so that a 20-row segment does not decide a release.
When to retrain: continuous training triggers
Retraining costs compute and review time, and every new model is a risk. Common triggers, often combined:
- schedule: weekly or monthly; simple and predictable, but blind to sudden change;
- new labelled data: retrain when enough new labels have arrived to matter;
- drift: a data-drift alarm on inputs (Data Drift);
- performance: the champion's metric on recent labelled data drops (Concept Drift and Delayed Labels).
And a guard before any of them: if the new data fails validation, retraining would learn the bug. The policy function below combines these rules (the thresholds are illustrative; Retraining discusses how to choose them).
from dataclasses import dataclass
@dataclass
class State:
days_since_training: int
new_labelled_rows: int
drift_psi: float # largest feature PSI over the last week
live_auc_drop: float # champion's AUC on recent labelled data, versus at deployment
schema_ok: bool
def should_retrain(s, max_age=30, min_rows=5000, psi_alarm=0.2, auc_alarm=0.02):
if not s.schema_ok:
return False, "data failed validation: fix the pipeline, do not retrain on it"
if s.new_labelled_rows < min_rows:
return False, f"only {s.new_labelled_rows} new labelled rows (< {min_rows})"
reasons = []
if s.days_since_training >= max_age: reasons.append(f"schedule ({s.days_since_training} days)")
if s.drift_psi >= psi_alarm: reasons.append(f"drift (PSI {s.drift_psi:.2f})")
if s.live_auc_drop >= auc_alarm: reasons.append(f"performance (AUC -{s.live_auc_drop:.3f})")
return (True, "retrain: " + ", ".join(reasons)) if reasons else (False, "no trigger")
scenarios = {
"quiet week": State(12, 8000, 0.04, 0.003, True),
"monthly schedule": State(30, 21000, 0.05, 0.004, True),
"sudden drift": State(9, 6000, 0.31, 0.011, True),
"drift, few labels": State(9, 1200, 0.31, 0.011, True),
"broken upstream feed": State(15, 9000, 0.85, 0.060, False),
}
for name, s in scenarios.items():
go, why = should_retrain(s)
print(f"{name:21} -> {'RETRAIN' if go else 'wait '} {why}")quiet week -> wait no trigger
monthly schedule -> RETRAIN retrain: schedule (30 days)
sudden drift -> RETRAIN retrain: drift (PSI 0.31)
drift, few labels -> wait only 1200 new labelled rows (< 5000)
broken upstream feed -> wait data failed validation: fix the pipeline, do not retrain on it
A quiet week triggers nothing. The monthly schedule triggers on day 30. Sudden drift (PSI 0.31) triggers after 9 days, but the same drift with only 1,200 new labels waits: a model retrained on too few recent labels could be worse, and the right reaction may be to collect labels faster or fall back to a safe rule. The broken feed shows the most important rule: it has the largest "drift" and performance drop of all, but the data failed validation, so the pipeline must be fixed, not the model retrained. Retraining on broken data is how a data incident becomes a model incident.
Pitfalls
- Retrying a failed gate until it passes. The gate is a statistical test; rerunning it with new seeds until green is p-hacking. Investigate instead.
- An evaluation set that drifts with the candidate. If each retraining also redraws the evaluation set, champion and candidate are never compared fairly. Version the evaluation set and refresh it deliberately, re-scoring the champion on the new one.
- CI that needs production data. Pull requests then either cannot run tests or get secrets they should not have. Commit small, synthetic or anonymised samples for CI.
- Automatic promotion of retrained models without monitoring. CT should end in a canary or shadow phase with rollback, not in an instant swap.
- No owner for a failed CT run. A scheduled retraining that fails silently every week leaves an ever older champion in production; alert on failures and on the champion's age.
Practice
- Which checks belong in CI on a pull request, and which only in the CD run? Give two of each, with the reason.
- The second candidate's AUC was higher than the champion's. Why did the gate reject it, and what would have to change for it to pass?
- A drift alarm fires and CT retrains automatically. The new model passes the gate against the champion on the fixed evaluation set. Can the drift still make the new model worse in production? What step catches that?
Answers
- CI: unit tests of transforms and the training smoke test, because they need no full data and finish in minutes; lint/type checks for the same reason. CD only: full-data validation and full training, and the gate against the champion, because they need the full data, credentials and much more time.
- The bootstrap interval of the AUC difference was [-0.0003, 0.0005], which contains 0: the improvement of 0.0001 is indistinguishable from noise on 900 rows. It would pass only with a real improvement larger than the noise, or with a much larger evaluation set that shrinks the interval (if the improvement is real).
- Yes: the fixed evaluation set reflects the old distribution, so it cannot show how either model does on the drifted data. A canary or shadow deployment with monitoring of live metrics (and, once labels arrive, recent-data evaluation) catches it; the evaluation set should also be refreshed with recent labelled data.
Test yourself
What does continuous training (CT) add to CI/CD for ML?
- Faster unit tests
- Retraining and re-evaluating the model when triggered by schedule, new data, drift or a performance drop, through the same gate and release path
- Automatic code review
- Training on every commit to every branch
Why does a CI job run a training smoke test on a few hundred rows?
- To get the production model
- To check in minutes that the training entry point runs, the loss decreases and the model saves and loads
- To tune hyperparameters
- To measure final accuracy
The gate's 95 % bootstrap interval for the AUC difference was [0.0135, 0.0317]. What does it mean?
- The candidate is worse
- The candidate's improvement is clearly larger than the evaluation noise, so it passes the gain check
- The test is inconclusive
- The champion should be deleted
New data fails validation and also shows strong drift. What should the CT policy do?
- Retrain immediately
- Not retrain; fix the data pipeline first
- Delete the champion
- Lower the gate threshold