Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 15 min · revision 2

Model Registry: Versions, Aliases and Promotion Rules

Register three model versions in the MLflow registry with signatures and lineage tags, serve whatever the champion alias points to, watch the signature reject malformed input, and promote a challenger with an explicit rule (an overall margin plus slice guard-rails, scored on the same evaluation rows) that moves the alias only when every condition holds.

Contentsand lesson path

On this page

  1. Why it matters
  2. Versions with signatures and lineage
  3. Aliases: the name a service loads
  4. Signatures check the input at the door
  5. An explicit promotion rule
  6. Check your understanding
  7. Apply it
  8. Review prompt

Lessons of Experiment Tracking & Reproducibility

  1. Why Results Become Unrepeatable Concept · 15 min
  2. Lab: Track and Compare Runs Lab · 25 min
  3. Versioning Data and Models Next to Code Concept · 20 min
  4. Worked Example: Rebuild Last Month's Model from Scratch Worked example · 25 min
  5. Model Registry: Versions, Aliases and Promotion Rules Concept · 15 min
  6. Check: Can You Reproduce It? Knowledge check · 8 questions

What you will learn

  • Register a model with its signature, metrics and lineage in a model registry and promote it between versions or aliases using an explicit criterion.

01. Why it matters

A tracker records runs, and a run can produce a model. But a service that makes predictions should not load "the model from run 9f3c…", and nobody should decide by hand, from memory, which run is good enough for production. A model registry adds a layer on top of the tracker. Each registered model has a name, such as tumour-model. Each time you register a new model under that name, it gets the next version number, and that version stays linked to the run, data and code that produced it.

Two more ideas make a registry useful. An alias is a movable name for one version, such as champion; a service loads models:/tumour-model@champion, and promotion means pointing the alias at another version. A promotion rule decides when the alias may move, written as code that anyone can rerun. This lesson builds all three with MLflow, using the breast cancer data from scikit-learn, with malignant as the positive class.

Terminal
mkdir registry-demo && cd registry-demo
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "mlflow==3.18.0" "scikit-learn==1.9.1"

02. Versions with signatures and lineage

common.py holds what every script shares: a SQLite store in the folder, which holds the runs and the registry; one fixed split into training rows and 171 evaluation rows that no version is trained on; and the two slices the promotion rule will guard, groups of rows defined by a feature. Here the slices are tumours with cell smoothness below and above the training median; in a product they are often customer segments, regions or device types.

register.py trains one candidate and logs it with a signature, the schema of the model's inputs and outputs. infer_signature reads it from the training columns and from the output of predict_proba. pyfunc_predict_fn="predict_proba" makes the generic loader return probabilities, not class labels. registered_model_name registers the logged model as a new version. Then the script adds version tags for lineage: the candidate, the training data digest, a hash of the code and the training run. The first version ever registered also gets the champion alias.

Python · common.py
"""Shared set-up: a local MLflow store, one fixed split, the slices to guard."""
import logging
import os
import warnings
from pathlib import Path

os.environ.setdefault("MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR", "false")
import mlflow  # noqa: E402
from sklearn.datasets import load_breast_cancer  # noqa: E402
from sklearn.model_selection import train_test_split  # noqa: E402

NAME = "tumour-model"                            # the registered model


def setup():
    logging.getLogger("mlflow").setLevel(logging.ERROR)
    warnings.filterwarnings("ignore", message="Hint: Inferred schema contains integer")
    mlflow.set_tracking_uri("sqlite:///mlflow.db")   # runs and the registry
    if mlflow.get_experiment_by_name("tumour") is None:
        mlflow.create_experiment(
            "tumour", artifact_location=Path("mlartifacts").resolve().as_uri())
    mlflow.set_experiment("tumour")


def split():
    """Train rows for fitting; evaluation rows, never trained on, for promotion."""
    df = load_breast_cancer(as_frame=True).frame
    df["malignant"] = 1 - df.pop("target")       # 1 = malignant
    train, evaluation = train_test_split(df, test_size=0.3, stratify=df["malignant"],
                                         random_state=0)
    return train, evaluation


def slices(X, train):
    """Two slices: cell smoothness below or above the training median."""
    cut = train["mean smoothness"].median()
    return {"low smoothness": X["mean smoothness"] < cut,
            "high smoothness": X["mean smoothness"] >= cut}
Python · register.py
import hashlib
import sys
from pathlib import Path

import mlflow
from mlflow.models import infer_signature
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from common import NAME, setup, split

CANDIDATES = {
    "logreg-C10": lambda: make_pipeline(StandardScaler(),
                                        LogisticRegression(C=10, max_iter=5000)),
    "hist-gbm": lambda: HistGradientBoostingClassifier(random_state=0),
    "logreg-C0.1": lambda: make_pipeline(StandardScaler(), LogisticRegression(C=0.1)),
}

# skops refuses to load these types unless told they come from a trusted source
TRUSTED = ["sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor"]

setup()
key = sys.argv[1]
train, _ = split()
X, y = train.drop(columns="malignant"), train["malignant"]
with mlflow.start_run(run_name=key) as run:
    model = CANDIDATES[key]().fit(X, y)
    dataset = mlflow.data.from_pandas(train, name="tumour-train", targets="malignant")
    mlflow.log_input(dataset, context="training")
    signature = infer_signature(X, model.predict_proba(X))   # input and output schema
    info = mlflow.sklearn.log_model(
        model, name="model", signature=signature, input_example=X.head(3),
        pyfunc_predict_fn="predict_proba",                 # callers get probabilities
        pip_requirements=["scikit-learn==1.9.1", "skops"],
        skops_trusted_types=TRUSTED,
        registered_model_name=NAME)                            # a new registry version

client = mlflow.MlflowClient()
version = info.registered_model_version
code = hashlib.sha256(Path("register.py").read_bytes()).hexdigest()[:12]
for tag, value in {"candidate": key, "train_data_digest": dataset.digest,
                   "code_sha256": code, "training_run": run.info.run_name}.items():
    client.set_model_version_tag(NAME, version, tag, value)   # lineage, per version
if not client.get_registered_model(NAME).aliases:             # first version ever
    client.set_registered_model_alias(NAME, "champion", version)
mv = client.get_model_version(NAME, version)
print(f"{NAME} version {mv.version}: {mv.tags['candidate']}, "
      f"data {mv.tags['train_data_digest']}, aliases {mv.aliases}")
Terminal
python register.py logreg-C10
Expected output
Successfully registered model 'tumour-model'.
Created version '1' of model 'tumour-model'.
tumour-model version 1: logreg-C10, data 5e4f0fae, aliases ['champion']

The first two lines come from MLflow itself. (If an AI coding assistant runs the script, MLflow 3.18 also prints an mlflow.agent.hint line first; MLFLOW_DISABLE_AGENT_HINT=1 hides it.) A version is immutable: its files and signature do not change after registration. To fix a model, you register a new version, so version 1 always means the same thing, which is what makes it safe to write down in an incident report or a rebuild record. Tags, aliases and descriptions can still be edited, because they are metadata about a version.

03. Aliases: the name a service loads

serve.py stands in for a prediction service. It never names a version: it loads models:/tumour-model@champion and reports which version that resolved to. You can also load a fixed version with models:/tumour-model/1, which is what a rebuild or an audit wants.

Python · serve.py
"""Stands in for the service: it always loads what the champion alias points to."""
import mlflow

from common import NAME, setup, split

setup()
version = mlflow.MlflowClient().get_model_version_by_alias(NAME, "champion")
model = mlflow.pyfunc.load_model(f"models:/{NAME}@champion")
_, evaluation = split()
by_size = evaluation.sort_values("mean radius").drop(columns="malignant")
rows = by_size.iloc[[0, 85, 170]]                # smallest, middle, largest radius
print(f"models:/{NAME}@champion -> version {version.version}"
      f" ({version.tags['candidate']})")
print("P(malignant) for 3 rows:", model.predict(rows)[:, 1].round(3).tolist())
Terminal
python serve.py
Expected output
models:/tumour-model@champion -> version 1 (logreg-C10)
P(malignant) for 3 rows: [0.0, 0.001, 1.0]

Older MLflow versions used fixed stages (Staging, Production, Archived) for the same purpose. Stages have been deprecated since MLflow 2.9 in favour of aliases and tags, which you can name to fit your process, for example champion, challenger or shadow. A loaded model stays in memory, so a running service sees a moved alias only when it resolves the alias again, for example on restart or on a scheduled reload.

04. Signatures check the input at the door

When a model has a signature, MLflow's generic loader checks every input against it before the model runs. The script sends three kinds of request to the champion: the right columns in a different order, a request with one column missing, and one with a number sent as text.

Python · signature.py
import textwrap

import mlflow
from mlflow.exceptions import MlflowException

from common import NAME, setup, split

setup()
model = mlflow.pyfunc.load_model(f"models:/{NAME}@champion")
schema = model.metadata.get_input_schema()
print(f"expects {len(schema.input_names())} columns, e.g.",
      [f"{c.name}: {c.type.name}" for c in schema.inputs[:2]])
_, evaluation = split()
X = evaluation.drop(columns="malignant").head(2)
requests = {"columns reordered": X[X.columns[::-1]],
            "one column missing": X.drop(columns="mean radius"),
            "radius sent as text": X.astype({"mean radius": str})}
for label, frame in requests.items():
    try:
        print(f"{label}: accepted, {model.predict(frame)[:, 1].round(3).tolist()}")
    except MlflowException as e:
        reason = str(e).split("Error: ")[-1]          # the last line says why
        print(textwrap.fill(f"{label}: refused, {reason}", 80, subsequent_indent="  "))
Terminal
python signature.py
Expected output
expects 30 columns, e.g. ['mean radius: double', 'mean texture: double']
columns reordered: accepted, [0.0, 0.0]
one column missing: refused, Model is missing inputs ['mean radius'].
radius sent as text: refused, Incompatible input types for column mean radius.
  Can not safely convert str to float64.

Reordered columns are accepted because the signature matches columns by name and puts them back in order, which removes the column-order risk from the first lesson. A missing column and a wrong type are refused with a clear message, instead of a silent wrong prediction or an error deep inside scikit-learn. MLflow also refuses 64-bit integer input, the pandas default, for a double column, because large 64-bit integers cannot always be stored exactly as floats; send floats, or declare such columns as double when you build the signature. Extra columns are ignored with a warning. MLflow's own scoring server, mlflow models serve, applies the same checks; validating input in an API you write yourself is the subject of the serving lab.

05. An explicit promotion rule

Now register two challengers: a histogram gradient-boosting model (version 2) and a more regularised logistic regression (version 3).

Terminal
python register.py hist-gbm
python register.py logreg-C0.1
Expected output
Registered model 'tumour-model' already exists. Creating a new version of this model...
Created version '2' of model 'tumour-model'.
tumour-model version 2: hist-gbm, data 5e4f0fae, aliases []
Registered model 'tumour-model' already exists. Creating a new version of this model...
Created version '3' of model 'tumour-model'.
tumour-model version 3: logreg-C0.1, data 5e4f0fae, aliases []

A promotion rule is explicit when a program can apply it without judgement. promote.py loads the champion and the challenger from the registry and scores both now, on the same 171 evaluation rows, instead of trusting numbers logged at different times on different data. Then decide() applies two conditions, both fixed before anyone looks at the results:

  1. the challenger's overall log loss must be lower by at least MARGIN (0.01), so that a tiny gain that may be noise does not trigger a change;
  2. no slice may get worse by more than GUARD (0.02), so that an overall gain cannot hide a group that the new model serves badly.

Only if both hold does it move champion to the challenger, keeping the old version reachable as previous-champion. Either way, the result is stored as a tag on the challenger, so the registry also remembers why a version was or was not promoted.

Python · promote.py
import sys

import mlflow
from sklearn.metrics import log_loss

from common import NAME, setup, slices, split

MARGIN = 0.01   # the challenger must lower overall log loss by at least this much
GUARD = 0.02    # and must not raise the log loss of any slice by more than this


def score(uri, X, y, groups):
    p = mlflow.pyfunc.load_model(uri).predict(X)[:, 1]
    result = {"overall": log_loss(y, p)}
    for name, mask in groups.items():
        result[name] = log_loss(y[mask], p[mask], labels=[0, 1])
    return result


def decide(champ, chall):
    """The promotion rule as code: a list of reasons to refuse, empty if none."""
    reasons = []
    gain = champ["overall"] - chall["overall"]
    if gain < MARGIN:
        reasons.append(f"overall gain {gain:.3f} < {MARGIN}")
    for name in champ:
        loss = chall[name] - champ[name]
        if name != "overall" and loss > GUARD:
            reasons.append(f"{name} worse by {loss:.3f} > {GUARD}")
    return reasons


setup()
client = mlflow.MlflowClient()
challenger = sys.argv[1]
champion = client.get_model_version_by_alias(NAME, "champion").version
train, evaluation = split()                      # rows no version was trained on
X, y = evaluation.drop(columns="malignant"), evaluation["malignant"]
groups = slices(X, train)
champ = score(f"models:/{NAME}/{champion}", X, y, groups)     # both scored now,
chall = score(f"models:/{NAME}/{challenger}", X, y, groups)   # on the same rows
print(f"log loss, {len(y)} rows    champion v{champion}  challenger v{challenger}")
for name in champ:
    print(f"  {name:17} {champ[name]:13.3f} {chall[name]:13.3f}")
reasons = decide(champ, chall)
client.set_model_version_tag(NAME, challenger, "promotion_check",
                             "; ".join(reasons) or "passed")
if reasons:
    print("REFUSED:", "; ".join(reasons))
else:
    client.set_registered_model_alias(NAME, "previous-champion", champion)
    client.set_registered_model_alias(NAME, "champion", challenger)
    print(f"PROMOTED: champion moves from v{champion} to v{challenger}")
Terminal
python promote.py 2
python promote.py 3
Expected output
log loss, 171 rows    champion v1  challenger v2
  overall                   0.168         0.143
  low smoothness            0.169         0.236
  high smoothness           0.166         0.054
REFUSED: low smoothness worse by 0.067 > 0.02
log loss, 171 rows    champion v1  challenger v3
  overall                   0.168         0.119
  low smoothness            0.169         0.116
  high smoothness           0.166         0.122
PROMOTED: champion moves from v1 to v3

Version 2 lowers the overall log loss by 0.025, more than the margin, but it is much worse on tumours with low smoothness (0.236 against 0.169), so it is refused. Version 3 is better overall by 0.049 and better on both slices, so the alias moves. Run the service again, without changing a line of serve.py, and list the versions.

Python · versions.py
import mlflow

from common import NAME, setup

setup()
client = mlflow.MlflowClient()
for mv in client.search_model_versions(f"name = '{NAME}'",
                                       order_by=["version_number ASC"]):
    aliases = client.get_model_version(NAME, mv.version).aliases
    print(f"v{mv.version} {mv.tags['candidate']:12} aliases {aliases}"
          f"  check: {mv.tags.get('promotion_check', '-')}")
Terminal
python serve.py
python versions.py
Expected output
models:/tumour-model@champion -> version 3 (logreg-C0.1)
P(malignant) for 3 rows: [0.005, 0.09, 1.0]
v1 logreg-C10   aliases ['previous-champion']  check: -
v2 hist-gbm     aliases []  check: low smoothness worse by 0.067 > 0.02
v3 logreg-C0.1  aliases ['champion']  check: passed

06. Check your understanding

Practice check · 3 questions

Versions, tags and rules

Use the scripts and outputs of this lesson.

Q1. A bug fix is ready for version 3, the current champion. A teammate suggests overwriting the files of version 3 so that the version number stays the same. What is the better way?
Q2. `register.py` stores `train_data_digest` as a tag on each version. Why a version tag rather than an alias?
Q3. Version 2 was refused because its low-smoothness slice got worse by 0.067. A teammate proposes raising `GUARD` to 0.07 so that version 2 passes, since it scores best on the other slice. What is the problem?
Practice only: not graded, not saved, not evidence.

07. Apply it

In the practice project, register the best model from your sweep.

  1. Log it with a signature and an input example, register it, and add version tags for the commit, the data hash and the training run.
  2. Write your promotion rule as a function with named thresholds, a margin and at least one slice guard-rail that matters for your data, and commit it before you score any challenger.
  3. Make your serving or batch-scoring code load models:/<name>@champion, then promote a second version with the rule and check that the code picks it up without changes.
  4. Send a request with a missing column and one with a wrong type, and record the errors.

08. Review prompt

Without looking back, explain the difference between a registered model, a version, a tag and an alias, and which of them can change; describe what a signature records and what happens to a request with a missing column, a wrong type or reordered columns; state the two conditions of the promotion rule in this lesson and why both models are scored on the same rows; and say how to undo a promotion.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check