Skip to main content

Package your model for Model Serving

Package a custom Python model with MLflow, including its preprocessing code and its artifacts, and deploy it to a Model Serving endpoint. This page covers writing an MLflow pyfunc model, logging it with its code and files, and registering it for serving.

MLflow's pyfunc flavor can package any Python code or Python model. Use a custom pyfunc model when:

  • Your model requires preprocessing before inputs can be passed to the model's predict function.
  • Your model framework is not natively supported by MLflow.
  • Your application requires the model's raw outputs to be post-processed for consumption.
  • The model itself has per-request branching logic.
  • You are looking to deploy fully custom code as a model.

If your model uses a framework that MLflow supports natively, log it with that framework's flavor instead. For the native flavors, see Custom models overview.

Requirements​

  • MLflow 3 or above, for the name argument of log_model() in the examples.

Write a custom pyfunc model​

MLflow lets you log Python code with the custom Python models format. To package arbitrary Python code with MLflow, implement predict. Optionally, implement load_context to load artifacts one time when the model loads.

  • predict runs on every request. Put the logic that handles each input here.
  • load_context runs one time, when the model loads. Put anything the model needs here, so that each request doesn't reload it.

The following example loads its weights and tokenizer in load_context, and runs preprocessing and postprocessing in predict. It imports CustomTokenizer from preprocessing_utils/my_custom_tokenizer.py, in a preprocessing_utils folder that you create.

Python
import mlflow
import torch


class CustomModel(mlflow.pyfunc.PythonModel):
def load_context(self, context):
self.model = torch.load(context.artifacts["model-weights"])
from preprocessing_utils.my_custom_tokenizer import CustomTokenizer
self.tokenizer = CustomTokenizer(context.artifacts["tokenizer_cache"])

def format_inputs(self, model_input):
# Replace this with your own input formatting. Return the formatted inputs.
return model_input

def format_outputs(self, outputs):
predictions = (torch.sigmoid(outputs)).data.numpy()
return predictions

def predict(self, context, model_input):
model_input = self.format_inputs(model_input)
outputs = self.model.predict(model_input)
return self.format_outputs(outputs)

Running the cell defines CustomModel. Create an instance with CustomModel() when you log the model.

note

Verify that the model can be served before you deploy it. See the MLflow documentation for how to use mlflow.models.predict to validate models before deployment. For the Databricks steps, see Validate before deploying to Model Serving.

Log the model with its code and artifacts​

important

Databricks Runtime ML runtimes include mlflow-skinny by default rather than the full mlflow package. When you log a pyfunc model on one of these runtimes without specifying pip_requirements, MLflow captures mlflow-skinny in the model's conda.yaml. Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise. Always specify mlflow==<version> in pip_requirements when you call mlflow.pyfunc.log_model() on a Databricks Runtime ML runtime:

Python
# DBR ML ships with mlflow-skinny by default, so specify mlflow explicitly
# to ensure Model Serving compatibility.
mlflow.pyfunc.log_model(
name="model",
python_model=your_model,
pip_requirements=["mlflow==3.8.1"], # use mlflow, not mlflow-skinny
registered_model_name="catalog.schema.model_name",
)

Use code_paths to log shared modules of code from your organization with the model. Code from these paths is available in the loaded context of the model, and other custom pyfunc models can use it.

To log the model with its shared code and the artifacts it loads, run the following:

Python
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=CustomModel(),
code_paths=["preprocessing_utils/"],
artifacts={'model-weights': "/Volumes/catalog/schema/volume/path/to/file", "tokenizer_cache": "./tokenizer_cache"},
registered_model_name="catalog.schema.model_name",
)
print(model_info.model_uri)

Replace catalog.schema.model_name with the name to register the model under. The call returns a ModelInfo object, and the last line prints the URI of the logged model.

Package artifacts with the model​

When your model needs files or artifacts during inference, package them into the model artifact when you log the model. If you work in Databricks notebooks, these files often reside in Unity Catalog volumes. Models also sometimes download artifacts from the internet, such as Hugging Face tokenizers. Model Serving requires that Unity Catalog volumes artifacts are packaged into the model artifact itself using MLflow interfaces. Package network artifacts with the model whenever possible.

Pass each artifact to log_model() with the artifacts parameter, as shown in the previous section. In a pyfunc model, each artifact path is in context.artifacts. Load it the usual way for its file type.

The following fragment is a separate example of load_context reading two artifacts. It leaves out predict.

Python
import mlflow
import torch
import transformers


class ModelPyfunc(mlflow.pyfunc.PythonModel):
def load_context(self, context):
self.model = torch.load(context.artifacts["model-weights"])
self.tokenizer = transformers.BertweetTokenizer.from_pretrained("model-base", local_files_only=True, cache_dir=context.artifacts["tokenizer_cache"])

Register and serve the model​

To register the model when you log it, pass registered_model_name to log_model(), as the logging example shows.

After you log your custom pyfunc model, you can register it to Unity Catalog or the Workspace Model Registry and serve your model to a Model Serving endpoint.

Customize model output in a notebook​

The following notebook shows how to post-process the raw output of the queried model for consumption.

Customize model serving output with MLflow PyFunc notebook

Additional resources​