跳到正文

第 12 课 · Models and Signatures

Custom PyFunc Models

Wrap preprocessing, business rules or an LLM chain in a custom MLflow PythonModel, and use models from code to log readable Python files.

Real systems are rarely just a model. You clean the input first, call one or two models, and then apply a rule. A custom pyfunc model packages all of that behind a single predict method.

Subclass PythonModel

Python
import mlflow
import pandas as pd

class RiskModel(mlflow.pyfunc.PythonModel):
    def predict(self, context, model_input, params=None):
        threshold = (params or {}).get("threshold", 0.5)
        score = (10 - model_input["visits"]).clip(lower=0) / 10
        return pd.DataFrame({"score": score, "risk": score > threshold})

with mlflow.start_run():
    info = mlflow.pyfunc.log_model(
        name="risk",
        python_model=RiskModel(),
        input_example=pd.DataFrame({"visits": [2, 9]}),
    )

The important points:

  • predict receives a context and the input. It can also take params. To let callers pass them, include params in the signature.
  • If you need files, such as a saved sub-model or a word list, pass them as artifacts to log_model and read their paths from context.artifacts.
  • Load heavy objects once in the optional load_context method, not inside every predict call.

Models from code

Saving an object with pickle-like tools can be fragile. Models from code saves a readable Python script instead. You write the class in a file and register the object at the bottom:

Python
# file: risk_model.py
import mlflow
from mlflow.models import set_model

class RiskModel(mlflow.pyfunc.PythonModel):
    def predict(self, context, model_input, params=None):
        return [value < 3 for value in model_input]

set_model(RiskModel())

Then log it by passing the file path:

Python
with mlflow.start_run():
    mlflow.pyfunc.log_model(
        name="risk",
        python_model="risk_model.py",
        input_example=[3, 12],
    )

The docs suggest this approach for code-heavy models without large trained weights, such as agents and custom logic. For trained weights, use a built-in flavor, or a pyfunc that loads the weights as artifacts. MLflow runs the script during logging to check it, and it infers requirements from the top-level imports. You can add helper modules with code_paths.

Never hard-code API keys or passwords in a model file. The script is saved as an artifact. Read secrets from environment variables or a secret manager at run time.

Package a pipeline

This stand-in bundles cleaning, scoring and a rule into one object, the same way a custom pyfunc would.

Python Stand-in: preprocessing and a rule behind predict

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.

The same cleaning runs in tests and in production, because it is part of the model. This helps prevent training-serving skew, where the live system prepares data differently from your training code.

Test before you ship

  1. Call predict on the class directly with typical and broken inputs.
  2. Log it, load it with mlflow.pyfunc.load_model, and call it again.
  3. Use the mlflow models predict command to run it in a fresh environment, which finds missing dependencies early.

Type hints

Recent versions can use type hints on predict to validate input. The docs say input hints must be list types, and you should not also pass an explicit signature in that case. Check the current rules before using this.

Using artifacts

Suppose your model needs a vocabulary file. Pass it when logging, and read its path in load_context:

Python
class Tagger(mlflow.pyfunc.PythonModel):
    def load_context(self, context):
        with open(context.artifacts["vocab"], encoding="utf-8") as f:
            self.vocab = set(f.read().split())

    def predict(self, context, model_input, params=None):
        return [sum(word in self.vocab for word in text.split())
                for text in model_input]

with mlflow.start_run():
    mlflow.pyfunc.log_model(
        name="tagger",
        python_model=Tagger(),
        artifacts={"vocab": "vocab.txt"},
        input_example=["a short sample"],
    )

MLflow copies the file into the model folder, so the model does not depend on a path on your laptop. Hard-coded local paths are a classic reason why a model works for its author and fails everywhere else.

Design for failure

A custom model controls how it handles bad input. Decide on purpose:

  • Reject the request with a clear error, when a wrong answer would be harmful.
  • Substitute a default, only when you can justify it and you log that you did.
  • Flag the result, for example with a column that says the input was incomplete.

Silently replacing missing values can hide a broken data pipeline for weeks. If you impute a value, count how often it happens and monitor that count.

Dependencies

MLflow tries to infer the packages that your model needs, but it can miss imports that happen inside functions or conditionally. Check the generated requirements file. You can pass your own list with the pip_requirements argument of log_model, or add extra entries with extra_pip_requirements. Pin versions that you tested.

Keep models small and focused

It is tempting to place business logic, database calls and email sending inside a model. Resist. A model should turn input into output. Side effects such as writing records or sending messages belong in the application around it, where you can add permissions, retries and human approval. A model that only computes is easier to test, and calling it twice causes no harm.

Common mistakes

Do not rely on global variables or on files in your working directory. A model that works in your notebook may fail after loading, because those objects do not travel with it. Put helper code in the class, in code_paths, or in artifacts. Also avoid changing the input table in place, since callers may reuse it after your model returns.

Finally, keep the output stable. If one version returns a list and the next returns a table, every caller must change. Decide on the output shape early and describe it in the signature.

Keep a changelog

Record what each version of your wrapper changed, especially cleaning rules and thresholds. A small change in preprocessing can move predictions as much as a new model, and it should be reviewed and evaluated in the same way.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Where should you load a large file once for a custom model?

    load_context runs when the model is loaded, so the work is not repeated per request.
  2. 2. What does set_model do in a models-from-code file?

    It marks the object in the script that MLflow should use as the model.
  3. 3. Why put preprocessing inside the packaged model?

    The same preparation then runs everywhere the model is used.

Summary

  • Subclass PythonModel to package custom logic behind predict.
  • Use load_context and artifacts for files.
  • Models from code saves readable scripts and uses set_model.
  • Keep secrets out of model files and test in a clean environment.

Next: Model Registry Basics

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