Sub topic 2
Registering a model from a run
This chapter assumes you know MLflow Tracking (experiments, runs, parameters, and artifacts), can train a scikit-learn model, and can start a tracking server with a database backend. You will register a model, document its versions, and point a champion alias at the version you want to serve.
Registering a model from a run
A run is one logged training session. Passing registered_model_name to log_model creates the registered model on the first run and adds a new version on each later run. The registry stores a reference to the logged artifact, not a second copy of it.
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-classifier")
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=200).fit(X, y)
with mlflow.start_run() as run:
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=infer_signature(X, model.predict(X)),
registered_model_name="iris-classifier",
)
print(run.info.run_id)To register an existing run later, call mlflow.register_model("runs:/<run_id>/model", "iris-classifier").
Documenting versions with descriptions and tags
A description explains what a version is. A tag stores a machine-readable fact, such as a validation result, that gates promotion.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
client.update_model_version("iris-classifier", "2", description="Retrained on full Iris data.")
client.set_model_version_tag("iris-classifier", "2", "validation_status", "passed")Aliases: named pointers to versions
An alias is a name, such as champion, that points to one model version. Code loads models:/iris-classifier@champion, so moving the alias changes the served model without editing that code. Registry stages are deprecated, so use aliases for new work.
Promoting a version to champion
Promotion means moving the alias to the version that passed validation.
client.set_registered_model_alias("iris-classifier", "champion", "2")
mv = client.get_model_version_by_alias("iris-classifier", "champion")
print(mv.version)Exercise
Version 2 is promoted to champion, and you find a bug. What single call restores version 1 as champion, and does the serving code need to change?
Show answer
Call client.set_registered_model_alias("iris-classifier", "champion", "1"). The serving code does not change, because it loads models:/iris-classifier@champion, which now resolves to version 1.