What you will be able to do
- Load a registered or logged MLflow model with mlflow.pyfunc.load_model and score a pandas DataFrame on the driver
- Build the correct models:/ URI for a Unity Catalog model version
- Score a large Spark DataFrame in parallel with mlflow.pyfunc.spark_udf and rebuild the model's environment with env_manager
- Choose between Series-to-Series and iterator pandas UDFs, and know when to use mapInPandas or applyInPandas instead
Key concept
pyfunc model as the scoring unit — An MLflow model loaded as a generic Python function exposes one predict call over pandas input. For small data you call predict on a pandas DataFrame yourself. For large data, spark_udf wraps the same model so Spark applies it to batches across the cluster.
1.Scoring a pandas DataFrame with mlflow.pyfunc.load_model
Batch inference means scoring a whole set of rows that already exists, such as last night's transactions or a customer table, and writing the predictions somewhere. It is not answering requests one at a time. On Databricks, every route to batch inference starts from an MLflow model loaded through the pyfunc interface. Whatever library trained the model, mlflow.pyfunc.load_model() returns an object with a predict method that takes pandas input. When you log a model, the run's Artifacts panel even generates the loading code for you, in both a pandas version and a Spark version.
model = mlflow.pyfunc.load_model(model_path)
model.predict(model_input)model_path is a model URI, the same string you use anywhere a logged or registered model is referenced. See Logged models and model URIs (runs:/, models:/). For batch scoring, what matters is that the URI alone decides which model is loaded. A run-relative path looks like runs:/{run_id}/{model-path}. A workspace-registry path names a stage, as in models:/fraud_detector/Production. load_model has no separate stage or alias argument. To get a different version, you change the URI.
Unity Catalog models use the three-level name catalog.schema.model, followed by a slash and the version number. A model registered as retail.forecasting.demand_model is loaded at version 3 with models:/retail.forecasting.demand_model/3. The leaf name demand_model on its own does not identify it, because the model is stored inside a specific catalog and schema. Collaborators need privileges on both of those. A colon-separated name or a hand-built dbfs:/models/... path is not a registry URI either.
import mlflow.pyfunc
# Load version 1 of the model "prod.ml_team.iris_model"
model_version_uri = "models:/prod.ml_team.iris_model/1"
first_version = mlflow.pyfunc.load_model(model_version_uri)
first_version.predict(test_x)Calling predict directly is the right choice when the data is already pandas and fits on the driver. A few thousand rows pulled into a notebook for analysis is the typical case: one load_model call and one predict call, with no cluster-wide setup. The same pattern turns into a trap when you run it the other way round. Calling toPandas() on a 50-million-row Delta table copies every record to the driver program. Spark's own guidance is to do that only on a small subset of the data. Once the data starts out as a large Spark table, scoring belongs on the cluster.
Checkpoint 1 of 8· Fill the gap
Which call completes this sample so that a registered or logged MLflow model can score a pandas DataFrame on the driver?
model = mlflow.pyfunc. ? (model_path)
model.predict(model_input)mlflow.pyfunc.load_model returns a generic Python function model, and its predict method takes pandas input directly. spark_udf wraps the model for scoring Spark DataFrames across a cluster, log_model saves a model, and get_model_dependencies only fetches the dependency file.
Source: docs.databricks.comCheckpoint 2 of 8· Check yourself
A nightly job needs churn scores for a 50-million-row Delta table. A colleague writes pdf = spark.table("customers").toPandas() and then model.predict(pdf) with a pyfunc model. What is the problem, and what should the job do instead?
Even with Arrow enabled, toPandas() copies every row of the table to the driver, which only suits a small subset of data. A large Spark table should be scored on the cluster with spark_udf.
“Even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program”Source: docs.databricks.com
Checkpoint 3 of 8· Exam question
A data scientist has a pandas DataFrame with 10,000 rows already loaded in the driver's memory and a model registered at models:/churn_model/Production. They want to generate predictions for this one-off analysis with the least setup overhead. Which approach best fits this situation?
Correct answer: D — Call mlflow.pyfunc.load_model("models:/churn_model/Production") and pass the pandas DataFrame directly to .predict(), since the whole dataset already fits comfortably in driver memory.
- A. Converting a DataFrame that already fits in driver memory into a Spark DataFrame just to build a distributed pandas UDF adds Spark job scheduling and Arrow serialization overhead for no real benefit at this size, making it unnecessarily heavy for a 10,000-row one-off job.
- B. Standing up a real-time serving endpoint and calling it row by row from a loop introduces network round trips and deployment overhead for what is a small, local, one-time scoring task, and it is slower than scoring the DataFrame directly in process.
- C.
mlflow.pyfunc.load_model()does not take astageargument to select an alias; model stage or alias selection belongs in the model URI itself, so this call does not do what the scenario needs and adds an unnecessary new model version. - D. Loading the model as a
PyFuncModeland calling.predict()directly on the in-memory pandas DataFrame is the simplest path when the data already fits comfortably without Spark, avoiding any cluster job overhead for a small one-off scoring task.
Checkpoint 4 of 8· Exam question
A team registered an MLflow model in Unity Catalog under the three-level name retail.forecasting.demand_model and wants to load version 3 of that model to run pandas-based batch predictions in a notebook. Which model loading call is correct?
Correct answer: A — mlflow.pyfunc.load_model("models:/retail.forecasting.demand_model/3") — the three-level name plus the numeric version identifies the exact Unity Catalog model version to load.
- A. A Unity Catalog registered model URI uses the
models:/scheme followed by the full three-levelcatalog.schema.modelname and a version or alias, so this string correctly identifies version 3 of the named model for loading. - B. The catalog and schema segments are required parts of a Unity Catalog registered model's identity and are never inferred from the current session, so dropping them to just the leaf name would fail to resolve the model.
- C. The
models:/scheme with slash-separated segments is required, not a bare colon-separated three-level name; this string is not a valid MLflow model URI regardless of registry backend. - D. Unity Catalog registered models are addressed through the
models:/URI scheme, not a fixed DBFS filesystem path, so this string does not point to a valid registered model location.
2.Distributing the model with mlflow.pyfunc.spark_udf
mlflow.pyfunc.spark_udf turns the same pyfunc model into a Spark UDF. Spark then applies it to the rows of a Spark DataFrame across the cluster, and the work never passes through a single pandas DataFrame on the driver. You give it the active spark session and a model URI, then use the returned UDF like any other column expression. Usually that means withColumn("prediction", ...), followed by writing the result to a new Delta table. MLflow positions this route for scoring on a Spark cluster, whether as a batch job or as a Spark Streaming job.
# load input data table as a Spark DataFrame
input_data = spark.table(input_table_name)
model_udf = mlflow.pyfunc.spark_udf(spark, model_path)
df = input_data.withColumn("prediction", model_udf())Batch scoring like this suits work where throughput and cost matter more than per-request latency, with results arriving in minutes. Looping over 50 million rows in a notebook and calling a real-time endpoint once per row inverts that trade-off. It routes a throughput job through infrastructure built for individual requests, and the driver loop does all the waiting.
The UDF runs the model on cluster workers, and those workers need the library versions the model was trained with. The model's logged requirements record those versions; see Model signature, input example and pip requirements. Pass env_manager="virtualenv" to spark_udf, and MLflow restores those dependencies inside the UDF's own context while leaving the notebook's environment untouched. That is the fix when a cluster's installed scikit-learn differs from the one in training and predictions drift or fail to load. MLflow warns you about such a mismatch when you load the model, but it does not correct it. On the driver, mlflow.pyfunc.get_model_dependencies returns a requirements file that you can install with %pip install.
| Situation | Call | Why |
|---|---|---|
| Small pandas DataFrame already on the driver | mlflow.pyfunc.load_model(uri).predict(pdf) | No cluster setup; predict accepts pandas input |
| Large Spark table to score and write back | mlflow.pyfunc.spark_udf(spark, uri) with withColumn | Spark applies the model across the cluster |
| Workers' libraries differ from training | spark_udf(..., env_manager="virtualenv") | Restores the model's dependencies inside the UDF only |
| Large table pulled with toPandas() then predict | Avoid | Collects every record to the driver |
Checkpoint 5 of 8· Check yourself
After a cluster upgrade, a spark_udf scoring job starts producing drifting predictions. The workers now run a different scikit-learn version from the one the model was trained with. What fixes this without changing the notebook's own environment?
With env_manager="virtualenv", spark_udf restores the model's logged dependencies inside the UDF's own context and leaves the outside environment untouched. MLflow only warns about a mismatch and does not fix it, and calling toPandas() on a large table collects every record onto the driver.
“When you load a model as a PySpark UDF, specify env_manager="virtualenv" in the mlflow.pyfunc.spark_udf call.”Source: docs.databricks.com
Checkpoint 6 of 8· Exam question
A data engineer has a Delta table with 50 million transaction rows and a model registered at models:/fraud_detector/Production. They need to score every row and write predictions to a new Delta table while distributing the scoring work across the cluster. Which approach should they use?
Correct answer: B — Load the model with mlflow.pyfunc.spark_udf(spark, "models:/fraud_detector/Production") and add predictions to the Spark DataFrame via withColumn, letting executors score partitions in parallel.
- A. Collecting 50 million rows into a single pandas DataFrame with
.toPandas()pulls the entire dataset into driver memory, which risks an out-of-memory failure and abandons the cluster's distributed executors entirely. It also removes any parallelism, since one.predict()call runs sequentially on the driver. - B. Wrapping the registered model as a pandas UDF with
mlflow.pyfunc.spark_udfand applying it throughwithColumnlets each executor load the model once and score its own partition in parallel, which is the standard pattern for distributed batch inference over a large Delta table. - C. Issuing 50 million individual REST calls from a single driver notebook is extremely slow, adds network latency per row, and does not use the cluster's compute for scoring at all, making it impractical at this scale.
- D. This SQL function can call a served model per row, but it requires a live serving endpoint to already be deployed and bypasses pandas or Spark DataFrame scoring altogether, so it does not match a pandas-based batch scoring workflow over an existing Delta table.
3.Writing your own pandas UDF for model scoring
Sometimes you need custom pre- or post-processing around the model, or a model object that spark_udf does not wrap for you. In that case you write the pandas UDF yourself, and spark_udf is in fact the packaged version of this same mechanism. Databricks recommends pandas UDFs for scaling batch and streaming inference across a cluster. A pandas UDF uses Apache Arrow to move data between the JVM and Python and works on whole pandas objects instead of single rows. That vectorization is why it can run up to 100x faster than a row-at-a-time Python UDF.
The basic form is Series to Series. You declare it with the pandas_udf decorator and the type hints pd.Series -> pd.Series, and you use it in select or withColumn. Spark splits the data into batches of rows, calls your function once per batch, and concatenates the results. Each output Series must be the same length as its input. The Series your function receives is one internal batch, not the whole column, so anything computed across 'the column' inside the function is really computed per batch.
The answer is once per batch, which is wasted work for any model that is expensive to deserialize. The iterator form fixes this. The function takes Iterator[pd.Series] and returns Iterator[pd.Series], which lets it do setup once and then loop over the incoming batches, yielding one result per batch. This variant exists for exactly the case of loading a model file and applying it to every input batch. The total output length across all yielded batches must still match the total input length. Wrap the loop in try/finally, or use a context manager, so that any resources are released at the end.
# In the UDF, you can initialize some state before processing batches.
# Wrap your code with try/finally or use context managers to ensure
# the release of resources at the end.
y = 1 # value captured by the UDF closure
@pandas_udf("long")
def plus_y(batch_iter: Iterator[pd.Series]) -> Iterator[pd.Series]:
try:
for x in batch_iter:
yield x + y
finally:
pass # release resources here, if anyA basic iterator UDF takes a single Spark column. Most models need several features, so there is a multi-column variant with the hint Iterator[Tuple[pd.Series, ...]] -> Iterator[pd.Series]. Each item from the iterator is a tuple holding one Series per input column, and the UDF is called with that many columns. It follows the same rules as the single-column iterator, including setting up state before the loop.
| Type hint | Input columns | Fits when |
|---|---|---|
| pd.Series -> pd.Series | One or more | Cheap per-batch logic with no setup cost |
| Iterator[pd.Series] -> Iterator[pd.Series] | One | An expensive setup step, such as loading a model, should happen before the batches |
| Iterator[Tuple[pd.Series, ...]] -> Iterator[pd.Series] | Several | The same as above, for a model with several feature columns |
Checkpoint 7 of 8· Match them up
You are writing your own pandas UDF to score a model on a Spark table. Match each type hint to how it behaves.
Tap a term, then the definition that fits it.
A Series-to-Series UDF runs once per batch, so any setup in its body is repeated for every batch. Both iterator forms let you do expensive setup, such as loading a model, once before looping over the batches. The single-Series iterator takes one column, and the tuple form takes several feature columns.
“useful when the UDF execution requires initializing some state, for example, loading a machine learning model file to apply inference to every input batch”Source: docs.databricks.com
4.DataFrame-level scoring with mapInPandas and applyInPandas
pandas function APIs hand your function whole pandas DataFrames instead of individual columns. They run on the same Arrow machinery as pandas UDFs, and type hints are optional. Two of them matter for inference.
mapInPandas takes an iterator of pandas DataFrames and yields an iterator of pandas DataFrames, and you declare the output schema yourself. Because the function receives an iterator, you can load the model once before the loop, just as in an iterator UDF. A pandas UDF has to emit exactly one value per input row. mapInPandas can return output of any length, so one function can score, filter out low-confidence rows and add several output columns.
df = spark.createDataFrame([(1, 21), (2, 30)], ("id", "age"))
def filter_func(iterator):
for pdf in iterator:
yield pdf[pdf.id == 1]
df.mapInPandas(filter_func, schema=df.schema).show()groupBy().applyInPandas() follows a split-apply-combine pattern. Each group arrives as a single pandas DataFrame containing all of its rows, and the results are combined back into a Spark DataFrame using a schema you supply. It fits per-group scoring, such as a separate forecasting model for each store. The cost is memory. A whole group is loaded before your function runs, and maxRecordsPerBatch does not split groups. One oversized store can therefore cause an out-of-memory error even when every other group is small. Use mapInPandas when rows can be scored independently, and keep applyInPandas for logic that really needs all of a group at once.
Checkpoint 8 of 8· Fill the gap
This function gets an iterator of pandas DataFrames and yields fewer rows than it receives. Which DataFrame method runs it across the cluster without grouping the data first?
df = spark.createDataFrame([(1, 21), (2, 30)], ("id", "age"))
def filter_func(iterator):
for pdf in iterator:
yield pdf[pdf.id == 1]
df. ? (filter_func, schema=df.schema).show()mapInPandas turns an iterator of pandas DataFrames into another iterator of pandas DataFrames, and its output can be any length. That lets one function score rows and filter them. applyInPandas is called after groupBy() and loads each whole group into memory. withColumn and select take a column expression such as a pandas UDF, and a pandas UDF must return exactly one value per input row.
Source: docs.databricks.comSources7
Sources
(7)
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/mlflow/modelsOfficial docs
“For Python MLflow models, an additional option is to use mlflow.pyfunc.load_model() to load the model as a generic Python function.”
↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model“A panel opens to the right showing code you can use to load the logged model and make predictions on Spark or pandas DataFrames.”
↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model“a registered model path (such as models:/{model_name}/{model_stage}).”
↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model“export the model as an Apache Spark UDF to use for scoring on a Spark cluster, either as a batch job”
↩︎ Distributing the model with mlflow.pyfunc.spark_udf“This restores model dependencies in the context of the PySpark UDF and does not affect the outside environment.”
↩︎ Distributing the model with mlflow.pyfunc.spark_udf“MLflow warns you if a mismatch is detected between the current environment and the model's dependencies.”
↩︎ Distributing the model with mlflow.pyfunc.spark_udf“you can call mlflow.pyfunc.get_model_dependencies to retrieve and download the model dependencies.”
↩︎ Distributing the model with mlflow.pyfunc.spark_udf“For Python MLflow models, an additional option is to use mlflow.pyfunc.load_model() to load the model as a generic Python function.”
↩︎ Key concept“When you load a model as a PySpark UDF, specify env_manager="virtualenv" in the mlflow.pyfunc.spark_udf call.”
↩︎ Exam trap 4“make predictions on Spark or pandas DataFrames”
↩︎ Prediction“When you load a model as a PySpark UDF, specify env_manager="virtualenv" in the mlflow.pyfunc.spark_udf call.”
↩︎ Checkpoint - 2.
“You can also load model versions by version number:”
↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model“Collaborators must also have the USE CATALOG and USE SCHEMA privileges on the catalog and schema containing the model.”
↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model“model_version_uri = "models:/prod.ml_team.iris_model/1"”
↩︎ Exam trap 1 - 3.
“collection of all records in the DataFrame to the driver program”
↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model“collection of all records in the DataFrame to the driver program”
↩︎ Exam trap 2“Even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program”
↩︎ Checkpoint - 4.
“Batch and streaming scoring supports high-throughput, low-cost scoring at latencies as low as minutes.”
↩︎ Distributing the model with mlflow.pyfunc.spark_udf“Use Spark Pandas UDFs to scale batch and streaming inference across a cluster.”
↩︎ Writing your own pandas UDF for model scoring - 5.https://docs.databricks.com/aws/en/udf/pandasOfficial docs
“pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.”
↩︎ Writing your own pandas UDF for model scoring“Spark runs a pandas UDF by splitting the data into batches of rows, calling the function for each batch, and then concatenating the results.”
↩︎ Writing your own pandas UDF for model scoring“loading a machine learning model file to apply inference to every input batch”
↩︎ Writing your own pandas UDF for model scoring“The length of the entire output in the iterator should be the same as the length of the entire input.”
↩︎ Writing your own pandas UDF for model scoring“The wrapped pandas UDF takes multiple Spark columns as an input.”
↩︎ Writing your own pandas UDF for model scoring“loading a machine learning model file to apply inference to every input batch”
↩︎ Exam trap 3“useful when the UDF execution requires initializing some state, for example, loading a machine learning model file to apply inference to every input batch”
↩︎ Checkpoint - 6.https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.pandas_udf.htmlSecondary source
“is the length of an internal batch used for each call to the function.”
↩︎ Writing your own pandas UDF for model scoring - 7.
“It can return output of arbitrary length in contrast to some pandas UDFs such as Series to Series.”
↩︎ DataFrame-level scoring with mapInPandas and applyInPandas“All data for a group is loaded into memory before the function is applied.”
↩︎ DataFrame-level scoring with mapInPandas and applyInPandas“This can lead to out of memory exceptions, especially if the group sizes are skewed.”
↩︎ DataFrame-level scoring with mapInPandas and applyInPandas