Sub topic 9
Logging models with signatures
This chapter assumes you can log parameters and metrics inside a run and can open the MLflow UI. It also assumes you know what an artifact is and have trained a scikit-learn model. By the end you will be able to log a model with a signature and an input example, and load it back. You will also be able to read the errors that schema enforcement raises.
Why a model is more than a pickle file
You could save a trained model with joblib.dump and log the file as an artifact. That works, but the file alone doesn't tell the next person three things:
- Which libraries and versions are needed to load it.
- Which columns it expects, and in what types.
- How to call it without knowing it is a scikit-learn object.
mlflow.<flavor>.log_model answers these questions. It writes a directory of files into the run's artifact store. The directory holds the serialized model and a description of how to load and call it.
A typical model directory looks like this:
| File | Purpose |
|---|---|
| `MLmodel` | YAML metadata: flavors, signature, MLflow version, creation time |
| `model.pkl` | The serialized estimator (the file name depends on the flavor) |
| `requirements.txt`, `conda.yaml`, `python_env.yaml` | The environment needed to load the model |
| `input_example.json` | A small sample input, if you provided one |
The exact file list varies with the flavor and the MLflow version.
Flavors and the pyfunc interface
A flavor is a way of reading the saved model. The scikit-learn model above is saved with the sklearn flavor, so you can load it as a real LogisticRegression with mlflow.sklearn.load_model. Every flavor also exposes a generic python_function (pyfunc) flavor. It offers one interface, predict(data), whatever library produced the model.
Pyfunc is what deployment tools use. A serving tool doesn't need to know whether the model came from scikit-learn, XGBoost or PyTorch. It calls predict.
What a signature is
A model signature describes the model's inputs and outputs. It is stored in the MLmodel file. It lists each input column with a name and a data type, and does the same for the output. Optionally it also lists parameters, which are extra arguments passed at prediction time.
A signature does three jobs:
- It documents the model. The UI shows the expected columns on the model's page.
- It enables schema enforcement. When you call
predicton a pyfunc model, MLflow checks your data against the signature before the model sees it. - It gives downstream tools, such as the Model Registry and serving, a contract to rely on.
There are two kinds of schema:
- Column-based schemas use
ColSpec, one entry per named column with a type such asdouble,long,stringorboolean. They fit tabular data in a pandas DataFrame. - Tensor-based schemas use
TensorSpec, which gives a NumPy dtype and a shape. A dimension of-1means any size. They fit arrays and images.
Inferring a signature
The usual way to get a signature is infer_signature. You give it example inputs and example outputs, and it reads the types from them.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True, as_frame=True)
model = LogisticRegression(max_iter=200).fit(X, y)
predictions = model.predict(X)
signature = infer_signature(X, predictions)
print(signature)Because X is a DataFrame, the inferred input schema is column-based. It has four double columns named after the iris features. The predictions are a 1-D NumPy array of integers, so the output schema is a tensor of int64 with shape (-1,).
The most common mistake is to infer from the wrong objects. If you pass X.values instead of X, you lose the column names and get a tensor schema. Then the model's input contract no longer says which feature is which. Pass the same kind of object your users will pass at prediction time.
Logging the model with the signature and an input example
Pass the signature to log_model inside a run. Add an input_example too, which is a few real rows saved next to the model.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True, as_frame=True)
model = LogisticRegression(max_iter=200).fit(X, y)
signature = infer_signature(X, model.predict(X))
mlflow.set_experiment("iris-model-logging")
with mlflow.start_run(run_name="logreg-with-signature") as run:
info = mlflow.sklearn.log_model(
model,
"model",
signature=signature,
input_example=X.head(3),
)
print("run id:", run.info.run_id)
print("model uri:", info.model_uri)The input example serves two purposes. It shows other people what valid input looks like. MLflow can also use it to infer a signature if you leave signature out, and in recent versions it validates that the model can run on the example when it is logged. Still, pass the signature explicitly, so that the contract is visible in your code and doesn't depend on a default.
> A version note for the code above: newer MLflow releases prefer a name argument over the positional artifact path, and the older form may print a deprecation warning. The returned info.model_uri works in both cases, so use it instead of building the URI by hand.
What happens when you call log_model
The model directory goes to the artifact store, the same place as other artifacts. The tracking server only keeps the run's metadata and the artifact location. If your client can't reach the artifact store (for example, a local ./mlartifacts path that exists only on the server's machine), log_model fails even though log_metric worked. Metrics go through the server, while artifacts may be written directly by the client, depending on how the server is configured.
Loading the model back
You refer to a logged model by URI. The two forms you will use are:
runs:/<run_id>/model, which points at the artifact path inside a specific run.models:/<name>@<alias>, which points at a registered model. The next chapter covers it.
import mlflow
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True, as_frame=True)
run_id = "PASTE_YOUR_RUN_ID_HERE"
loaded = mlflow.pyfunc.load_model(f"runs:/{run_id}/model")
print(loaded.metadata.signature)
print(loaded.predict(X.head(3)))mlflow.pyfunc.load_model returns a PyFuncModel wrapper, not the scikit-learn object. The wrapper holds the signature in loaded.metadata.signature and applies schema enforcement on every predict call. If you need scikit-learn methods such as predict_proba, load with mlflow.sklearn.load_model instead. That path returns the native estimator and skips enforcement.
Schema enforcement and its errors
Enforcement checks three things, in this order:
- All required columns are present.
- Each column's type can be converted to the declared type without losing information.
- For tensor inputs, the shape and dtype match.
Here is what a missing column looks like:
import mlflow
from mlflow.exceptions import MlflowException
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True, as_frame=True)
loaded = mlflow.pyfunc.load_model("runs:/PASTE_YOUR_RUN_ID_HERE/model")
bad = X.head(3).drop(columns=[X.columns[0]])
try:
loaded.predict(bad)
except MlflowException as err:
print(err)The message states that the model is missing inputs and names the column. This failure is deliberate. Without enforcement, scikit-learn would raise a less helpful error, or in some models would silently use the columns in the wrong order.
Common signature problems
- Integer columns with missing values. pandas stores an integer column that contains
NaNas float. If you infer the signature from clean data, the column islong. In production, a batch with a missing value arrives as float, and MLflow refuses the conversion from float to integer. If a column can ever contain missing values, cast it tofloat64before you infer the signature, and keep that cast in your preprocessing. - Wrong type at serving time. JSON clients often send
1where the model declareddouble, or1.0where it declaredlong. Widening an integer to a float is generally accepted. Narrowing a float to an integer is rejected. When you design the signature, choose the type that the callers can actually produce. - Signature inferred from the wrong stage. If your pipeline scales or encodes features inside the model, infer from the raw input. If preprocessing happens outside the model, the signature describes the processed data, and every caller must repeat that preprocessing. Decide which one you mean and log the preprocessing as part of the model (for example, a scikit-learn
Pipeline) when callers should send raw data. - Tensor shape mismatch. A signature inferred from a batch of 32 images records
-1for the batch dimension, so any batch size works. The remaining dimensions are fixed, so an image of a different size is rejected. - A hand-written signature that drifts. If you build a signature manually and later add a feature, the signature still lists the old columns. Prefer
infer_signatureover a hand-written signature, so the schema follows the code.
When inference doesn't give what you want, you can declare the signature yourself:
from mlflow.models import ModelSignature
from mlflow.types.schema import ColSpec, Schema
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True, as_frame=True)
input_schema = Schema([ColSpec("double", name) for name in X.columns])
output_schema = Schema([ColSpec("long")])
signature = ModelSignature(inputs=input_schema, outputs=output_schema)
print(signature)A manual schema is useful when you want a column to be optional or want to widen a type on purpose, for example declaring double where the sample data happened to hold only whole numbers.
Reproducing the environment
MLflow records the Python packages it detects while logging, in requirements.txt and the related files. The detection looks at what your code imported when it saved the model. It can miss packages that load only at prediction time. If your model depends on a custom module, check the recorded requirements before you rely on them. You can override them with the pip_requirements or extra_pip_requirements arguments of log_model.
Summary
log_modelstores a model directory in the artifact store: the model, its environment and its metadata.- A signature declares the input and output schema.
infer_signature(X, predictions)builds it from real objects. input_examplerecords sample input that shows callers what valid data looks like.mlflow.pyfunc.load_modelenforces the signature on every call.mlflow.sklearn.load_modeldoes not.- The usual failures are missing columns, integer columns that meet missing values, and a signature inferred from the wrong object.
Exercise
You infer a signature from a DataFrame in which the column "age" is an integer with no missing values. In production a batch arrives with a missing age, and pandas converts the column to float. What happens at predict time, and what should you have done when logging the model?
Show answer
The signature declares "age" as long, and MLflow refuses to convert float values to an integer type, so predict raises an MlflowException about incompatible input types. When logging, cast "age" to float64 (and handle the missing values in preprocessing) before calling infer_signature, so the schema declares double.
Exercise
A teammate loads your model with mlflow.sklearn.load_model and passes a NumPy array with the columns in the wrong order. The call succeeds and returns wrong predictions. Why did no error occur, and how would you make this mistake fail loudly?
Show answer
mlflow.sklearn.loadmodel returns the native scikit-learn estimator, which doesn't apply the signature, and a NumPy array carries no column names to check. Loading with mlflow.pyfunc.loadmodel and passing a DataFrame makes MLflow enforce the signature, so missing or mistyped columns raise an error. Logging a signature inferred from a DataFrame, and a Pipeline that selects columns by name, also makes the contract explicit.