TExcelTAD

The Model Registry

An experiment tracker holds hundreds of runs, and a few of them produced models good enough to ship. Which one is in production right now? Which one was in production last Tuesday, when the complaint came in? What data was it trained on, who approved it, and how do we go back to the previous one in two minutes? A model registry answers these questions. It is a catalogue of named models, each with numbered versions, movable aliases that say which version plays which role, and links from every version back to the run, code and data that produced it.

Versions, aliases and lineage

runs (tracker) run a: data d1run b: data d2run c: data d3 risk-model v1 risk-model v2 risk-model v3 versions @champion @challenger serving promote: move @champion to v3rollback: move it back to v2 versions never change; aliases move; serving loads models:/risk-model@champion
  • A registered model is a name for one prediction task (risk-model), not for one algorithm. A logistic regression and a random forest for the same task are versions of the same registered model.
  • A version is immutable: a specific artifact (with its hash), registered from a specific run. Version numbers only grow. Retraining creates a new version; it never overwrites one.
  • An alias is a movable, named pointer to one version: champion (serving), challenger (candidate under evaluation), shadow, previous. Serving code loads risk-model@champion and never names a version number, so promotion and rollback are a change in the registry, not a redeploy of code.
  • Lineage links each version to its run, and through the run to the code version, the data version, the parameters and the metrics (experiment tracking, data versioning). Tags on versions hold the review state (validation_status: approved), the approver, a link to the model card (governance).

Stages versus aliases. Older MLflow (and many tutorials) used fixed stages: every version was in None, Staging, Production or Archived, and promotion was a stage transition. Since MLflow 2.9 stages are deprecated in favour of aliases and tags (MLflow 3.17 still has transition_model_version_stage, with the warning that it "is deprecated since 2.9.0" and that stages will be removed in a future major release): stages were one fixed workflow for every team, allowed only one "Production" meaning, and mixed environment (staging, production) with role. Aliases are free-form, and environment separation is better done with separate registries or model names per environment.

Promotion rules

Moving champion is a deployment decision, so it should follow written rules rather than a feeling, and the rules can be code. A typical promotion gate checks the challenger against the champion on the same, fixed evaluation set that neither was trained or tuned on:

  1. a minimum improvement on the main metric (not just "higher": the difference must exceed the noise of the evaluation set);
  2. no important segment (region, customer type, device) gets worse by more than a tolerance;
  3. same or newer data lineage, and the data passed validation;
  4. operational checks: latency, model size, a valid signature, a security scan of the artifact;
  5. human approval for high-risk models, recorded as a tag.

After the gate, rollout is usually gradual (shadow, canary), and the old champion stays registered so that rollback is an alias move. The same pattern, applied to an online learner's updates, is in Replay Buffers and Rollback.

From scratch: a registry with a promotion gate

A registry in 25 lines: versions stored as pickled bytes with a hash and lineage fields, aliases as a dictionary, and an audit log of every alias move. The champion is the running example's logistic regression; the challenger is a random forest. Both are trained on the same 1,400 rows; the gate uses 600 held-out rows, and a segment (rows whose first feature is above 1.0, 106 of them) stands in for a customer group that must not get worse.

python · try it yourself
import hashlib, pickle
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

class Registry:
    def __init__(self):
        self.models = {}                    # name -> list of versions
        self.aliases = {}                   # (name, alias) -> version number
        self.audit = []                     # who moved which alias when, and why
    def register(self, name, model, **lineage):
        blob = pickle.dumps(model)
        versions = self.models.setdefault(name, [])
        versions.append({"version": len(versions) + 1, "blob": blob,
                         "sha256": hashlib.sha256(blob).hexdigest()[:12], **lineage})
        return len(versions)
    def set_alias(self, name, alias, version, reason):
        old = self.aliases.get((name, alias))
        self.aliases[(name, alias)] = version
        self.audit.append(f"{name}@{alias}: v{old} -> v{version} ({reason})")
    def load(self, uri):                    # "risk-model@champion" or "risk-model/2"
        name, sep, ref = uri.partition("@") if "@" in uri else uri.partition("/")
        v = self.aliases[(name, ref)] if sep == "@" else int(ref)
        return pickle.loads(self.models[name][v - 1]["blob"]), self.models[name][v - 1]

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_eval, y_tr, y_eval = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
reg = Registry()
lineage = {"data_version": "cec5ca7719cc", "code_version": "9e2d41a"}
m1 = make_pipeline(StandardScaler(), LogisticRegression(C=0.1)).fit(X_tr, y_tr)
v1 = reg.register("risk-model", m1, run="logreg-C0.1", **lineage)
reg.set_alias("risk-model", "champion", v1, "first model")
m2 = RandomForestClassifier(n_estimators=200, min_samples_leaf=2, random_state=0).fit(X_tr, y_tr)
v2 = reg.register("risk-model", m2, run="forest-200", **lineage)
reg.set_alias("risk-model", "challenger", v2, "candidate from nightly training")

def promote(reg, name, X, y, segment, min_gain=0.005, max_segment_drop=0.01):
    champ, cinfo = reg.load(f"{name}@champion")
    chall, hinfo = reg.load(f"{name}@challenger")
    auc = lambda m, mask: roc_auc_score(y[mask], m.predict_proba(X[mask])[:, 1])
    everyone = np.ones(len(y), bool)
    a_c, a_h = auc(champ, everyone), auc(chall, everyone)
    s_c, s_h = auc(champ, segment), auc(chall, segment)
    print(f"eval rows {len(y)}, segment rows {segment.sum()}")
    print(f"AUC overall: champion v{cinfo['version']} {a_c:.4f}, challenger v{hinfo['version']} {a_h:.4f}")
    print(f"AUC segment: champion {s_c:.4f}, challenger {s_h:.4f}")
    checks = {"overall gain >= min_gain": a_h - a_c >= min_gain,
              "no segment drop > max": s_c - s_h <= max_segment_drop,
              "same data lineage": cinfo["data_version"] == hinfo["data_version"]}
    for k, ok in checks.items():
        print(f"  {'PASS' if ok else 'FAIL'} {k}")
    if all(checks.values()):
        reg.set_alias(name, "champion", hinfo["version"], f"beat v{cinfo['version']} by {a_h - a_c:.4f} AUC")
    return all(checks.values())

promote(reg, "risk-model", X_eval, y_eval, segment=X_eval[:, 0] > 1.0)
model, info = reg.load("risk-model@champion")
print("serving:", f"v{info['version']}", info["run"], info["sha256"])
print("\n".join(reg.audit))
eval rows 600, segment rows 106
AUC overall: champion v1 0.9398, challenger v2 0.9819
AUC segment: champion 0.9425, challenger 0.9795
  PASS overall gain >= min_gain
  PASS no segment drop > max
  PASS same data lineage
serving: v2 forest-200 85487f5ecaf6
risk-model@champion: vNone -> v1 (first model)
risk-model@challenger: vNone -> v2 (candidate from nightly training)
risk-model@champion: v1 -> v2 (beat v1 by 0.0421 AUC)

The forest wins clearly: AUC 0.9819 against 0.9398 overall on 600 rows, and 0.9795 against 0.9425 on the 106-row segment, so all three checks pass and champion moves to v2. The serving side asks for risk-model@champion and now gets v2, identified by its artifact hash. The audit log keeps every move with its reason, which is what you read during an incident. A real gate would also bootstrap the AUC difference to check it exceeds the noise of 600 rows (here it is large); see comparing models.

The same with the MLflow Model Registry

Recorded with MLflow 3.17.2: both models are logged with registered_model_name="risk-model", which registers each run's model as a new version. Then the aliases are set, a tag marks v2's review state, and the lineage is read back from each version to its run.

python · try it yourself
import logging, os
os.environ["MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR"] = "false"
import mlflow
from mlflow import MlflowClient
logging.getLogger("mlflow").setLevel(logging.ERROR)
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

mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("risk-model")
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_eval, y_tr, y_eval = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

def train_and_register(run_name, model):
    with mlflow.start_run(run_name=run_name):
        mlflow.log_params({"data_version": "cec5ca7719cc", "model": type(model[-1]).__name__})
        model.fit(X_tr, y_tr)
        auc = roc_auc_score(y_eval, model.predict_proba(X_eval)[:, 1])
        mlflow.log_metric("eval_auc", auc)
        info = mlflow.sklearn.log_model(model, name="model", registered_model_name="risk-model",
                                        pip_requirements=["scikit-learn==1.7.0"],
                                        skops_trusted_types=["sklearn.tree._tree.Tree"])  # see below
    return info

train_and_register("logreg", make_pipeline(StandardScaler(), LogisticRegression(C=0.1)))
train_and_register("forest", make_pipeline(RandomForestClassifier(n_estimators=200, min_samples_leaf=2,
                                                                   random_state=0)))
client = MlflowClient()
client.set_registered_model_alias("risk-model", "champion", 1)
client.set_registered_model_alias("risk-model", "challenger", 2)
client.set_model_version_tag("risk-model", 2, "validation_status", "pending")

for mv in sorted(client.search_model_versions("name = 'risk-model'"), key=lambda m: int(m.version)):
    mv = client.get_model_version("risk-model", mv.version)   # search results leave out aliases
    run = client.get_run(mv.run_id)                          # lineage: version -> run -> params, metrics
    print(f"v{mv.version}: run {run.info.run_name!r}, data {run.data.params['data_version']}, "
          f"eval_auc {run.data.metrics['eval_auc']:.4f}, aliases {sorted(mv.aliases)}, tags {mv.tags}")

champ = mlflow.pyfunc.load_model("models:/risk-model@champion")
chall = mlflow.pyfunc.load_model("models:/risk-model@challenger")
print("champion predictions  :", champ.predict(X_eval[:8]).tolist())
print("challenger predictions:", chall.predict(X_eval[:8]).tolist())

# promotion: the challenger passed the gate, so move the alias; serving code keeps loading @champion
client.set_registered_model_alias("risk-model", "champion", 2)
client.set_model_version_tag("risk-model", 2, "validation_status", "approved")
client.delete_registered_model_alias("risk-model", "challenger")
print("after promotion: champion ->", client.get_model_version_by_alias("risk-model", "champion").version)
# rollback is the same operation in reverse
client.set_registered_model_alias("risk-model", "champion", 1)
print("after rollback:  champion ->", client.get_model_version_by_alias("risk-model", "champion").version)
Successfully registered model 'risk-model'.
Created version '1' of model 'risk-model'.
Registered model 'risk-model' already exists. Creating a new version of this model...
Created version '2' of model 'risk-model'.
v1: run 'logreg', data cec5ca7719cc, eval_auc 0.9398, aliases ['champion'], tags {}
v2: run 'forest', data cec5ca7719cc, eval_auc 0.9819, aliases ['challenger'], tags {'validation_status': 'pending'}
champion predictions  : [1, 0, 0, 1, 1, 0, 0, 0]
challenger predictions: [1, 0, 0, 1, 1, 0, 0, 0]
after promotion: champion -> 2
after rollback:  champion -> 1
  • Registering prints Successfully registered model 'risk-model'. and Created version '1', then Created version '2' for the second run: versions are numbered by the registry.
  • Each version knows its run (mv.run_id), so lineage is two calls away: v1 came from run logreg, v2 from forest, both on data cec5ca7719cc, with evaluation AUCs 0.9398 and 0.9819 (the same numbers as the from-scratch version: same data, same split, same models).
  • models:/risk-model@champion and models:/risk-model@challenger load the two versions as generic pyfunc models, the interface a serving process uses. On the first 8 evaluation rows they agree.
  • Promotion is set_registered_model_alias("risk-model", "champion", 2) plus a tag update and removing the challenger alias; rollback is the same call with version 1. Both take effect for any process that resolves the alias on its next load, which is why serving processes should reload on a signal or periodically, and log which version answered each request.

One detail from the run itself: logging the forest first failed with UntrustedTypesFoundException: ... ['sklearn.tree._tree.Tree']. This MLflow version saves scikit-learn models with skops instead of pickle and refuses to save a model it could not safely load back: a tree's node arrays are indexed without bounds checks, so a tampered file could crash the loading process or read memory. Because we trained the model ourselves, the example passes skops_trusted_types=["sklearn.tree._tree.Tree"]. Never extend that list for files from an unknown source; Saving Models explains why loading untrusted model files is dangerous.

Other registries follow the same model with different names: the registries of cloud ML platforms (SageMaker Model Registry with model package groups and approval status, Vertex AI Model Registry with version aliases, Azure ML), Weights & Biases' registry with aliases on artifact versions, and Hugging Face Hub repositories with tags and revisions. A plain bucket with a models/<name>/<version>/ layout and a JSON file of aliases is a registry too, if the rules are enforced.

Pitfalls

  • Serving a version number. Code that loads risk-model/7 must be changed and redeployed to promote or roll back; load an alias.
  • Promotion without a fixed evaluation set. Comparing the champion's months-old score with the challenger's fresh score on different data says nothing. Score both, now, on the same rows.
  • Overwriting a version. Re-registering different bytes under an existing version (possible in home-made registries) destroys the audit trail. Versions are immutable.
  • Registering only the model. A version without its preprocessing, feature list and signature cannot be served correctly; register the whole pipeline object (Model Artifacts, Signatures and Metadata).
  • No retention rule. Registries grow; archive old versions (tags, or deleting their aliases) but keep any version that ever served, for audits and rollback.
  • Anyone can move champion. Restrict who can set production aliases, or let only the CD pipeline do it after the gate (CI/CD and Continuous Training).

Practice

  1. Why is "the challenger's AUC is higher" not enough to promote it? Name two further checks.
  2. In the MLflow example, what has to change in the serving code to roll back from v2 to v1?
  3. A team uses one registered model per algorithm: risk-logreg, risk-forest. What goes wrong when they want to switch production from the logistic regression to the forest?
Answers
  1. The difference may be noise of a small evaluation set, and an overall gain can hide a loss on an important segment. Check that the gain exceeds a minimum (or a bootstrap interval), that no segment drops beyond a tolerance, plus data lineage and operational checks (latency, size, signature).
  2. Nothing: serving loads models:/risk-model@champion. Rollback is set_registered_model_alias("risk-model", "champion", 1); the serving processes pick it up on their next load.
  3. Serving has to change the model name, which is a code or config change and a redeploy rather than an alias move, and the history of "what served this task" is split across two names. One registered model per task, with algorithms as versions, avoids both.

Test yourself

What is a model alias such as champion?

  1. A copy of the model file
  2. A movable named pointer to one immutable version
  3. A new version
  4. A deployment stage that cannot change

In MLflow 2.9 and later, what replaced the fixed stages Staging and Production as the recommended mechanism?

  1. Nothing
  2. Model version aliases (and tags)
  3. Experiments
  4. Run names

Which link lets you find the training data of a registered version?

  1. The alias
  2. The version's source run, whose params or tags record the data version
  3. The model name
  4. The serving logs

Why did saving the random forest with MLflow first fail in the example?

  1. The model was too large
  2. MLflow saved it with skops, which refuses types such as sklearn.tree._tree.Tree unless they are explicitly trusted
  3. Random forests cannot be registered
  4. The tracking URI was wrong