What you will be able to do
- Write a custom model by subclassing mlflow.pyfunc.PythonModel, with work split correctly between load_context and predict
- Package files with the artifacts dictionary, shared code with code_path, and packages with pip_requirements
- Log a model with a signature, register it under a three-level Unity Catalog name, and check it with mlflow.models.predict before you serve it
Key concept
PythonModel with load_context and predict — A custom pyfunc model is a subclass of mlflow.pyfunc.PythonModel. Its load_context method runs once to load weights, tokenizers and other packaged artifacts onto self. Its predict method runs on every request and holds the custom logic that turns the incoming input into a result.
1.Wrapping custom logic in a PythonModel
Databricks Model Serving can turn any Python model or custom code into a production API, and Databricks calls these custom models. To deploy one, you log it in MLflow format, register it in Unity Catalog, and then create an endpoint for it. If your model is a plain scikit-learn or XGBoost estimator, a built-in flavor such as mlflow.sklearn.log_model already captures it. Use the pyfunc route when the model needs code that no built-in flavor covers. Common cases are preprocessing before the estimator, raw outputs that need post-processing, per-request branching, and frameworks that MLflow does not support natively.
A pyfunc model is a class that subclasses mlflow.pyfunc.PythonModel. It has two methods, and each has a different job. predict(self, context, model_input) receives the input from every scoring request and returns the result, so a scikit-learn preprocessing step followed by a heuristic rule both belong inside it. load_context(self, context) runs once, when the model is loaded. Anything the model needs only once goes there: weights, a tokenizer, a lookup file. Keeping that work out of predict keeps per-request latency low.
No other MLflow class fills this role. MLflow has no SklearnModel class with a transform hook, no EvaluationModel with a score method, and mlflow.entities holds tracking metadata, not code that runs at serving time. If an object needs custom per-request logic, it subclasses PythonModel and implements predict.
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):
# insert some code that formats your inputs
pass
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)load_context also runs more often than you might expect. During zero-downtime maintenance, Databricks reloads models on existing endpoints. If a model fails to reload, the update is marked as failed and the previous configuration keeps serving. A load_context that calls a flaky external service, or relies on state that only existed at training time, can therefore break a routine maintenance reload.
Checkpoint 1 of 8· Fill the gap
This custom pyfunc model loads its weights and tokenizer once, when the model is loaded, rather than on every scoring request. Which method name completes the sample?
class CustomModel(mlflow.pyfunc.PythonModel):
def ? (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):
# insert some code that formats your inputs
pass
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)A PythonModel has two jobs split across two methods. load_context(self, context) runs once when the model is loaded and gets the packaged artifacts through context.artifacts. predict runs on every request. Doing one-time loading in load_context keeps per-request latency low.
Source: docs.databricks.comCheckpoint 2 of 8· Exam question
A team wraps a scikit-learn preprocessing step and a downstream heuristic rule inside a single object before logging it for real-time serving. Which MLflow class should the object subclass so that predict() receives the raw request payload and can run this custom logic?
Correct answer: A — mlflow.pyfunc.PythonModel, implementing a predict method that accepts the context and the model input and returns the result.
- A. Subclassing
PythonModeland implementingpredict(self, context, model_input)is the documented pattern for wrapping arbitrary preprocessing and business logic as a custom pyfunc model that Model Serving can invoke. - B. MLflow has no
SklearnModelclass with atransformmethod; the sklearn flavor logs an estimator directly and does not provide a hook for arbitrary combined preprocessing and rule logic. - C. There is no
EvaluationModelclass in MLflow; evaluation harnesses consume an already-logged model rather than acting as the model implementation itself. - D.
mlflow.entities.Modelis a metadata record describing a logged model version, not a base class with arunmethod that executes inference logic.
2.Packaging files with the artifacts dictionary
The artifacts parameter of log_model() maps a logical name to a file path. MLflow copies each file into the logged model directory. Inside the model, context.artifacts["name"] returns the local path to that copy, and you load it with whatever reader suits the file type. The same applies to a JSON scaling config, a tokenizer cache or model weights. Once packaged, the file travels with the model, so anyone can inspect or reuse the model directory without the training code.
mlflow.pyfunc.log_model(
...
artifacts={'model-weights': "/Volumes/catalog/schema/volume/path/to/file", "tokenizer_cache": "./tokenizer_cache"},
...
)Packaging is required for some files, not just recommended. Notebook work often keeps files in Unity Catalog volumes, but an endpoint cannot read those files from the volume at serving time. Model Serving requires that they be copied into the model artifact through MLflow. Files a model would normally download at load time, such as Hugging Face tokenizers, should also be packaged whenever possible, because real-time workloads perform best when every dependency is captured at deployment time. None of the other log_model parameters can carry a file. pip_requirements lists package names to install, a signature describes input and output schemas, and registered_model_name is a registry name string.
Checkpoint 3 of 8· Check yourself
A data scientist keeps lookup-table weights in a Unity Catalog volume and wants the custom pyfunc model to use them once it is behind a Model Serving endpoint. What should they do?
An endpoint can't read files from a Unity Catalog volume while it is serving. The file has to be copied into the model artifact through the artifacts parameter, and the model then loads it from context.artifacts. pip_requirements and the signature can't carry files.
“Model Serving requires that Unity Catalog volumes artifacts are packaged into the model artifact itself using MLflow interfaces.”Source: docs.databricks.com
Checkpoint 4 of 8· Exam question
A custom pyfunc model needs a fitted tokenizer file that was saved separately from the model object during training. The team wants the tokenizer loaded once when the serving container starts, not on every scoring request. Which pattern accomplishes this?
Correct answer: A — Pass the tokenizer file path in the artifacts dictionary at log time, then load it from context.artifacts inside load_context, caching it on self.
- A. Artifacts declared at log time are copied alongside the model, and
load_contextruns exactly once when the model is loaded into the serving container, making it the correct place to load and cache the tokenizer for reuse across requests. - B.
load_contextruns whenever the model is loaded, including inside the deployed serving container, so reloading the tokenizer on every request is unnecessary overhead and misunderstands when the hook fires. - C. Embedding a fitted tokenizer's binary state as literal source code is impractical and not how MLflow expects trained artifacts to be packaged with a pyfunc model.
- D. Reading a fresh copy from an environment-variable path on every request repeats the same unnecessary disk I/O per call and does not use the artifact-tracking mechanism MLflow provides for this purpose.
Checkpoint 5 of 8· Exam question
During mlflow.pyfunc.log_model(), a data scientist wants to bundle a JSON-formatted feature-scaling config file with the model so the packaged model directory can be inspected or reused independently of the code that produced it. Which parameter should hold this file?
Correct answer: A — The artifacts parameter, mapping a logical name to the config file's local path so MLflow copies the file into the model directory.
- A. The
artifactsdictionary maps a name to a local file or directory path, and MLflow copies it into the packaged model so it travels with the model and is retrievable throughcontext.artifactsat inference time. - B.
pip_requirementsonly accepts pip-installable package specifiers, not arbitrary file paths, so a JSON config file placed there would not be copied or resolved correctly. - C. The
signatureparameter describes the shape and types of model inputs and outputs; it has no mechanism for embedding an unrelated configuration file's contents. - D.
registered_model_nameis a plain string identifying where the model is registered; appending a file path to it does not attach or copy any file into the model package.
Sources3
3.Declaring packages and shared code
Each deployment builds a container from what the model declares. A model logged with a native flavor has its package dependencies captured automatically. A pyfunc model can be missing packages unless you list them, and the base image does not fill the gap: application-level dependencies must be declared in the MLflow model. A missing package typically shows up as a dependency error during deployment, about ten minutes after you clicked deploy.
| Parameter | What it carries | Use it when |
|---|---|---|
| pip_requirements | The full list of pip packages for the model environment | You want to state the environment exactly, as most pyfunc models should |
| extra_pip_requirements | Packages added on top of what MLflow captures automatically | Automatic capture is right but missing a package or two |
| conda_env | A conda environment dictionary with channels and dependencies | You need to control the conda environment, such as its channel |
| code_path | Local Python files or folders added to the model's import path | predict or load_context imports your organisation's shared modules |
With code_path, a model can import shared code. If a model is logged with code_path = ["preprocessing_utils/"], the from preprocessing_utils.my_custom_tokenizer import CustomTokenizer line in the earlier load_context works inside the serving container, because that folder was logged with the model.
One packaging failure is specific to Databricks Runtime ML. Those runtimes include mlflow-skinny rather than the full mlflow package. If you log a pyfunc model there without pip_requirements, MLflow writes mlflow-skinny into the model's conda.yaml. Model Serving needs the full mlflow package and cannot build the image without it. The fix is to always pin mlflow explicitly.
# 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",
)Checkpoint 6 of 8· Match them up
Match each log_model parameter to what it puts into a custom model's serving environment
Tap a term, then the definition that fits it.
pip_requirements replaces automatic capture with an exact list, and extra_pip_requirements adds to it. conda_env sets the whole conda environment, including channels. code_path ships your own Python modules, not packages from an index, so imports in load_context or predict still work inside the serving container.
“To include additional requirements beyond what is automatically captured, use extra_pip_requirements.”Source: docs.databricks.com
Checkpoint 7 of 8· Check yourself
On a Databricks Runtime ML cluster, a pyfunc model was logged without pip_requirements and registered to Unity Catalog. Its serving endpoint then fails to build the container image. Which change fixes the deployment?
Databricks Runtime ML includes mlflow-skinny, so automatic capture writes mlflow-skinny into conda.yaml. Model Serving needs the full mlflow package to build the image, and the base image won't add application-level dependencies. Pin a full mlflow version, such as mlflow==3.8.1, in pip_requirements.
“Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise.”Source: docs.databricks.com
4.Signature, Unity Catalog registration and pre-deployment checks
Unity Catalog requires a signature. For most registries a signature and an input example are recommended. For Unity Catalog the signature is mandatory, so a model logged without one cannot be registered there. infer_signature(training_data, model.predict(training_data)) builds one from sample data, and you pass the result as signature= to log_model. An input example is optional, but it pays off later: the Serving UI's Show Example button loads it into the query box.
Unity Catalog is the recommended registry, and a model there has a three-level name, catalog.schema.model_name. There are two ways to register. You can pass registered_model_name to log_model, as in the code above. Or you can register an existing logged model afterwards with mlflow.register_model, using a models:/{model_id} URI in MLflow 3 or a runs:/{run_id}/{model-path} URI in MLflow 2.x. Code that reads from or writes to Unity Catalog sets mlflow.set_registry_uri("databricks-uc") first. Version management after registration, such as aliases and promotion, is covered in model lifecycle management.
Validate the model before any compute exists. mlflow.models.predict runs the logged model against an input in an environment built from the model's declared dependencies. That exposes a missing package, a file that was never added to artifacts, or an object that will not deserialize, all without provisioning an endpoint. A local check takes seconds. Finding the same problem through a failed endpoint deployment takes about ten minutes per attempt.
Checkpoint 8 of 8· Check yourself
A team logs a custom pyfunc model with python_model, artifacts and pinned pip_requirements, but no other arguments. When they try to register it as catalog.schema.churn_model, Unity Catalog rejects it. What change gets the model registered?
Other registries only recommend a signature, but Unity Catalog requires one. A model logged without a signature can't be registered there, whichever registration path you use. Build one with infer_signature, pass it as signature= to log_model, and register the newly logged model. An input example is optional and doesn't replace the signature.
“Adding a signature and input example to MLflow is recommended. Signatures are necessary for logging models to the Unity Catalog.”Source: docs.databricks.com
Sources
(3)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/machine-learning/model-serving/deploy-custom-python-codeOfficial docs
“anything that needs to be loaded just one time for the model to operate should be defined in this function”
↩︎ Wrapping custom logic in a PythonModel“authors of models can log full code references that load into the path”
↩︎ Declaring packages and shared code“use mlflow.models.predict to validate models before deployment”
↩︎ Signature, Unity Catalog registration and pre-deployment checks“predict - this function houses all the logic that is run every time an input request is made.”
↩︎ Key concept“Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise.”
↩︎ Exam trap 1“Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise.”
↩︎ Checkpoint - 2.
“Make sure your customized models are robust and are able to reload at any time.”
↩︎ Wrapping custom logic in a PythonModel“application-level dependencies must be explicitly specified in your MLflow model.”
↩︎ Declaring packages and shared code“After the model is logged, register it in the Unity Catalog (recommended) or the workspace registry.”
↩︎ Signature, Unity Catalog registration and pre-deployment checks“Signatures are necessary for logging models to the Unity Catalog.”
↩︎ Exam trap 3“To include additional requirements beyond what is automatically captured, use extra_pip_requirements.”
↩︎ Checkpoint“Adding a signature and input example to MLflow is recommended. Signatures are necessary for logging models to the Unity Catalog.”
↩︎ Checkpoint - 3.https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-custom-artifactsOfficial docs
“Network artifacts loaded with the model should be packaged with the model whenever possible.”
↩︎ Packaging files with the artifacts dictionary“Model Serving requires that Unity Catalog volumes artifacts are packaged into the model artifact itself using MLflow interfaces.”
↩︎ Exam trap 2“these artifacts' paths are accessible from the context object under context.artifacts”
↩︎ Prediction“Model Serving requires that Unity Catalog volumes artifacts are packaged into the model artifact itself using MLflow interfaces.”
↩︎ Checkpoint