Sub topic 12
Logging a Model with Its Feature Lookups
This chapter assumes you can build a training set with FeatureEngineeringClient.create_training_set, that you know what a feature table and a FeatureLookup are, and that you have used MLflow to log a scikit-learn model. It covers how to log a model so that it carries its feature lookup metadata, what that metadata contains, and the errors that most often appear at this step.
Why package features with the model
A trained model only knows column positions or names. It does not know that order_count_90d came from main.ml.user_features, joined on user_id. If you log the model with plain mlflow.sklearn.log_model, whoever scores it later has to rebuild the same join by hand. Any difference between the training join and the inference join is training-serving skew.
FeatureEngineeringClient.log_model solves this. It logs the model as usual and also stores the feature lookup definitions with it. At inference time the model reads those definitions and fetches feature values by key, so the caller only supplies the lookup keys.
What the training set contributes
The TrainingSet object returned by create_training_set holds three things you need later:
- The feature lookups: table names, feature names, and lookup keys.
- The label column name.
- The columns you excluded, such as
user_id.
training_set.load_df() returns a DataFrame with the joined features and the label. You train on that. You then pass the same training_set object to log_model, which reads the lookup metadata from it.
from databricks.feature_engineering import FeatureEngineeringClient, FeatureLookup
fe = FeatureEngineeringClient()
labels_df = spark.table("main.ml.churn_labels") # user_id, label
feature_lookups = [
FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d", "avg_order_amount_90d"],
lookup_key="user_id",
)
]
training_set = fe.create_training_set(
df=labels_df,
feature_lookups=feature_lookups,
label="label",
exclude_columns=["user_id"],
)
training_df = training_set.load_df()Because user_id is excluded, the training DataFrame contains only the features and the label. The model never sees the key as an input.
Training and logging the model
Train the model on the DataFrame from the training set. Then log it with fe.log_model.
import mlflow
from sklearn.ensemble import RandomForestClassifier
train_pdf = training_df.toPandas()
X = train_pdf.drop(columns=["label"])
y = train_pdf["label"]
model = RandomForestClassifier(n_estimators=100, random_state=42).fit(X, y)
mlflow.set_registry_uri("databricks-uc")
fe.log_model(
model=model,
artifact_path="model",
flavor=mlflow.sklearn,
training_set=training_set,
registered_model_name="main.ml.churn_model",
)The arguments that matter:
| Argument | Purpose |
|---|---|
| `model` | The fitted model object. |
| `artifact_path` | Folder name inside the MLflow run where the model is stored. |
| `flavor` | The MLflow flavor module that knows how to serialize the model, such as `mlflow.sklearn`. |
| `training_set` | The object that supplies the feature lookup metadata. |
| `registered_model_name` | Three-level Unity Catalog name for the registered model. |
Setting the registry URI to databricks-uc makes the registered model a Unity Catalog object. Its name must therefore be catalog.schema.model. If you leave the registry at its default, the call tries to use the workspace model registry, and a three-level name fails there.
How the packaged model works
At logging time, the lookup definitions are stored as part of the model artifact. At inference time, the logged model wraps the original model. It reads the input keys, queries the feature tables named in the metadata, assembles the same columns the model was trained on, and calls the original model.
The consequence is that the feature table is read at inference time, not copied into the model. The model holds references to tables and column names, not feature values. Two things follow:
- Predictions use the current values in the feature table. A refreshed table changes the predictions for the same key.
- The identity of the model depends on the tables still existing, with the same names and columns.
Model signature and input examples
MLflow records a signature, which is the schema of the model's input and output. With fe.log_model, the logged input schema is the set of lookup keys that the caller must supply. The features themselves are produced inside the model. Check the logged model in the MLflow UI or the Unity Catalog model page to confirm it lists the features and their source tables.
Edge cases and common errors
Excluded columns still needed by the model. If you exclude a column from the training set, it is not in training_df, so the model cannot depend on it. Excluding the key is normal. Excluding a feature you later expect at inference is not.
Label left in the features. load_df() returns the label column. If you forget to drop it before fitting, the model trains on the answer. Always drop the label from X, as the example does.
Training on a different DataFrame than the training set. Logging a model trained on data not derived from training_set records lookups that do not match the model's real input columns. Inference then fails or returns wrong results. Train only on training_set.load_df() output, or on columns derived from it without renaming them.
Column order and names. The columns the model expects at inference come from the lookups, in the lookup order. Reordering or renaming columns between training and logging breaks that match.
Registry mismatch. A two-level name or a missing mlflow.set_registry_uri("databricks-uc") produces a registry error. Set the URI before logging.
Missing permissions. Logging to main.ml.churn_model needs permission to create models in the main.ml schema. Scoring later requires read access to the feature tables as well as the model. A user who can run the model but cannot read main.ml.user_features sees a permission error at inference.
Dropped or changed features. If someone drops order_count_90d from the feature table, or changes its meaning, a model already logged against it either fails or silently scores on different values. Treat features used by registered models as a contract. Add new columns instead of changing existing ones, and create new feature names for changed definitions.
Time series features. If the training set used a timestamp_lookup_key, the logged lookups include it. The scoring input must then also contain that timestamp column, so each row is looked up as of its own time.
Verifying the logged model
After logging, a quick check confirms that the model really carries its lookups. Scoring with keys only should work without errors:
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").show(5)If this fails with a missing column error, the lookups were not recorded the way you expected. Return to the training step and check that you passed training_set to log_model. Batch scoring is covered in more detail in the next chapter.
Summary of the workflow
- Build a
training_setfrom labels and feature lookups. - Call
load_df()and train only on that output. - Set the registry URI to
databricks-uc. - Call
fe.log_modelwith the fitted model, the flavor, thetraining_set, and a three-level model name. - Confirm the logged model scores with keys only.
Exercise
A teammate logs a churn model with mlflow.sklearn.log_model, not fe.log_model. Scoring with fe.score_batch and only user_id fails. Why, and what do they change?
Show answer
Plain mlflow.sklearn.log_model does not store the feature lookup metadata, so the model has no record of which feature tables and keys to query. It expects every feature column in the input. The fix is to build the model from a training_set made with create_training_set, then log it with fe.log_model(..., flavor=mlflow.sklearn, training_set=training_set, registered_model_name=...), after setting mlflow.set_registry_uri("databricks-uc").
Exercise
A model version is in production. A data engineer proposes redefining avg_order_amount_90d in the feature table to use a 30-day window. What risk does this create, and what is a safer approach?
Show answer
The logged model stores a reference to the column name, so it will start reading the new 30-day values at inference while it was trained on 90-day values. That changes the input distribution without any error. The safer approach is to add a new column, such as avg_order_amount_30d, train and log a new model version on it, and leave the original column unchanged until the old model is retired.