Sub topic 13
Batch scoring with automatic feature retrieval
This chapter assumes you can run PySpark in a Databricks notebook and that you have already trained a model and logged it with fe.log_model, as covered in the previous chapter. You should also know the catalog.schema.table naming used by Unity Catalog.
What batch scoring does
Batch scoring means running a model over many rows at once, usually on a schedule, and saving the predictions. Typical examples are a nightly churn score for every active user or a weekly demand forecast per product.
Without a feature table, the scoring job must rebuild every feature the model expects. That code often differs slightly from the training code, which is how training-serving skew starts. With a model logged through FeatureEngineeringClient.log_model, the feature lookups are stored with the model. At scoring time you pass only the lookup keys, and score_batch retrieves the rest.
How the retrieval works
When you logged the model, the training_set object recorded three things: which feature tables were used, which feature names were read from each, and which key joined them. score_batch reads that metadata and then does the following.
- Loads the model from the Unity Catalog model registry.
- Reads the lookup metadata saved with the model.
- Joins the requested features from each feature table onto your input DataFrame, using the lookup keys.
- Calls the model's predict function on the joined result.
- Returns your input columns, the retrieved features, and a
predictioncolumn.
A complete scoring run
The following code scores every user in a table called main.ml.users_to_score. It also saves the output to a Delta table.
from databricks.feature_engineering import FeatureEngineeringClient
import mlflow
mlflow.set_registry_uri("databricks-uc")
fe = FeatureEngineeringClient()
# The input needs only the lookup key. Features are retrieved from the feature table.
batch_df = spark.table("main.ml.users_to_score").select("user_id")
predictions = fe.score_batch(
model_uri="models:/main.ml.churn_model/1",
df=batch_df,
)
predictions.select("user_id", "prediction").write.mode("overwrite").saveAsTable(
"main.ml.churn_predictions"
)The model URI has the form models:/<catalog>.<schema>.<model>/<version>. Pinning a version number makes a job reproducible. If you promote models with aliases, you can use models:/main.ml.churn_model@champion instead, so the job follows the alias without a code change.
What the output contains
The returned DataFrame holds the columns you passed in, the feature columns that were looked up, and a prediction column. Keep only what downstream consumers need, as in the select above. Feature columns are usually large and are already stored in the feature table, so repeating them in the predictions table wastes space.
Overriding a feature
Your input DataFrame can include a column with the same name as a feature the model expects. In that case the value you supply is used and the lookup for that feature is skipped. This is useful for what-if analysis, for example scoring users as if their order_count_90d were 0. It is also an easy way to get wrong results by accident, because a stale column left over in your input silently replaces the feature table value.
Missing keys and missing values
Feature retrieval is a left join from your input. If a user_id has no row in the feature table, the job does not fail. The feature columns for that user come back as null.
What happens next depends on the model. A scikit-learn RandomForestClassifier such as the one in the earlier chapter rejects nulls in older library versions and may raise an error for the whole batch. Some libraries, such as XGBoost and LightGBM, accept nulls and treat them as missing. Either way, handle new users deliberately:
- Make sure the feature pipeline has run for every user in the scoring set before scoring starts.
- Count rows with null features after scoring and alert when the share is above a threshold.
- If you train with imputed values, wrap the model in a pipeline that applies the same imputation, so training and scoring handle gaps the same way.
The following check counts how many scored users had no features.
from pyspark.sql import functions as F
missing = predictions.filter(F.col("order_count_90d").isNull()).count()
total = predictions.count()
print(f"{missing} of {total} users had no feature row")Time series feature tables at scoring time
If the feature table has a time series column, the lookup needs a timestamp. At training time the timestamp came from the labeled event. At scoring time you supply it in the input DataFrame, using the same column name that the lookup used as its timestamp_lookup_key.
For a model trained with timestamp_lookup_key="event_ts", the input might be built like this:
from pyspark.sql import functions as F
batch_df = (
spark.table("main.ml.users_to_score")
.select("user_id")
.withColumn("event_ts", F.current_timestamp())
)
predictions = fe.score_batch(
model_uri="models:/main.ml.churn_model/1",
df=batch_df,
)Each user then receives the most recent feature row at or before that timestamp. Using current_timestamp() means "the latest known values now". Using a past timestamp lets you reproduce what the model would have predicted on an earlier date, provided the feature table still holds the history.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Permission error when loading the model or reading features | The job's identity lacks access to the model or the feature table | Grant `EXECUTE` on the model and `SELECT` on each feature table, plus `USE CATALOG` and `USE SCHEMA` on their parents |
| Error that a lookup key column is missing | The input DataFrame does not contain the key used in the lookup | Select the key column with exactly the logged name and type |
| Model not found | The registry URI is not set to Unity Catalog, or the name is not three-level | Call `mlflow.set_registry_uri("databricks-uc")` and use `catalog.schema.model` |
| Predictions differ from training expectations | A column in the input overrides a feature | Remove stray feature-named columns from the input |
| Many null feature values | New keys have not reached the feature table yet | Run the feature pipeline first, then score |
| Job output changes after a retrain | The URI follows an alias that moved | Pin a version number if you need exact reproducibility |
Operating notes
- Run the feature pipeline and the scoring job as ordered tasks in one Databricks job, so scoring always reads the refreshed table.
- Record the model version and the scoring time with each output row, so you can trace a prediction back to its inputs later.
- Score in partitions if the input is very large.
score_batchworks on a Spark DataFrame, so it scales with the cluster, but the model's predict function still runs per batch of rows, and a heavy model needs a cluster sized for it. - Feature values change as the feature table is updated. A rerun tomorrow with the same model version and the same keys can give different predictions. Use a time series feature table with an explicit timestamp if you need reruns that match.
Exercise
A scoring job calls fe.score_batch with a DataFrame containing user_id and a leftover column order_count_90d from an earlier experiment. The model was logged with a lookup that includes order_count_90d from main.ml.user_features. Which value does the model use for that feature, and how would you prevent the problem?
Show answer
The model uses the value in the input DataFrame, because a column with the same name as a model feature overrides the lookup. Prevent it by selecting only the lookup key columns before calling score_batch, for example df.select("user_id").
Exercise
You score 10,000 users, and 400 of them were created today, after the last feature pipeline run. What does score_batch return for those 400 users, and what two steps would you take?
Show answer
It returns rows for them, with null feature values, because the retrieval is a left join and the feature table has no rows for those keys. The prediction then depends on how the model handles nulls, and it may fail. Run the feature pipeline before scoring so the new users have rows, and add a post-scoring check that counts null features and alerts when the share is too high.