跳到正文

第 10 课 · Models and Signatures

The MLflow Model Format

See what is inside an MLflow Model folder, how the MLmodel file and flavors work, how to log and load a model, and why loading untrusted models is risky.

A model saved as a single mystery file is hard to reuse. Which library made it? Which versions does it need? An MLflow Model is a folder with a standard layout that answers these questions.

What is inside the folder

File Purpose
MLmodel Required YAML file that describes the model and its flavors
Model data, such as model.skops or model.pkl The saved model itself
requirements.txt, python_env.yaml, conda.yaml Information to rebuild the environment
input_example.json (optional) A sample input, when you provided one

The exact data file names vary by library and version.

Flavors

A flavor is a convention that tells tools how to load a model. Built-in flavors include sklearn, pytorch, tensorflow, keras, xgboost, lightgbm, catboost, onnx, transformers and statsmodels.

The most important is python_function, usually called pyfunc. It is a common interface: whatever library made the model, you can load it and call predict. This is why deployment tools can serve many kinds of models in the same way.

A single model usually has two flavors. A scikit-learn model has the sklearn flavor, which gives you the real scikit-learn object back, and the python_function flavor, which lets you call predict through the generic interface.

An illustrative MLmodel file, shortened and simplified, might look like this:

YAML
flavors:
  python_function:
    loader_module: mlflow.sklearn
  sklearn:
    sklearn_version: "x.y.z"
signature:
  inputs: '[...]'
  outputs: '[...]'

Open the file of your own model to see its real contents.

Log and load

Python
import mlflow
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier

X, y = load_iris(return_X_y=True, as_frame=True)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y)

with mlflow.start_run():
    info = mlflow.sklearn.log_model(
        model,
        name="iris-tree",
        input_example=X.head(3),
        skops_trusted_types=["sklearn.tree._tree.Tree"],  # see below
    )

print(info.model_uri)

generic = mlflow.pyfunc.load_model(info.model_uri)
print(generic.predict(X.head(3)))

native = mlflow.sklearn.load_model(info.model_uri)
print(native.get_depth())

As of MLflow 3.18.0, the scikit-learn flavor saves in the skops format by default (outside Databricks). skops refuses types that it does not trust, and tree-based models, such as decision trees and random forests, contain one: sklearn.tree._tree.Tree. Without skops_trusted_types, saving this model fails. Add a type only for models that you trained yourself or have reviewed, because a damaged or malicious tree can be unsafe to run. Other models may need other types, or none.

In MLflow 3, you pass name= to log_model. Older examples use artifact_path= and URIs such as runs:/<run_id>/model. The newer URI form for a logged model is models:/<model_id>. Use the model_uri returned by log_model instead of building it yourself.

Environment: loading is not installing

mlflow.pyfunc.load_model does not install the dependencies of a model. The environment where you load it must already have compatible packages. In a different environment, you may see import errors or, worse, different behavior. Some command line tools can create environments for you; see serving and deployment.

mlflow.pyfunc.get_model_dependencies(model_uri) returns the local path of a requirements file with the recorded dependencies.

Why a common interface matters

This stand-in shows the flavor idea: two very different objects are wrapped to offer the same predict method.

Python Stand-in: one predict interface for different models

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Security of model files

Several model formats use Python pickle or similar mechanisms. Loading a pickled file can run arbitrary code. Only load models from sources you trust, and restrict who can write to your registry and artifact store.

Save locally without a server

You do not always need a tracking run. Many flavors offer save_model, which writes the folder to a path, and load_model, which reads it back:

Python
mlflow.sklearn.save_model(
    model, "exported_model",
    skops_trusted_types=["sklearn.tree._tree.Tree"],  # for the tree above
)
again = mlflow.pyfunc.load_model("exported_model")

This is handy for a quick experiment or a package that you hand to another system. For team work, prefer log_model, which also records which run and settings produced the model.

Choosing a flavor

Situation A sensible choice
A scikit-learn estimator or pipeline The sklearn flavor
A model from another supported library The flavor of that library
Custom preprocessing or several models A custom pyfunc
An LLM or agent made of Python code Models from code with pyfunc
A format that many runtimes share onnx, if your model converts well

Check the documentation for the current list and any extra requirements, because flavors differ in which features they support.

Check what you saved

After logging, inspect the model folder. In the UI, open the run, then the model. Verify that:

  • The signature lists the right column names and types.
  • The input example looks like real, non-sensitive input.
  • The requirements list contains the libraries you actually use, with versions.
  • The files do not contain secrets.

A dependency that is missing from the list often shows up only in production. Testing in a clean environment finds it much earlier. The custom pyfunc lesson covers that test.

Version drift

A model saved with one library version may not load, or may behave differently, with another. Pickled objects are especially sensitive to this. Keep the environment files, rebuild the environment from them when you load an old model, and retest after upgrading libraries. If a model must live for years, plan to retrain or re-export it rather than trusting that old files will keep working forever.

Common mistakes

Do not copy only the data file, such as the pickle, to another system. Without the metadata and environment files, nobody knows how to load it correctly. Move the whole model folder, or load the model by its URI.

Another frequent surprise is that the native flavor and the pyfunc flavor can offer different methods. For example, a classifier may expose probability methods only through its native object. Check which one your application needs before you design around predict.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does the MLmodel file do?

    It is the metadata file that tells tools how the model can be loaded.
  2. 2. Which interface lets tools call predict on many kinds of models?

    pyfunc provides a standard load and predict interface.
  3. 3. What happens to dependencies when you call load_model?

    Loading does not set up the environment for you.

Summary

  • An MLflow Model is a folder with an MLmodel file, model data and environment files.
  • Flavors describe how to load it, and pyfunc gives a common predict.
  • Use the URI returned by log_model.
  • Treat model files like executable code.

Next: Signatures and Input Examples

你的学习进度保存在此浏览器中,无需账号。