Sub topic 3
Loading a Model by Alias or Version
This chapter assumes you know Python, MLflow experiments and runs, and MlflowClient. You need a tracking server with a database backend, and a registered model named iris-classifier with at least two versions.
Loading a model by alias or version
Use a models:/ URI. An alias URI follows later promotions. A version URI always loads the same artifact.
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
champion = mlflow.pyfunc.load_model("models:/iris-classifier@champion")
pinned = mlflow.pyfunc.load_model("models:/iris-classifier/1")Serving code should load by alias. Audit and reproduction code should load by version.
Rolling back a bad promotion
Repoint the alias at the previous good version. Serving code that loads @champion needs no change.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
client.set_registered_model_alias("iris-classifier", "champion", "1")Promoting across environments by copying versions
Use copy_model_version when staging and production need separate registered models and separate access rules.
client.copy_model_version(
src_model_uri="models:/iris-classifier-staging@champion",
dst_name="iris-classifier-prod",
)The copy receives a new version number in the destination model. Store the source version in a tag so you can trace it.
Why stages are deprecated and how to migrate
Registry stages such as Staging and Production are deprecated in MLflow 2.9 and later. Replace transition_model_version_stage calls with alias assignments:
- Old:
client.transition_model_version_stage("iris-classifier", 2, stage="Production") - New:
client.set_registered_model_alias("iris-classifier", "champion", "2")
Replace models:/iris-classifier/Production with models:/iris-classifier@champion.
Searching and inspecting registered models
for mv in client.search_model_versions("name='iris-classifier'"):
print(mv.version, mv.run_id, mv.tags)
print(client.get_registered_model("iris-classifier").aliases)Automating promotion gates and controlling access
The open-source registry does not enforce promotion gates. Run the check in a CI job and move the alias only when the check passes:
mv = client.get_model_version_by_alias("iris-classifier", "candidate")
if mv.tags.get("validation_status") == "passed":
client.set_registered_model_alias("iris-classifier", "champion", mv.version)Control access on the tracking server. MLflow's basic authentication can grant read or write permissions per registered model.
Exercise
Exercise
After a rollback moves @champion to version 1, does a serving app that loads models:/iris-classifier@champion need a code change?
Show answer
No. The alias now resolves to version 1, so the app loads version 1 the next time it loads the model.