Sub topic 9
Versioning models and using a registry
This chapter assumes you can train a scikit-learn model, use Git, and have read the chapters on experiment tracking and release criteria. It covers what a model version is, what a registry stores, and how to promote a model without breaking the systems that consume it.
Why a model needs its own versioning
Git versions code, and a data tool versions datasets. A trained model is a third artifact. It is a binary file produced by running code on data in a specific environment. Committing the file to Git does not answer the questions a team asks later:
- Which code commit, dataset version and parameters produced this model?
- What metrics did it score before release?
- Which version is serving traffic right now?
- Which version was serving last Tuesday, when the complaints began?
A model version is an immutable, numbered snapshot of a trained model plus the metadata that answers those questions. A model registry is a service that stores these versions, groups them under a named model, and records which version is approved for which use.
What a registry stores
| Element | Meaning | Example |
|---|---|---|
| Registered model | A named family of versions for one task | `iris-classifier` |
| Model version | An immutable artifact with an incrementing number | version 7 |
| Source run | Link to the experiment run that produced it | run ID, parameters, metrics |
| Tags | Free-form key-value facts | `data_version=2026-11-02`, `git_commit=a1b2c3d` |
| Alias or stage | A movable pointer to one version | `champion` points to version 7 |
Two rules follow from this table. First, versions never change after creation. If you retrain, you create version 8. Second, deployment uses pointers, never raw version numbers. Changing which version champion points to is the release, and changing it back is the rollback.
Lifecycle of a version
The states are conventions, and different tools implement them differently. Older MLflow versions had fixed stages (Staging, Production, Archived). Those stages are deprecated in favor of aliases and tags, which let you define names such as champion, challenger or shadow that match your own process.
Registering a model with MLflow
The script below trains a model, logs it, registers it as a new version and records lineage tags. It uses a SQLite backend because the registry needs a database-backed tracking store.
import subprocess
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("iris")
NAME = "iris-classifier"
SEED = 42
C = 1.0
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=SEED
)
try:
commit = subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"], text=True
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
commit = "unknown"
with mlflow.start_run() as run:
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
mlflow.log_param("C", C)
mlflow.log_param("seed", SEED)
mlflow.log_metric("accuracy", accuracy)
mlflow.set_tag("git_commit", commit)
mlflow.set_tag("data_version", "iris-sklearn-builtin")
mlflow.sklearn.log_model(
model, artifact_path="model", registered_model_name=NAME
)
print("run", run.info.run_id, "accuracy", round(accuracy, 3))Each execution of this script adds a new version under iris-classifier. The version links back to the run, so its parameters, metrics and tags are one click away.
Promoting with an alias
Promotion is a decision, and the decision should be code. The next script reuses the release gate from the evaluation chapter. It compares the newest version against the current champion and moves the alias only if the gate passes.
import mlflow
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
mlflow.set_tracking_uri("sqlite:///mlflow.db")
NAME = "iris-classifier"
client = MlflowClient()
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
def accuracy_of(version):
return client.get_run(version.run_id).data.metrics["accuracy"]
versions = client.search_model_versions(f"name='{NAME}'")
candidate = max(versions, key=lambda v: int(v.version))
try:
champion = client.get_model_version_by_alias(NAME, "champion")
baseline = accuracy_of(champion)
except MlflowException:
champion, baseline = None, 0.0 # first release: only the floor applies
if champion is not None and champion.version == candidate.version:
print("Candidate is already the champion.")
elif should_promote(accuracy_of(candidate), baseline):
client.set_registered_model_alias(NAME, "champion", candidate.version)
print("Promoted version", candidate.version)
else:
print("Rejected version", candidate.version)A serving process then loads whatever the alias points to:
import mlflow
mlflow.set_tracking_uri("sqlite:///mlflow.db")
model = mlflow.pyfunc.load_model("models:/iris-classifier@champion")
print(model.predict([[5.1, 3.5, 1.4, 0.2]]))Rollback is a single call: client.set_registered_model_alias(NAME, "champion", previous_version). No retraining and no rebuild are needed.
Common errors
- Overwriting instead of versioning. Saving
model.pklto a shared folder destroys the audit trail. Always create a new version. - Deploying by "latest". The newest version is not necessarily the approved one. Deploy through an alias, so promotion remains an explicit step.
- Registering only the weights. Preprocessing, the feature list and the library versions must travel with the model. Log a full pipeline object, and record the environment through the logged model's dependency files.
- Missing lineage. A version without a git commit and data version cannot be reproduced. Set these tags automatically, as in the script above, and never by hand.
- Comparing metrics from different test sets. If the champion and candidate were scored on different data, the gate compares unlike numbers. Record the evaluation dataset version as a tag, or re-score both on the same data.
- Pickle compatibility. A model serialized with one scikit-learn version may fail or misbehave under another. Pin the versions that were logged with the model.
Decision criteria
A registry adds process, so adopt it when it pays off. A single model retrained quarterly by one person can live with tagged files in object storage. Move to a registry when several people train models, when more than one service consumes them, when you need fast rollback, or when an audit requires proof of what ran in production on a given date.
When you choose a tool, compare four things: whether it supports aliases or custom stages, whether it enforces access control on promotion, whether it records lineage automatically, and whether it integrates with your CI/CD system so the promotion script runs as a pipeline step.
Exercise
A team's serving code loads models:/fraud@champion. Last night a new version 12 was registered, and this morning accuracy dropped in production. Version 11 was the champion until yesterday. What do you do first, and why does the registry make it fast?
Show answer
Check whether the champion alias moved to version 12. If it did, set the alias back to version 11 with set_registered_model_alias("fraud", "champion", 11). Version 11 is an immutable artifact with the same code, data and environment as before, so the rollback needs no retraining or rebuild. Serving picks up the change the next time it resolves the alias. Then investigate version 12 using its linked run, tags and metrics.
Exercise
Why is models:/iris-classifier/latest a poor target for production serving, compared with an alias?
Show answer
"Latest" means the highest version number, not an approved one. Any registration, including a version that failed validation, would immediately change what production serves. An alias moves only when a promotion step deliberately sets it, so the release is an explicit, logged and reversible action.