Sub topic 2
Registered models and model versions
This chapter covers the two objects the Model Registry is built from, and how they relate to a logged model in a run. It assumes you know MLflow Tracking (experiments, runs, parameters, metrics, artifacts) and can train and save a scikit-learn model. You should also be comfortable with a virtual environment and the command line. The chapter explains the data model only. Later chapters cover registration details, tags, and aliases.
Three objects, three jobs
The registry adds a naming and versioning layer on top of what Tracking already stores. Three things are involved.
- Logged model artifact. This is the set of files written by
mlflow.sklearn.log_model(or another flavor) inside a run. It holds the serialized model, anMLmodelmetadata file, environment files, and the signature. It belongs to one run and is reached through that run. - Registered model. This is a named entry in the registry, such as
iris-classifier. It holds no model files itself. It is a container that groups every version of one logical model, and it carries a description and tags. - Model version. This is one numbered entry under a registered model. It records where its model files come from (the
source), which run produced it (run_id), and its own tags, description, and aliases.
A registered model is the answer to "which model is this?" A model version is the answer to "which build of it?"
What the relationship means in practice
The link from a version to a run is a reference, not a copy. Registering creates a version record whose source points at the artifact location. This has three consequences.
- Many runs can feed one registered model, one run per version. A version's
run_idlets you trace it back to the parameters, metrics, and code state of the run that made it. - The artifact store stays the source of truth for the files. If someone removes a run's artifacts from storage, the version record still exists but cannot be loaded.
- A registered model exists independently of any experiment. Experiments organize runs. Registered models organize deployable candidates. The two do not have to share a name, although matching them is a common convention.
Version numbers are integers starting at 1, assigned by the registry in order of creation. The Python client returns them as strings ("1", "2"), which matters when you compare or sort them. A version number identifies one build permanently. Do not assume a deleted number will be reused, and do not store "latest" as a number in other systems.
The registry needs a database backend
Registered models and versions are stored in the tracking server's backend store. A SQL database (SQLite for local work, PostgreSQL or MySQL for shared use) supports the registry. The plain file-based store used by default for local runs does not give you a registry in a server deployment. The next chapter sets up a server for this. For now, the examples assume a server is running at http://127.0.0.1:5000 with a SQL backend store.
Creating versions
The shortest path creates both objects at once. Passing registered_model_name to log_model creates the registered model if it does not exist and adds a new version each time. The script below runs two training runs, so it produces versions 1 and 2.
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)
for c in (0.1, 1.0):
model = LogisticRegression(C=c, max_iter=200).fit(X, y)
with mlflow.start_run():
mlflow.log_param("C", c)
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=infer_signature(X, model.predict(X)),
registered_model_name="iris-classifier",
)You can also create the registered model first, then attach versions explicitly with the client. This separates "declare the name and its documentation" from "add a build".
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
try:
client.create_registered_model(
"iris-classifier-demo",
description="Iris species classifier used in the registry tutorial.",
)
except MlflowException as e:
if e.error_code != "RESOURCE_ALREADY_EXISTS":
raise
print("Registered model already exists, reusing it.")Registered model names are unique within a registry. Creating the same name twice raises an MlflowException with the error code RESOURCE_ALREADY_EXISTS, which the example above handles. Registering a model under an existing name does not fail. It adds a version, which is why a typo in the name silently creates a second, unwanted registered model.
Inspecting what exists
Use MlflowClient to read the registry. The following script lists every version of one registered model and prints the fields you will use most.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
rm = client.get_registered_model("iris-classifier")
print("Registered model:", rm.name)
print("Description:", rm.description)
versions = client.search_model_versions("name='iris-classifier'")
for mv in sorted(versions, key=lambda v: int(v.version)):
print(
f"version={mv.version} run_id={mv.run_id} "
f"status={mv.status} source={mv.source}"
)
one = client.get_model_version("iris-classifier", "1")
print(one.creation_timestamp, one.tags, one.aliases)Notes on this output:
- Sort with
int(v.version). Sorting the strings directly puts"10"before"2". statusisREADYonce the version has finished being created. A version can briefly showPENDING_REGISTRATIONwhile the registry copies or validates the source, andFAILED_REGISTRATIONif that step failed. Check forREADYbefore you promote anything.sourceis a URI to the model files. Its exact form depends on your MLflow version. In MLflow 2.x it is typically a path under the run's artifact location, and newer releases may point to a separately tracked logged model. Treat it as opaque and use the version identifiers to load models.search_model_versionstakes a filter string. It returns at most a page of results by default, so passmax_resultswhen a model has many versions.
What belongs where
Some information describes the model as a whole, and some describes one build. Putting it in the wrong place makes later automation harder.
| Information | Put it on | Reason |
|---|---|---|
| What the model is for, who owns it | Registered model (description, tags) | True for every version |
| Training parameters, metrics | The run | Already recorded by Tracking, reachable through `run_id` |
| Validation result for one build | Model version (tags) | Differs per version |
| Which version is serving | Alias (later chapter) | A pointer that moves between versions |
Versions are meant to be stable records of what was built. The thing that changes over time is which version is in use, and the registry models that with aliases rather than by editing versions.
Deleting
You can delete a single version with client.delete_model_version("iris-classifier", "2"). You can delete a whole registered model with client.delete_registered_model("iris-classifier"), which removes all of its versions from the registry. Deleting registry entries does not necessarily delete the underlying artifacts in the run. Cleaning up storage is a separate decision. Because these calls remove history that other systems may reference by number, prefer leaving old versions in place unless you have a retention policy.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `RESOURCE_ALREADY_EXISTS` on create | The registered model name is already taken | Catch the error, or call `get_registered_model` first |
| Two similar registered models appear | A typo in `registered_model_name` | Use a shared constant, delete the stray entry |
| Registry calls fail on a local file store | The backend store does not support the registry | Run a server with a SQL `--backend-store-uri` |
| Version loads fail after the run was cleaned up | Artifacts were deleted but the version remains | Keep artifacts for as long as versions reference them |
| Wrong "latest" version chosen | Version strings sorted as text | Convert with `int(...)` before sorting |
Exercise
A teammate says, "I registered the model, so the model files are now stored inside the registered model." Correct this using the terms registered model, model version, and run. Then give one reason it matters.
Show answer
The registered model is only a named container. Each model version is a record that points at model files still stored as artifacts of the run that logged them (its run_id and source). It matters because removing a run's artifacts breaks every version that points at them, even though the registry entries still exist. It also means a version can always be traced back to the run that produced it.
Exercise
You run client.search_model_versions("name='iris-classifier'") and sort the results with key=lambda v: v.version. With 12 versions, the version listed last is "9". What went wrong, and what is the fix?
Show answer
The client returns version numbers as strings, so they sort alphabetically and "9" comes after "12". Sort with key=lambda v: int(v.version).