Register models and promote with aliases
In this task you'll give models version numbers and choose which one is live by moving a name, not by copying files.
A model registry keeps every registered model with a version number and links back to the run (settings, scores, data) that made it. Apps never ask for version 7; they ask for an alias such as @champion. Promoting a model, or rolling back, is just moving the alias to another version.
This track uses two aliases: @challenger for the newest candidate and @champion for the model in use. promote.py scores both on the same holdout data and moves @champion only if the challenger is better by a margin.
Model files can carry code. MLflow 3 saves scikit-learn models with skops, which refuses types it can't check; tree models (random forests) need their tree type named as trusted, which you should only do for models you trained yourself.
Example. Fernhill Cloud's ticket-routing model was deployed by copying a file to a server, and nobody could say which training run it came from. With a registry and aliases, the app loads models:/ticket-router@champion, and a rollback is one command that moves the alias back.
Before you start
You need: Python 3.10 or newer, and about 500 MB of disk for MLflow and scikit-learn. No cloud account. Time: 30 minutes.
Where to look
- MLflow UI
- Models
- delivery-late
- Versions and aliases
Steps
- Register a model:
python train.py --register. It printsregistered delivery-late version 1 as @challenger. - Save
promote.pyfrom Commands and runpython promote.py. With no champion yet, version 1 is promoted.The script scores on data/holdout.csv, which no model trains on. - Register a forest:
python train.py --algo forest --register, thenpython promote.pyagain. The forest scores a little higher but not by the 0.005 margin, so version 1 stays champion.A margin stops models swapping back and forth on noise. - Open the MLflow UI, choose Models, then delivery-late: see both versions and where each alias points.
- Roll back by hand (for practice):
python -c "import mlflow; mlflow.set_tracking_uri('sqlite:///mlflow.db'); mlflow.MlflowClient().set_registered_model_alias('delivery-late','champion','1')".
Commands
# promote.py: compare @challenger with @champion on the same holdout data, and move @champion only if it's better.
import argparse
import mlflow, pandas as pd
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
from sklearn.metrics import roc_auc_score
p = argparse.ArgumentParser()
p.add_argument("--holdout", default="data/holdout.csv")
p.add_argument("--margin", type=float, default=0.005, help="how much better the challenger must be")
a = p.parse_args()
NAME = "delivery-late"
mlflow.set_tracking_uri("sqlite:///mlflow.db")
client, df = MlflowClient(), pd.read_csv(a.holdout)
X, y = df.drop(columns="late"), df["late"]
def score(alias):
try:
version = client.get_model_version_by_alias(NAME, alias).version
except MlflowException:
return None, None
model = mlflow.sklearn.load_model(f"models:/{NAME}@{alias}")
return version, roc_auc_score(y, model.predict_proba(X)[:, 1])
cv, cauc = score("challenger")
pv, pauc = score("champion")
if cv is None:
raise SystemExit("No @challenger to compare. Run train.py --register first.")
print(f"challenger v{cv}: auc {cauc:.4f}" + (f" champion v{pv}: auc {pauc:.4f}" if pv else " no champion yet"))
if pv is None or cauc >= pauc + a.margin:
client.set_registered_model_alias(NAME, "champion", cv)
print(f"PROMOTED: @champion now points at version {cv}")
else:
print(f"KEPT: version {pv} stays @champion (the challenger isn't at least {a.margin} better)")
# Register, compare, promote
python train.py --register
python promote.py
python train.py --algo forest --register
python promote.py
Watch out for
- Cost
- Free.
- Security
- Only trust model files from your own registry; in a shared registry, limit who can register and who can move @champion.
- Common mistakes
- Apps loading a fixed version number, so promotions never reach them, and comparing models on different test data.
Clean up
Keep the mlops folder for the next tasks in this section; delete it (and its .venv) at the end.
Words to know
- Model registry
- A store of model versions linked to the runs that made them.
- Alias
- A movable name such as @champion that points at one version.
- Holdout set
- Data kept aside for comparing models fairly.
- Champion and challenger
- The model in use, and a new one that must beat it.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands OnKeep going
- MLOps roadmap: what to learn, in what orderExplained
- Versioning data and modelsExplained
- Model registry: versions, aliases and promotionExplained
- Stop weak models with a quality gatePrevious in MLOps in depth
- Score a file of records in a batchNext in MLOps in depth
- AI agents and MLOpsAll pages in this topic