A trained model is an artifact, like a container image: it should be built reproducibly, recorded with everything that made it, tested before it ships, promoted through environments by a gate rather than by hand, and easy to roll back. Experiment tracking records each training run (code commit, data version, parameters, metrics); the model registry holds the versions worth keeping, with their lineage and an alias such as champion that serving follows. This lesson follows one model version from a training run to production, and shows the two failures that registries exist to prevent: a model nobody can reproduce, and a promotion that skipped the gate.
Difficulty: Advanced · Know this first: Lesson 330, Lesson 324
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from a finished training run to the champion alias. It is a worked example, not a measurement. The tracked-record and gate hops are where promotion goes wrong.
Pick how the candidate compares with the champion, and how promotion works. The gate passes only if no important slice is worse than its threshold.
Promoted
Three questions. No score is saved anywhere — this is just you against the material.
Model promotion grows in four levels: reading the registry, tracking every run, gating promotion, and running it as a governed release process.
At the basic level you can say which version is serving, where it came from, and what the previous one was.
Where it breaks: a champion with no run behind it.
Try it: Basic
Which version is in production, and what is the rollback target?
Now do it: Find your champion and its run in the registry.
At the intermediate level no model reaches the registry without a tracked, reproducible run.
Try it: Intermediate
A colleague uploads a model trained in a notebook. What do you ask for?
Now do it: Move one notebook model into a tracked pipeline run.
At the advanced level promotion is a pipeline with a gate, not a click.
Try it: Advanced
Where should the thresholds for the gate come from?
Now do it: Write the gate thresholds for one model.
At the master level model releases are as governed as software releases.
Trade-off: gates and approvals slow urgent fixes; a fast, rehearsed rollback lets you keep the gate and still move quickly.
Try it: Master
An urgent fix must ship today. What keeps it safe without skipping the gate?
Now do it: Time your gate end to end.
Tracking, registering, and promoting with MLflow's client (2.x and later use aliases; the older fixed stages are deprecated). Check the current MLflow documentation for exact signatures.
import mlflow
from mlflow import MlflowClient
mlflow.set_experiment("fraud-scorer")
with mlflow.start_run() as run:
mlflow.log_params({"max_depth": 6, "lr": 0.05, "seed": 7})
mlflow.log_param("dataset_version", "v412")
mlflow.set_tag("git_sha", GIT_SHA)
model = train(...)
mlflow.log_metric("auc", 0.861)
mlflow.sklearn.log_model(model, name="model", signature=signature, # MLflow 3; artifact_path= in 2.x
registered_model_name="fraud-scorer") # creates version 19
client = MlflowClient()
# the gate writes its verdict on the version; promotion checks it
client.set_model_version_tag("fraud-scorer", "19", "gate", "passed")
client.set_registered_model_alias("fraud-scorer", "champion", "19") # promote
# rollback: client.set_registered_model_alias("fraud-scorer", "champion", "18")
model = mlflow.pyfunc.load_model("models:/fraud-scorer@champion") # serving
What a validation gate checks, at minimum:
The same pattern exists in every platform: SageMaker Model Registry (model package groups, approval status), Vertex AI Model Registry (versions and aliases), Azure Machine Learning (registered models with versions and tags), and Databricks with Unity Catalog (MLflow aliases).
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The average went up; one group paid for it.
Only the promotion pipeline can move the champion alias (registry permissions), the gate runs in under 15 minutes so there is no reason to skip it, the new-customer slice has its own threshold, and every promotion is canaried before full traffic.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A virtual environment for Python packages: python3 -m venv ~/mlops && . ~/mlops/bin/activate. Then pip install mlflow scikit-learn.
Type each one, read what it prints, and compare it with the note above it.
Start a local tracking server with a SQLite backend (the registry needs a database).
mkdir -p ~/labs/registry && cd ~/labs/registry
mlflow server --backend-store-uri sqlite:///mlflow.db --port 5000 >server.log 2>&1 &
sleep 8; curl -s -o /dev/null -w "%{http_code}\n" localhost:5000Train, log, and register two versions of a small model.
cat > train.py <<'EOF'
import sys, mlflow
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
mlflow.set_tracking_uri("http://localhost:5000"); mlflow.set_experiment("demo")
X, y = load_breast_cancer(return_X_y=True)
C = float(sys.argv[1])
with mlflow.start_run():
m = LogisticRegression(C=C, max_iter=5000).fit(X[:400], y[:400])
mlflow.log_param("C", C); mlflow.log_metric("auc", roc_auc_score(y[400:], m.predict_proba(X[400:])[:, 1]))
mlflow.sklearn.log_model(m, name="model", registered_model_name="demo-scorer")
EOF
python3 train.py 0.1 && python3 train.py 1.0Promote version 2 by moving the champion alias, then load the model by alias.
python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','2'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"Roll back: move the alias to version 1, and check it.
python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','1'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"
kill %1registry.pyThis program is a tiny model registry: runs record their lineage, registered versions are immutable, a gate compares a candidate with the champion overall and per slice, and promotion and rollback move an alias. It promotes one good candidate, refuses one that is better on average and much worse for new customers, and rolls back. Save it as registry.py, then run it.
# registry.py
RUNS = {
8790: {"commit": "a91f0d", "data": "v398", "seed": 7, "auc": 0.849, "slices": {"returning": 0.861, "new": 0.802}},
8812: {"commit": "4be21c", "data": "v412", "seed": 7, "auc": 0.861, "slices": {"returning": 0.872, "new": 0.799}},
8840: {"commit": "c03e77", "data": "v415", "seed": 7, "auc": 0.866, "slices": {"returning": 0.889, "new": 0.621}},
}
GATE = {"min_overall_gain": 0.0, "max_slice_drop": 0.01}
versions, aliases, log = {}, {}, []
def register(run_id):
v = len(versions) + 1
versions[v] = {"run": run_id, **RUNS[run_id]} # immutable from now on
return v
def gate(candidate, champion):
c, b = versions[candidate], versions[champion]
reasons = []
if c["auc"] - b["auc"] < GATE["min_overall_gain"]:
reasons.append(f"overall {c['auc'] - b['auc']:+.3f}")
for name, score in c["slices"].items():
drop = b["slices"][name] - score
if drop > GATE["max_slice_drop"]:
reasons.append(f"slice '{name}' {-drop:+.3f}")
return reasons
def promote(candidate):
champion = aliases.get("champion")
reasons = gate(candidate, champion) if champion else []
if reasons:
log.append(f"v{candidate} REFUSED: " + "; ".join(reasons) + f" (champion stays v{champion})")
return
aliases["champion"] = candidate
if champion:
aliases["previous"] = champion
r = versions[candidate]
log.append(f"v{candidate} is champion (run {r['run']}, commit {r['commit']}, data {r['data']}, seed {r['seed']})")
def rollback():
aliases["champion"], aliases["previous"] = aliases["previous"], aliases["champion"]
log.append(f"rollback: champion is v{aliases['champion']} again")
v1, v2, v3 = register(8790), register(8812), register(8840)
promote(v1)
promote(v2)
promote(v3)
rollback()
print("\n".join(log))
print("aliases:", aliases)
print("versions are unchanged:", {v: versions[v]["run"] for v in versions})
Run it, and you should see this output:
$ python3 registry.py
v1 is champion (run 8790, commit a91f0d, data v398, seed 7)
v2 is champion (run 8812, commit 4be21c, data v412, seed 7)
v3 REFUSED: slice 'new' -0.178 (champion stays v2)
rollback: champion is v1 again
aliases: {'champion': 1, 'previous': 2}
versions are unchanged: {1: 8790, 2: 8812, 3: 8840}
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/model-registry-and-promotion && cd ~/labs/model-registry-and-promotion) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Model Registry and Promotion: Tracking, Validation Gates, and Rollback", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Start a local tracking server with a SQLite backend (the registry needs a database).'
'Train, log, and register two versions of a small model.'
'Promote version 2 by moving the champion alias, then load the model by alias.'
'Roll back: move the alias to version 1, and check it.'
)
step_1() {
mkdir -p ~/labs/registry && cd ~/labs/registry
mlflow server --backend-store-uri sqlite:///mlflow.db --port 5000 >server.log 2>&1 &
sleep 8; curl -s -o /dev/null -w "%{http_code}\n" localhost:5000
}
step_2() {
cat > train.py <<'EOF'
import sys, mlflow
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
mlflow.set_tracking_uri("http://localhost:5000"); mlflow.set_experiment("demo")
X, y = load_breast_cancer(return_X_y=True)
C = float(sys.argv[1])
with mlflow.start_run():
m = LogisticRegression(C=C, max_iter=5000).fit(X[:400], y[:400])
mlflow.log_param("C", C); mlflow.log_metric("auc", roc_auc_score(y[400:], m.predict_proba(X[400:])[:, 1]))
mlflow.sklearn.log_model(m, name="model", registered_model_name="demo-scorer")
EOF
python3 train.py 0.1 && python3 train.py 1.0
}
step_3() {
python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','2'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"
}
step_4() {
python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','1'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"
kill %1
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
curl, kill, mkdir, cat, cd, Redirection, If...Else, Here documents.Your company has 25 models in production, half trained in notebooks and deployed by copying files. Design the tracking, registry, and promotion process.
What must every run record? Which models are registered, and how do versions link to data and code? What does the gate check, and who sets thresholds? How does serving load models, and how is rollback done? Who may promote, and what is recorded?
Say 25 models, 4 retrains a week each, 3 environments, and 2 regressions reached production last quarter.
A tracker and registry (MLflow or the cloud equivalent) shared by all teams; training only in pipelines from a commit and a dataset version; registration from the pipeline with the signature and lineage; a gate job with per-model thresholds in Git (holdout, slices, fairness, latency); staging soak with replayed traffic; aliases champion and challenger, moved only by the pipeline; approvals and model cards for consequential models; serving by alias with canary rollout; rollback rehearsed monthly.
A gate and approvals add an hour to an urgent release and catch the regressions that averages hide; moving every team onto pipelines costs a quarter of migration and removes "nobody can rebuild it"; strict registry permissions annoy people until the first audit.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| A model nobody can rebuild | Hop 2: Tracked record | Breaks | The champion has a model file and an accuracy number in a slide. No commit, no data version, no parameters. When a bug in a feature needs a retrain, nobody can reproduce the champion to compare against. |
| The gate was skipped | Hop 4: Validation gate | Breaks | The release is urgent, so the gate is skipped and v19 is promoted directly. Overall AUC is better, but v19 was trained on a dataset where new customers were under-sampled, and on that slice it is 18 points worse. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.