Sub topic 5
Registering a model from a run
This chapter assumes you can train a scikit-learn model and know MLflow Tracking basics: experiments, runs, parameters, metrics, and artifacts. It also assumes you have a tracking server running with a SQL backend store, as set up in the earlier chapter. The Model Registry needs that database. A plain file store is not enough for registry features in a server setup.
By the end you will know two ways to register a model, what each one creates, and which errors to expect.
What registration does
A run can log a model as an artifact. That artifact lives inside the run and has no name beyond its path, such as model. Registration links that artifact to a named entry in the registry.
Registration creates two kinds of record:
- A registered model is the named container, for example
iris-classifier. It is created the first time you register under that name. - A model version is a numbered record inside that container. Each registration adds one version: 1, 2, 3, and so on.
A model version does not copy the model files. It stores a pointer to the source run's artifact, along with the version number, timestamps, tags, and aliases. Because of this pointer, deleting a run or its artifacts can break a registered version. Keep the runs behind versions you care about.
Option 1: register while logging
The simplest path is to pass registered_model_name to log_model. MLflow logs the model in the run and registers it in one call.
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)What happens, in order:
- The run logs the model files under the artifact path
model. - The signature, which records the expected input and output schema, is saved with the model.
- MLflow looks for a registered model called
iris-classifier. If none exists, it creates one. - MLflow creates a new model version that points to this run's
modelartifact.
Run the script twice and you get versions 1 and 2. The name is the only link between them, so a typo creates a new registered model instead of a new version. Define the name once, in a constant or a config file, and reuse it.
The call prints the run ID. Save it. You need it for the second option.
Option 2: register after the fact
Often you do not want to register every run. You train many candidates, compare their metrics, and register only the best. In that case, log without registered_model_name, then register later from the run URI.
A run URI has the form runs:/<run_id>/<artifact_path>. The artifact path must match the one used in log_model, here model.
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
run_id = "<run-id-from-the-previous-step>"
mv = mlflow.register_model(f"runs:/{run_id}/model", "iris-classifier")
client.set_model_version_tag("iris-classifier", mv.version, "validation_status", "passed")
print(mv.name, mv.version)Replace the placeholder with a real run ID before you run this. mlflow.register_model returns a ModelVersion object. Its name and version fields identify the new version. The script then records a validation result as a tag on that version. Tags are covered in the next chapter, and the call is shown here because registering and tagging usually happen together.
Comparing the two options
| Aspect | `registered_model_name` in `log_model` | `mlflow.register_model` |
|---|---|---|
| Calls needed | One | Two: log, then register |
| When you decide | Before the run ends | Any time after the run |
| Typical use | Pipelines where every run is a release candidate | Experiments where you pick the best run |
| Risk | Registry fills with versions you never use | Run must still exist when you register |
If your training script runs many experiments, prefer option 2. A registry full of rejected versions makes it harder to see which ones matter.
Version numbers and what they mean
The registry assigns version numbers itself. You cannot choose them, and they only increase. A few consequences follow:
- Version numbers are not tied to quality. Version 5 is only the fifth registration, and it may be worse than version 3.
- Registering the same run twice creates two versions that point to the same artifact. The registry does not deduplicate.
- Deleting a version does not renumber the others.
Because of this, never treat "the highest version" as "the best version" in serving code. Use an alias for that, which a later chapter covers.
Checking what you registered
After registering, confirm the result instead of assuming it worked. You can look in the MLflow UI under the Models tab, or query it with the client.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
for mv in client.search_model_versions("name='iris-classifier'"):
print(mv.version, mv.run_id, mv.source)Each version shows its run_id and its source, the artifact location it points to. If source is wrong or empty, loading will fail later.
Common errors
- Registry features fail or the Models tab is missing. The server is running with a file-based backend. Restart it with a database backend store such as
sqlite:///mlflow.db. RESOURCE_DOES_NOT_EXISTwhen registering from a run URI. The run ID is wrong, or the artifact path does not match. If you logged tomodel, the URI must end in/model.- A second registered model appears with a slightly different name. Names are exact strings.
iris-classifierandiris_classifierare different models. - Registration works but loading fails later. The run's artifacts were deleted, or the artifact root is not reachable from the machine that loads the model. Check that the server's
--default-artifact-rootis accessible to clients. - No signature on the version. If you omit
signature, the model still registers. Later consumers get no input validation. Always pass a signature.
Summary of the decision
Use registered_model_name when every run should produce a candidate version. Use mlflow.register_model when you want to choose which run becomes a version. In both cases, pass a signature, reuse one name constant, and check the result with search_model_versions.
Exercise
You trained 20 runs and logged each model at artifact path model without registering. Run abc123 has the best validation score. Write the call that registers it as a new version of iris-classifier, and explain what happens if iris-classifier does not exist yet.
Show answer
Call mlflow.register_model("runs:/abc123/model", "iris-classifier"). If no registered model named iris-classifier exists, MLflow creates it and then creates version 1 pointing to run abc123's model artifact. If it already exists, MLflow adds the next version number. No model files are copied.
Exercise
A teammate deletes the run behind version 3 of iris-classifier to save space. What is the likely effect on version 3, and how can you avoid the problem?
Show answer
Version 3 remains listed in the registry, but its source points to artifacts that no longer exist, so loading it fails. Avoid this by not deleting runs or artifacts that back registered versions, and by restricting who can delete runs on shared servers.