What you will be able to do
- Split a chain's code between load_context (one-time loading) and predict (per-request work) in an mlflow.pyfunc.PythonModel subclass
- Place input normalization and output cleanup hooks inside predict, and map them to the query-preprocessing and post-processing steps of a RAG chain
- Ship runtime files with artifacts= and shared Python modules or private wheels with code_paths= so the served chain can load them
- Log, validate and register a custom pyfunc chain to Unity Catalog with a three-level name
Key concept
PythonModel split: load_context vs predict — A custom pyfunc chain has two required methods: load_context holds everything that should be loaded once for the model to work (weights, tokenizers, lookup files), and predict holds everything that must run on every request, including pre- and post-processing.
1.Why wrap a chain in a pyfunc model
A pyfunc model is MLflow's escape hatch for code that no built-in flavor describes. A scikit-learn model can be logged with mlflow.sklearn.log_model and MLflow knows how to save, load and call it. A chain that rewrites a user question, calls a model, then strips and reformats the answer is not a scikit-learn model or a PyTorch model; it is Python code. The pyfunc flavor lets you package that code so Model Serving can run it behind a REST endpoint.
Databricks lists the situations where a custom pyfunc is the right tool. Three of them describe a chain with pre- and post-processing exactly:
- the model needs its inputs preprocessed before they reach its predict function
- the application needs the model's raw outputs post-processed before anything consumes them
- the model has branching logic that differs per request
The other two cases are a framework MLflow does not natively support, and fully custom code deployed as a model.
The mechanics are a subclass. You write a class that inherits from mlflow.pyfunc.PythonModel, implement its methods, and log an instance with mlflow.pyfunc.log_model. The smallest possible example just doubles its input, but the same shape scales to a full retrieval-augmented chain.
Checkpoint 1 of 9· Check yourself
A team must deploy an LLM chain to Model Serving. Before the model sees a user question, the chain has to rewrite it. Before a client sees the model's answer, the chain has to strip and reformat it. How should they package this chain?
The chain is plain Python code, and no built-in flavor describes it. Databricks names preprocessed inputs and post-processed raw outputs as cases for a custom pyfunc model, which does that work in its own code.
“Your application requires the model's raw outputs to be post-processed for consumption.”Source: docs.databricks.com
Sources1
2.One-time loading in load_context, per-request work in predict
**Two methods carry a packaged chain: load_context and predict.** Their difference is about how often each one runs. load_context is where anything the model needs loaded just once goes: model weights, a tokenizer, a vocabulary file, an embedding lookup table. predict holds all the logic that runs every time a request arrives.
Putting the split in the wrong place shows up as latency. If predict opens a large weights file or rebuilds a tokenizer, every request pays that cost, and the endpoint gets slower as traffic grows. The opposite mistake breaks the chain: per-request logic placed in load_context runs once, on no particular request, so it cannot format the input it was meant to format. Neither method is just for testing or just for validating schemas. load_context is how the served model gets its resources, and predict is the code the endpoint calls for each request.
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)Read the example by method. load_context stores the loaded model and tokenizer on self, which turns them into instance state that later calls reuse. It takes a context argument, and it finds its files through context.artifacts. predict takes context and model_input, and it only calls things that already exist on self. The import of CustomTokenizer also sits inside load_context, so the module is resolved once when the model loads.
Checkpoint 2 of 9· Fill the gap
In this custom pyfunc chain, the first method loads the model weights and the tokenizer. Which method name belongs in the blank so that these load once and are reused by every request?
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)load_context is where anything the model needs loaded just once goes, and it stores those resources on self. predict runs on every request, so loading the weights and tokenizer there would repeat that cost each time.
Source: docs.databricks.comCheckpoint 3 of 9· Exam question
A generative AI engineer is packaging a RAG chain as a custom MLflow pyfunc model by subclassing mlflow.pyfunc.PythonModel. The chain needs to load a large embedding lookup file once and reuse it across every request, while the retrieval-formatting and response-cleanup logic must run on each incoming request. Where should the engineer place the one-time loading code versus the per-request logic?
Correct answer: A — Load the large embedding lookup file in load_context, and run the retrieval-formatting and response-cleanup logic in predict.
- A.
load_contextruns once when the model is loaded, so the large file is read a single time and stays in memory.predictruns on every call, so formatting and cleanup belong there. - B. This swaps the two methods. Loading the file in
predictreads it again on every call, and logic placed inload_contextruns only once at load time, so it never processes individual requests. - C. Formatting and cleanup do belong in
predict, but loading the file there repeats the read on every request. The file is supposed to be loaded once and reused, andload_contextis the method that does that. - D. Loading the file in
load_contextis correct, but formatting and cleanup placed there run once at load time. They would never process the data of each incoming request, which is the job ofpredict.
Sources1
3.Pre- and post-processing hooks inside predict
**Pre- and post-processing are ordinary methods that predict calls on either side of the model call.** In the example above, format_inputs normalizes the request, self.model.predict does the inference, and format_outputs turns raw scores into the shape the caller wants: there the sigmoid of the model's outputs as a NumPy array. Keeping each hook as a named method makes the order visible in predict and lets you test each hook on its own.
A RAG chain has natural places for these hooks. At inference time the chain runs in five steps:
- Optional user query preprocessing: wrap the query in a template, rewrite it with another model, or extract keywords, producing a retrieval query.
- Retrieval: embed the retrieval query with the same embedding model used on the document chunks and return the most similar chunks.
- Prompt augmentation: combine the query and retrieved context in a template.
- LLM generation: the model answers, grounded on that context.
- Optional post-processing: apply business logic, add citations, or otherwise refine the generated text.
Steps 1 and 5 are where format_inputs and format_outputs belong when the chain is a pyfunc model. Both are per-request work, so both run inside predict, never in load_context. What does belong in load_context for a RAG chain is whatever the steps reuse: a tokenizer, a lookup file, weights.
| Chain piece | Runs | Method |
|---|---|---|
| Opening a lookup file, weights or tokenizer from context.artifacts | Once | load_context |
| Query preprocessing (template, rewrite, keyword extraction) | Every request | predict, via an input-formatting hook |
| Model or LLM call | Every request | predict |
| Post-processing (business logic, citations, cleanup) | Every request | predict, via an output-formatting hook |
It is post-processing (adding citations to the generated text), so it is an output-formatting hook called from predict after the LLM call.
Checkpoint 4 of 9· Match them up
Match each piece of a RAG chain packaged as a custom pyfunc model to where it runs in that model.
Tap a term, then the definition that fits it.
Query preprocessing, the LLM call and post-processing all happen on every request, so they all run inside predict, in that order. Only resources that are loaded once and reused, such as a tokenizer or a lookup file, belong in load_context.
“predict - this function houses all the logic that is run every time an input request is made.”Source: docs.databricks.com
4.Shipping files with artifacts and modules with code_paths
A served chain can only load what was packaged with it. Notebooks often read files from Unity Catalog volumes or download tokenizers from the internet at load time. Real-time serving at scale works best when every dependency is captured statically at deployment, and Model Serving requires files from Unity Catalog volumes to be packaged into the model artifact through MLflow. Two log_model parameters do that packaging, and they serve different kinds of dependency.
artifacts= takes a dictionary from a name to a file or directory path. MLflow copies each one into the model, and inside the model load_context looks the path up by name, for example context.artifacts["model-weights"], then loads it in the normal way for that file type. Weights, tokenizer caches, vocabularies and lookup tables go here.
mlflow.pyfunc.log_model(
...
artifacts={'model-weights': "/Volumes/catalog/schema/volume/path/to/file", "tokenizer_cache": "./tokenizer_cache"},
...
)code_paths= is for Python code that %pip install cannot install, such as .py files or a team's shared preprocessing_utils/ directory. MLflow stores those files in a code directory inside the model and adds them to the Python path when the model loads. That is why the earlier example can run from preprocessing_utils.my_custom_tokenizer import CustomTokenizer inside load_context. In MLflow 2.x the same parameter is spelled code_path.
A private library built as a wheel combines the two ideas. Pass the wheel in code_paths so it travels with the model, then list it as "code/<wheel-file-name>.whl" in extra_pip_requirements so the serving container installs it. Non-Python dependencies follow the artifacts route: Databricks recommends logging a small .txt or .json artifact that lists them.
mlflow.pyfunc.log_model(
name="model",
python_model=MyModel(),
code_paths=["/path/to/dependency.whl"], # This will be logged as `code/dependency.whl`
extra_pip_requirements=["code/dependency.whl"],
)Packaging files is separate from declaring packages. How pip_requirements, extra_pip_requirements and exact version pins work is covered under Declaring and pinning dependencies. What matters for a custom pyfunc is that MLflow cannot read your class to find every library it imports, so you list them yourself: application-level dependencies must be explicitly specified in the model, or deployment fails with dependency errors. The same goes for the packages that your code_paths modules import. Shipping preprocessing_utils/ does not install the libraries it imports.
| Dependency | Parameter | How the chain reaches it |
|---|---|---|
| Weights, vocabulary, lookup file, tokenizer cache | artifacts | context.artifacts["name"] in load_context |
| Shared .py modules or a code directory | code_paths (code_path in MLflow 2.x) | Normal import; added to the Python path |
| Private wheel | code_paths plus extra_pip_requirements | Installed from code/<wheel>.whl |
| PyPI packages the class or its modules import | pip_requirements or extra_pip_requirements | Installed in the serving environment |
Checkpoint 5 of 9· Check yourself
A chain's load_context imports CustomTokenizer from the team's preprocessing_utils/ directory and opens a vocab.json file that the tokenizer reads. Neither one can be installed with pip. Which log_model setup lets the served model reach both?
Data files the model reads at runtime go in artifacts, and load_context reaches them through context.artifacts. Python code that pip cannot install goes in code_paths, and MLflow adds it to the Python path when the model loads, so a normal import works.
“In PyFunc models, these artifacts' paths are accessible from the context object under context.artifacts”Source: docs.databricks.com
Checkpoint 6 of 9· Exam question
A team is building a custom pyfunc chain that calls a proprietary tokenizer stored in a private Python package used only by their team, plus a serialized vocabulary file that the tokenizer depends on at runtime. When calling mlflow.pyfunc.log_model for this chain, which combination of parameters correctly makes both available inside the deployed model?
Correct answer: A — Pass the vocabulary file via artifacts and the private package directory via code_paths, both as local paths.
- A.
artifactscopies data files such as a serialized vocabulary into the logged model, wherecontext.artifactsexposes them inload_context.code_pathsbundles local Python source such as a team-only package, so it can be imported when the model is served. - B.
artifactsis right for the vocabulary, but a package directory passed there is copied only as data and is not added to the import path. The proprietary tokenizer therefore cannot be imported inside the deployed model. - C. This swaps the two mechanisms. The vocabulary is data and belongs in
artifacts, wherecontext.artifactsexposes it at load time. A package directory inartifactsis copied only as data and is not importable, so the tokenizer cannot be imported. - D.
code_pathsbundles importable source, so the vocabulary file placed there is not exposed throughcontext.artifacts.pip_requirementslists installable dependencies and does not copy a local package directory, so the private tokenizer is also unavailable when serving.
5.Logging, validating and registering the chain
A pyfunc chain becomes deployable in three moves: log it, check that it loads and predicts, register it. After that, the registered version can be served from a Model Serving endpoint.
Logging on a Databricks Runtime ML cluster has one trap of its own. Those runtimes ship mlflow-skinny rather than the full mlflow package, and a pyfunc logged without pip_requirements records mlflow-skinny in its conda.yaml. Model Serving needs mlflow there and cannot build the container image without it. So pin mlflow explicitly when you log the chain.
# 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",
)Setting registered_model_name in log_model registers the model to Unity Catalog, and the name must use the full three-level form <catalog>.<schema>.<model>, separated by dots, in that order. A chain built under catalog prod_catalog and schema genai_apps is therefore prod_catalog.genai_apps.support_chain. Slashes, @ signs and a swapped schema-before-catalog order are not valid names.
Unity Catalog also requires a model signature, and the call above does not supply one. A signature records the schema of the model's inputs and outputs. An input example is a sample request: when you pass one to log_model, MLflow infers the signature from it and from the model's predicted output. With a signature in place, inputs are checked at inference and a mismatch raises an error; without one, nothing is enforced and the chain has to cope with whatever arrives. Add either signature= or input_example= to the log_model call next to registered_model_name. The two snippets below show each argument on an scikit-learn model, and the argument is the same on mlflow.pyfunc.log_model.
from mlflow.models.signature import infer_signature
signature = infer_signature(training_data, model.predict(training_data))
mlflow.sklearn.log_model(model, "model", signature=signature)input_example = {"feature1": 0.5, "feature2": 3}
mlflow.sklearn.log_model(model, "model", input_example=input_example)Validate before you deploy. Databricks recommends checking that the model can be served, for example with mlflow.models.predict. A cheaper first test is to load the logged chain back as a generic Python function and call it. That runs load_context against the packaged artifacts and code_paths rather than your notebook's files, so a missing artifact or an unimportable module fails here instead of during the endpoint build. If the build does fail, the endpoint's Build logs tab shows the package installation errors.
model = mlflow.pyfunc.load_model(model_path)
model.predict(model_input)Checkpoint 7 of 9· Fill the gap
Which value completes registered_model_name so that log_model registers this chain to Unity Catalog?
# 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=" ? ",
)A Unity Catalog model name has three levels, separated by dots, in catalog, schema, model order. A name with slashes, with the schema first, or with the schema missing is not valid.
Source: docs.databricks.comCheckpoint 8 of 9· Check yourself
On a Databricks Runtime ML cluster, an engineer logs a custom pyfunc chain with mlflow.pyfunc.log_model and no pip_requirements, then registers it. When they deploy it, the serving endpoint fails to build its container. What is the most likely cause, and what is the fix?
Databricks Runtime ML includes mlflow-skinny, and a pyfunc logged there without pip_requirements records mlflow-skinny in conda.yaml. Model Serving needs full mlflow to build the container, so pin mlflow to an exact version explicitly.
“Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise.”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A generative AI engineer finishes writing a custom pyfunc chain and wants to register it to Unity Catalog so it can be governed and later deployed to a serving endpoint. The chain is being developed under the catalog prod_catalog and schema genai_apps. Which registered_model_name value follows the correct Unity Catalog naming convention for mlflow.pyfunc.log_model?
Correct answer: A — prod_catalog.genai_apps.support_chain
- A. This is correct: Unity Catalog models use a three-level, dot-separated name of catalog, schema, and model name, so
prod_catalog.genai_apps.support_chaincorrectly places the model under the given catalog and schema. - B.
hive_metastoreis the legacy workspace-local catalog, not theprod_catalogcatalog the chain is being developed under. A model registered with this name would not land inprod_catalog.genai_apps, so it would not be governed there as required. - C. This reverses the required order; Unity Catalog names must go catalog first, then schema, then object name, so putting the schema before the catalog does not match the expected
prod_catalog.genai_apps.support_chainstructure. - D. Unity Catalog separates the catalog, schema and model with dots at every level. Using a slash before the model name makes this an invalid
registered_model_nameformlflow.pyfunc.log_model, so registration would fail.
Sources
(8)
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
“MLflow's Python function, pyfunc, provides flexibility to deploy any piece of Python code or any Python model.”
↩︎ Why wrap a chain in a pyfunc model“Your application requires the model's raw outputs to be post-processed for consumption.”
↩︎ Why wrap a chain in a pyfunc model“Your model requires preprocessing before inputs can be passed to the model's predict function.”
↩︎ Why wrap a chain in a pyfunc model“load_context - anything that needs to be loaded just one time for the model to operate should be defined in this function.”
↩︎ One-time loading in load_context, per-request work in predict“predict - this function houses all the logic that is run every time an input request is made.”
↩︎ One-time loading in load_context, per-request work in predict“predict - this function houses all the logic that is run every time an input request is made.”
↩︎ Pre- and post-processing hooks inside predict“Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise.”
↩︎ Logging, validating and registering the chain“you can register it to Unity Catalog or Workspace Registry and serve your model to a Model Serving endpoint”
↩︎ Logging, validating and registering the chain“it is beneficial to verify that the model is capable of being served.”
↩︎ Logging, validating and registering the chain“predict - this function houses all the logic that is run every time an input request is made.”
↩︎ Key concept“load_context - anything that needs to be loaded just one time for the model to operate should be defined in this function.”
↩︎ Exam trap 1“Model Serving requires mlflow (not mlflow-skinny) in conda.yaml and cannot build the container image otherwise.”
↩︎ Exam trap 3“This is critical so that the system minimize the number of artifacts loaded during the predict function, which speeds up inference.”
↩︎ Prediction - 2.https://docs.databricks.com/aws/en/agents/tutorials/ai-cookbook/fundamentals-inference-chain-ragOfficial docs
“In some cases, the user's query is preprocessed to make it more suitable for querying the vector database.”
↩︎ Pre- and post-processing hooks inside predict“The LLM's response may be processed further to apply additional business logic, add citations, or otherwise refine the generated text”
↩︎ Pre- and post-processing hooks inside predict - 3.https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-custom-artifactsOfficial docs
“Model Serving requires that Unity Catalog volumes artifacts are packaged into the model artifact itself using MLflow interfaces.”
↩︎ Shipping files with artifacts and modules with code_paths“Real-time workloads at scale perform best when all required dependencies are statically captured at deployment time.”
↩︎ Shipping files with artifacts and modules with code_paths“In PyFunc models, these artifacts' paths are accessible from the context object under context.artifacts”
↩︎ Prediction - 4.
“MLflow stores any files or directories passed using code_paths or code_path as artifacts along with the model in a code directory.”
↩︎ Shipping files with artifacts and modules with code_paths“You may have Python code dependencies that can't be installed using the %pip install command, such as one or more .py files.”
↩︎ Shipping files with artifacts and modules with code_paths“When loading the model, MLflow adds these files or directories to the Python path.”
↩︎ Exam trap 2 - 5.https://docs.databricks.com/aws/en/machine-learning/model-serving/private-libraries-model-servingOfficial docs
“you can specify its location using the code_paths parameter, and pass "code/<wheel-file-name>.whl" in the extra_pip_requirements parameter.”
↩︎ Shipping files with artifacts and modules with code_paths - 6.
“application-level dependencies must be explicitly specified in your MLflow model.”
↩︎ Shipping files with artifacts and modules with code_paths - 7.
“you must provide the full three-level name of the model in the format <catalog>.<schema>.<model>.”
↩︎ Logging, validating and registering the chain“you can specify an input example in your mlflow.<flavor>.log_model call, and the model signature is automatically inferred.”
↩︎ Logging, validating and registering the chain“If a signature is provided, model inputs are checked at inference and an error is reported if the inputs do not match the signature.”
↩︎ Logging, validating and registering the chain“you must provide the full three-level name of the model in the format <catalog>.<schema>.<model>.”
↩︎ Exam trap 4 - 8.
“Signatures are necessary for logging models to the Unity Catalog.”
↩︎ Logging, validating and registering the chain