Sub topic 11
Registering models and using aliases
A logged model is a set of files stored under one run. The Model Registry gives that model a stable name, a version number, and named pointers called aliases, so other code can ask for "the champion" without knowing a run ID.
This chapter assumes you have read the earlier chapters on runs, artifacts and logging models with signatures. It also assumes you have a tracking server running with a SQLite or other database backend, as in the setup chapter.
What the registry adds
A model logged inside a run has a URI such as runs:/<run_id>/model. That URI works, but it has three weaknesses for shared use:
- The run ID says nothing about whether the model is any good.
- A consumer must be told a new run ID every time you retrain.
- Nothing records which model is in production, or which one was there last week.
The registry addresses these with three concepts:
| Concept | What it is | Changes over time? |
|---|---|---|
| Registered model | A name, such as `iris-classifier`, that groups related versions | Rarely |
| Model version | An immutable snapshot numbered 1, 2, 3 and so on, created from a logged model | No |
| Alias | A named pointer such as `champion` that refers to exactly one version | Yes, by design |
A version stores the source run, the model files, the signature, and its own description and tags. You never edit the model inside a version. To change the model, you register a new version.
Prerequisite: a database-backed store
The registry needs a backend store that supports it. A plain local ./mlruns file store does not. The server command from the setup chapter uses sqlite:///mlflow.db, which is enough for learning. Teams usually use PostgreSQL or MySQL.
By default the registry uses the same URI as tracking. If you ever need them apart, mlflow.set_registry_uri(...) overrides it. For this chapter, set only the tracking URI.
Registering a model
There are two ways to create a version.
Register while logging. Pass registered_model_name to log_model. MLflow creates the registered model if the name is new, and otherwise adds the next version.
Register an existing logged model. Call mlflow.register_model with the model's URI. Use this when you decide after the fact that a run's model deserves a version, for example after reviewing it in the UI.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-registry")
X, y = load_iris(return_X_y=True, as_frame=True)
model = LogisticRegression(max_iter=200).fit(X, y)
signature = infer_signature(X, model.predict(X))
# Log without registering.
with mlflow.start_run() as run:
mlflow.sklearn.log_model(model, "model", signature=signature)
# Register the logged model afterwards.
mv = mlflow.register_model(f"runs:/{run.info.run_id}/model", "iris-classifier")
print(mv.name, mv.version)Running this script repeatedly creates version 1, then 2, then 3 of iris-classifier. Each call to register_model makes a new version, even if the files are identical, so register deliberately and not on every training run.
Aliases: named pointers to versions
An alias is a label you attach to one model version. You choose the names. Common choices are champion for the version serving production traffic and challenger for a candidate under evaluation.
The rules to remember:
- An alias points to exactly one version of its registered model.
- One version can carry several aliases.
- Alias names are unique within a registered model. Setting
championon version 3 silently removes it from version 2. - Names that look like version references, such as
latestorv1, are rejected.
Moving an alias is a single call, and it is the whole promotion step. No model files are copied.
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
NAME = "iris-classifier"
def newest_version(name):
versions = client.search_model_versions(f"name='{name}'")
return max(versions, key=lambda v: int(v.version))
candidate = newest_version(NAME)
client.set_registered_model_alias(NAME, "challenger", candidate.version)
challenger = client.get_model_version_by_alias(NAME, "challenger")
print("challenger is version", challenger.version, "from run", challenger.run_id)Notice the max(..., key=int(...)) call. Version numbers are strings, and search_model_versions does not promise any order. The chapter's earlier example took the first result with [0], which works when only one version exists. With several versions it can return the wrong one. Sort explicitly, or in newer releases read the version number from the object that log_model returns.
Loading by alias
Consumers load a model through a models:/ URI. There are two forms:
| URI | Meaning |
|---|---|
| `models:/iris-classifier/3` | Version 3, always |
| `models:/iris-classifier@champion` | Whichever version `champion` points to now |
import mlflow
from sklearn.datasets import load_iris
mlflow.set_tracking_uri("http://127.0.0.1:5000")
X, _ = load_iris(return_X_y=True, as_frame=True)
champion = mlflow.pyfunc.load_model("models:/iris-classifier@champion")
print(champion.predict(X.head(3)))The alias is resolved at the moment you call load_model. The alias is not a live connection. A serving process that loaded champion at 09:00 keeps using that version after someone moves the alias at 10:00, until the process reloads. Plan for that in deployment: restart on a schedule, reload on a signal, or have the serving layer check the alias periodically.
Use the version-number form when you need a result you can reproduce exactly, such as in a test or a report. Use the alias form when the point is to follow whatever is currently approved.
A promotion and rollback workflow
Here is a small, complete workflow. A candidate must pass a check, then it takes over champion. The function returns the previous champion, so you can roll back.
import mlflow
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
NAME = "iris-classifier"
def current_champion_version(name):
try:
return client.get_model_version_by_alias(name, "champion").version
except MlflowException:
return None
def promote(name, version):
previous = current_champion_version(name)
client.set_model_version_tag(name, version, "validated", "true")
client.set_registered_model_alias(name, "champion", version)
if previous is not None:
client.set_registered_model_alias(name, "previous_champion", previous)
return previous
def rollback(name):
previous = client.get_model_version_by_alias(name, "previous_champion")
client.set_registered_model_alias(name, "champion", previous.version)
challenger = client.get_model_version_by_alias(NAME, "challenger")
old = promote(NAME, challenger.version)
print("promoted version", challenger.version, "replacing", old)This design has a few properties worth noting:
- The
validatedtag is metadata on the version. You can filter on it later withsearch_model_versions("tags.validated = 'true'"). previous_championis a convention of this team, not a built-in feature. MLflow only knows that aliases are names.- Rollback is another alias move. Version 3 is not deleted, so you can inspect it afterwards.
Without an alias history, you would need to dig through logs to find what was running before. Writing the old pointer down at promotion time is cheap.
Tags, descriptions and lineage
Every version keeps a link to its source run through run_id and source. From the registry you can reach the parameters, metrics and artifacts that produced the version. From the run you can see which versions were registered from it.
Use tags and descriptions for facts about the version itself:
client.set_model_version_tag(name, version, key, value)for machine-readable facts such asvalidated,data_snapshotorapproved_by.client.update_model_version(name, version, description="...")for a human-readable note.
Keep run-level facts, such as hyperparameters and training metrics, on the run. Keep decisions about the model, such as approval status, on the version.
Aliases instead of stages
Older MLflow tutorials describe model stages named Staging, Production and Archived, with calls like transition_model_version_stage. Stages are deprecated in current MLflow. Aliases replace them for these reasons:
- Stages were a fixed list of names, so every team had to fit its process into the same three labels.
- A stage allowed several versions at once in the same stage, which made "the production model" ambiguous.
- Aliases are free-form names and each points to one version.
If you meet stage-based code, translate Production into a champion alias and Staging into challenger. Loading with models:/name/Production belongs to the old API, so move it to models:/name@champion.
Common errors
- A registry call fails against a file store. The registry needs a database-backed server. Check the tracking URI.
- The wrong version gets the alias. You took
[0]from an unordered search. Sort byint(version). load_modelraises an error saying the alias does not exist. The alias is spelled differently, or it was set on another registered model. Aliases belong to one registered model each.- Production keeps serving the old model after promotion. The process resolved the alias at load time. Reload it.
- A model registers but cannot be loaded for scoring. The environment that loads the model lacks the libraries it was trained with. Check the
requirements.txtstored in the model artifacts. - Dozens of near-identical versions.
registered_model_namewas left in a training script that runs on every experiment. Register only the models that you intend to compare or promote.
Cleaning up
Remove an alias without touching the version:
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
MlflowClient().delete_registered_model_alias("iris-classifier", "challenger")Deleting a model version with delete_model_version or a whole registered model with delete_registered_model is permanent. Aliases that pointed at a deleted version go with it. Ask your team before running either on a shared server.
Exercise
Your serving job loads "models:/iris-classifier@champion" once at startup. You move the champion alias from version 2 to version 3 at noon, but predictions at 12:30 still come from version 2. Explain why, and give two ways to fix it.
Show answer
The alias is resolved only when loadmodel runs. The process loaded version 2 at startup and holds that model in memory, so moving the alias does not change it. Fixes: restart or reload the serving process after each promotion, or have the service poll getmodelversionby_alias periodically and reload when the version number changes. Loading a fixed version number would not fix this, since it removes the alias lookup altogether.
Exercise
A teammate runs "client.searchmodelversions(\"name='iris-classifier'\")[0].version" to find the newest version and then sets the champion alias on it. Last week this picked version 1 when version 4 existed. What is wrong, and what should the code do?
Show answer
The search result has no guaranteed order, so the first element is not necessarily the newest. Also, version is a string, so sorting it as text would place "10" before "9". The code should convert versions to integers and take the maximum, for example max(versions, key=lambda v: int(v.version)).
Exercise
You register version 5 and set the alias challenger on it. Then you run setregisteredmodel_alias for champion on version 5 as well. List the aliases version 5 now has, and say what happens to the version that previously held champion.
Show answer
Version 5 has both challenger and champion, since one version can carry several aliases. The previous champion version loses the champion alias, because an alias name points to only one version in a registered model. That version still exists unchanged.