CertSafari
    Databricks Certified Machine Learning Professional· Lessons

    Domain 3 · Lesson 11/11

    Custom pyfunc models: logging artifacts and dependencies and registering in Unity Catalog

    Custom Model Serving

    13 min read
    6% of exam
    3 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    A custom pyfunc model that loads weights and a tokenizer once in load_context, then formats inputs, predicts and post-processes outputs in predictpython
    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)

    Checkpoint 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?

    Sources12

    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.

    Logging a file from a Unity Catalog volume and a local tokenizer cache as named artifactspython
    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?

    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?

    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?

    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.

    Ways to declare what a custom model needs
    ParameterWhat it carriesUse it when
    pip_requirementsThe full list of pip packages for the model environmentYou want to state the environment exactly, as most pyfunc models should
    extra_pip_requirementsPackages added on top of what MLflow captures automaticallyAutomatic capture is right but missing a package or two
    conda_envA conda environment dictionary with channels and dependenciesYou need to control the conda environment, such as its channel
    code_pathLocal Python files or folders added to the model's import pathpredict 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.

    Pinning full mlflow and registering to Unity Catalog in the same log_model callpython
    # 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.

    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?

    Sources21

    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?

    Sources21

    Sources

    (3)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 3.
      “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

    Continue to part 2 of 2

    Deploying and querying custom model serving endpoints

    Spotted a mistake, or was something unclear? Tell us.