Sub topic 9
Loading a Model by Alias or Version
This chapter assumes you have registered at least one model version and set an alias on it, as covered in the earlier chapters. It also assumes a tracking server is running at http://127.0.0.1:5000. You should be comfortable with mlflow.set_tracking_uri and MlflowClient.
Registering and promoting only matter if consuming code can find the right model. This chapter covers the models:/ URI, the difference between an alias URI and a version URI, what happens at load time, and the errors you are most likely to hit.
The models:/ URI
A model URI is a string that tells MLflow where a model lives. For registered models there are two common forms:
| URI | Resolves to | Changes when you promote? |
|---|---|---|
| `models:/iris-classifier@champion` | The version the `champion` alias currently points at | Yes |
| `models:/iris-classifier/1` | Version 1 exactly | No |
Registry URIs are not the only form. runs:/<run_id>/model points at a logged model inside a run and bypasses the registry entirely. You used it in the registration chapter as the source for register_model. For serving code, prefer the registry forms, because they go through the governed names and versions.
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")Both calls return a PyFuncModel. The alias form follows later promotions. The version form never changes.
How resolution works
The alias is not stored inside the model. It is a row in the registry database that maps (registered model name, alias) to a version number. Loading goes through these steps:
- The client asks the tracking server which version the alias points at.
- The server returns the model version, including its
source(the artifact location). - The client downloads the model artifacts from that source into a local temporary directory.
- The client reads the
MLmodelfile and builds aPyFuncModelfrom the declared flavor.
The key consequence is timing. The alias is resolved once, at load time. If you promote a new version while a process is running, that process keeps using the model it already loaded. It does not see the change until it loads again.
Loading with the pyfunc flavor
mlflow.pyfunc.load_model is the flavor-neutral loader. It works for scikit-learn, PyTorch, XGBoost, and custom models alike, and it exposes one predict method. That uniformity is why serving code usually uses it.
The loaded object also carries metadata you can use for logging and debugging:
import mlflow
from sklearn.datasets import load_iris
mlflow.set_tracking_uri("http://127.0.0.1:5000")
model = mlflow.pyfunc.load_model("models:/iris-classifier@champion")
print(model.metadata.run_id)
print(model.metadata.signature)
X, _ = load_iris(return_X_y=True)
print(model.predict(X[:5]))The signature printed here is the one you attached when logging the model. Input passed to predict is checked against it. If you send a DataFrame with a missing column or the wrong type, MLflow raises an exception instead of silently returning bad predictions. That check is a main reason to log a signature.
Loading with a native flavor
If you need the original object, such as the scikit-learn estimator with predict_proba, use the flavor's own loader:
import mlflow.sklearn
sk_model = mlflow.sklearn.load_model("models:/iris-classifier@champion")
print(type(sk_model))The models:/ URI works the same way. Only the returned type differs. Use the native loader when you need flavor-specific methods. Use pyfunc when you want a stable interface that does not depend on the framework.
Alias or version: choosing deliberately
Use the alias form when the consumer should always run whatever is currently approved. A batch scoring job or an API service typically loads @champion. Promotion and rollback then become registry operations with no code change or redeploy of the loading code. The reload still has to happen, as described below.
Use the version form when the result must be reproducible. Examples are an evaluation report, a regression test, or an audit of last quarter's predictions. A pinned URI loads the same artifacts regardless of what anyone promotes later.
A useful pattern combines both. Load by alias, then resolve and record the concrete version so every prediction log or metric can be traced to it:
import mlflow
from mlflow import MlflowClient
TRACKING_URI = "http://127.0.0.1:5000"
NAME = "iris-classifier"
ALIAS = "champion"
mlflow.set_tracking_uri(TRACKING_URI)
client = MlflowClient()
version = client.get_model_version_by_alias(NAME, ALIAS).version
model = mlflow.pyfunc.load_model(f"models:/{NAME}/{version}")
print(f"Loaded {NAME} version {version} via alias {ALIAS}")Here the alias is looked up once, and the load uses the version URI. This removes a race. With a plain alias URI, someone could move the alias between your lookup and your load, so the version you logged would not match the model you loaded.
Picking up promotions in a long-running service
A service that loads at startup will not notice a promotion or rollback. There are two common approaches:
- Restart or redeploy the service after changing the alias. This is simple and gives a clear point where the new model takes effect.
- Re-resolve the alias periodically and reload only when the version number changes.
The second approach looks like this:
import time
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
NAME = "iris-classifier"
ALIAS = "champion"
current_version = None
model = None
def refresh():
global current_version, model
latest = client.get_model_version_by_alias(NAME, ALIAS).version
if latest != current_version:
model = mlflow.pyfunc.load_model(f"models:/{NAME}/{latest}")
current_version = latest
print(f"Now serving version {latest}")
for _ in range(3):
refresh()
time.sleep(30)Checking the version number is cheap, because it is one small registry call. The expensive artifact download only happens when the version actually changed. In real code you would run refresh on a timer thread and swap the model reference atomically.
Common errors
The alias does not exist. Loading models:/iris-classifier@champion before any version has that alias raises an MlflowException with error code RESOURCE_DOES_NOT_EXIST. This also happens after delete_registered_model_alias, which is why deleting an alias is a more drastic rollback than repointing it. Check the alias with get_model_version_by_alias first if you want to handle the case gracefully.
Wrong name or case. Registered model names and alias names must match exactly. Champion and champion are different aliases. A typo in the registered model name gives the same does-not-exist error.
Wrong tracking URI. If you forget set_tracking_uri, MLflow uses the local ./mlruns directory, which has no registry entries for this model. The error looks like a missing model, but the real problem is that you are talking to the wrong store. Set the URI explicitly or use the MLFLOW_TRACKING_URI environment variable.
Mixing up @ and /. Use @ before an alias and / before a version number. models:/iris-classifier/champion is read as a stage name, not an alias, and fails or behaves unexpectedly.
Artifact access from the client. The registry only stores a pointer. The client downloads the artifacts from wherever the model was logged. With the server from earlier chapters, whose artifact root is a local folder, loading from a different machine fails because that path does not exist there. Remote clients need a shared artifact store or a server configured to proxy artifacts. This is not a registry bug.
Dependency mismatches. The model is deserialized in your current environment. If the scikit-learn version differs from the one used for training, you can get warnings or load failures. Use mlflow.pyfunc.get_model_dependencies on the model URI to see the recorded requirements before you load.
Where loading fits
Alias loading is the consumer half of the promotion workflow. The producer half registers versions, records validation tags, and moves the alias. Loading is why the alias works as an indirection layer. The consumer names a role (champion), and the registry decides which concrete version fills it. The next chapter uses the same mechanism to roll back by pointing the alias at an earlier version.
Exercise
Your API service starts, loads models:/iris-classifier@champion (version 2), and runs for a week. An engineer then repoints champion to version 1 after a bad promotion. The service still returns version 2 predictions. Why, and what are two ways to fix it?
Show answer
The alias is resolved only when load_model runs, so the running process holds the version 2 model it loaded at startup. Moving the alias in the registry does not push anything to running processes. Fix it by restarting or redeploying the service so it reloads, or by adding a periodic check that calls get_model_version_by_alias, compares the version number with the one currently loaded, and reloads when they differ.
Exercise
A nightly audit job must reproduce last month's scores exactly. Should it load models:/iris-classifier@champion or models:/iris-classifier/<version>, and what should the scoring pipeline record to make that possible?
Show answer
It should load the version URI, because a version never changes while the alias moves with each promotion. The pipeline should record the version number that was used for each scoring run, which it can get from get_model_version_by_alias when the production job resolves the alias. The audit job can then load exactly that version.