Sub topic 3
Prevention and Detection of Training-Serving Skew
This chapter assumes you can write Python with pandas, have trained a supervised model, and understand a mean, a variance, and a histogram. You should also know how a model is served behind an API or a batch job.
Validating inputs at serving time
Validate every request before it reaches the model. Check that required features exist, that values fall in plausible ranges, and that categories are known. Reject bad requests or route them to a fallback. Do not fill missing values with a silent default such as 0.
EXPECTED_RANGES = {"age": (0, 120), "income": (0, 1e7)}
def validate_request(row: dict) -> None:
for name, (low, high) in EXPECTED_RANGES.items():
value = row.get(name)
if value is None:
raise ValueError(f"missing feature: {name}")
if not low <= value <= high:
raise ValueError(f"out of range: {name}={value}")Testing offline and online parity
Run the same raw events through the training transform and the serving transform. Then assert that the outputs match.
import pandas as pd
from pandas.testing import assert_frame_equal
def test_offline_online_parity(offline_transform, online_transform, raw_events):
offline = offline_transform(pd.DataFrame(raw_events))
online = pd.DataFrame([online_transform(event) for event in raw_events])
assert_frame_equal(
offline.reset_index(drop=True),
online[offline.columns].reset_index(drop=True),
check_exact=False,
rtol=1e-6,
)Detecting skew in production
Logging serving features
Log the feature values the model actually received, not the raw request. Store them with the prediction and a timestamp.
Comparing distributions with PSI and the KS test
The Population Stability Index (PSI) measures how far the logged serving values have moved from the training distribution. A common rule of thumb treats a PSI above 0.25 as a strong signal to investigate. The two-sample Kolmogorov-Smirnov (KS) test checks whether two numeric samples plausibly come from the same distribution. Use scipy.stats.ks_2samp for this.
> Callout: a silent default hides skew. Fail loudly on missing values, or log every fallback so you can count it.
Shadow deployments and canary releases
Before switching traffic, run the new model in shadow mode. It scores real requests, but its predictions are not returned to users. Compare its features and predictions with the current model. Then send a small share of live traffic, such as 5 percent, to the new model as a canary. Increase the share only when the metrics stay stable.
Responding to skew
Triage first. Find which feature moved and check whether the cause is a bug, an upstream change, or real change in the world. Roll back if users are affected. Fix the pipeline if the serving code differs from training. Retrain only when the data has changed in a way the model must learn.
Exercise
A feature income is filled with 0 when missing at serving time, but with the training median at training time. Which check would catch this, and which metric would show it?
Show answer
Parity testing catches it because the offline and online transforms give different values for the same missing input. PSI or the KS test on logged income values shows it because the serving distribution gains a spike at 0.