Sub topic 2
What training-serving skew is and why it fails silently
This chapter assumes you know the basic supervised learning workflow (train, validate, predict), can read Python and pandas, and have a general idea of how a model is deployed behind an API or a batch job. It also assumes you are comfortable with means, variances, and histograms.
Definition
Training-serving skew is a difference between the features a model saw during training and the features it receives in production, for the same underlying entity at the same moment. The model is a fixed function. If the inputs it gets in production are computed differently from the inputs it learned from, its outputs are no longer what you validated.
Two points in this definition matter.
- The difference is in the feature values or their distribution, not in the real world. A customer's true age did not change. The pipeline that turned "age" into a number changed.
- The comparison is between two code paths or data paths you own. That makes skew a bug in your system, and it can usually be fixed. Drift, covered in the next chapter, is a change in the world.
Two paths to one model
Every deployed model has a training path and a serving path. Both turn raw data into a feature vector, but they often run in different places, on different data, and in different code.
| Aspect | Training path | Serving path |
|---|---|---|
| Data source | Warehouse tables, files, historical logs | Request payload, online database, cache |
| Execution | Batch jobs over millions of rows | One request or a small batch, low latency |
| Typical code | SQL, pandas, Spark | A service in another language or framework |
| Time | Past, with known outcomes | Present, outcome unknown |
| Failure visibility | Metrics on a validation set | Often none, because labels arrive late or never |
Skew is any mismatch where these two columns produce different numbers for what should be the same feature.
A concrete example
The simplest skew is two implementations of one feature with different missing-value rules. Training fills a missing age with the training mean. A separately written serving handler fills it with 0.
import pandas as pd
# Training path: missing ages are filled with the training mean (40.0)
train = pd.DataFrame({"age": [30, 40, None, 50]})
train["age"] = train["age"].fillna(train["age"].mean())
# Serving path: a separately written handler fills missing ages with 0
def serve_features(request: dict) -> dict:
return {"age": request.get("age") or 0}
print(train["age"].tolist()) # [30.0, 40.0, 40.0, 50.0]
print(serve_features({"age": None})) # {'age': 0}For the same input (age unknown), the model sees 40 during training and 0 in production. Age 0 is far outside anything the model saw, so it sits in a region where the model's behavior is arbitrary. A tree model may route the row down an unusual branch. A linear model extrapolates along a coefficient that was never fitted for that value.
The code also contains a second, subtler bug. request.get("age") or 0 treats a real age of 0 the same as a missing one. That is harmless for ages but wrong for features such as "number of purchases", where 0 is a real value and missing is not. Small shortcuts like this are how skew enters.
Why it fails silently
Most software bugs announce themselves with an exception, a failed request, or a wrong status code. Skew does not, for several reasons.
- The types are valid.
0is a valid float. The model accepts any number and returns a probability. Nothing in the request path raises an error. - The output is plausible. A classifier always returns a score between 0 and 1. A degraded model returns scores that look like normal scores.
- Offline metrics are computed on the training path. Your validation AUC comes from features produced by the batch code. It describes the model fed by that code. It says nothing about the model fed by the serving code.
- Labels arrive late. For churn, fraud chargebacks, or loan defaults, ground truth can take weeks. By the time live accuracy is measurable, the damage is done.
- Degradation is gradual and diluted. If only 5% of requests have a missing age, overall accuracy drops by a small amount that hides inside normal week-to-week variance.
- Monitoring watches the wrong layer. Latency, error rate, and CPU stay healthy because the service is working exactly as coded.
The result is a model that is healthy by every operational measure and quietly worse in business terms.
What a skewed feature looks like
Skew shows up as a change in a feature's distribution between the two paths. The shift in the example above is large enough to see without any test.
import numpy as np
rng = np.random.default_rng(0)
train_age = rng.normal(40, 10, 5000)
serving_age = np.where(rng.random(5000) < 0.05, 0.0, rng.normal(40, 10, 5000))
print(f"train mean={train_age.mean():.1f}, serving mean={serving_age.mean():.1f}")
print(f"serving share equal to 0: {(serving_age == 0).mean():.1%}")The means differ by about two units, which is easy to dismiss. The spike of exact zeros is the real signal. Summary statistics can hide a problem that a histogram or a count of special values reveals. Later chapters cover Population Stability Index (PSI) and the Kolmogorov-Smirnov (KS) test, which formalize this comparison.
Common forms of skew
Each of these gets its own chapter. For now, learn to recognize them.
- Duplicated feature logic. The same feature is written once for training and once for serving, and the two diverge.
- Fit-time state. Means, medians, scaling factors, and category vocabularies are computed on training data and not carried to serving.
- Different sources and schemas. Training reads a cleaned warehouse table. Serving reads a raw operational database with different units, types, or null handling.
- Time leakage. Training rows include information that would not have existed at prediction time, so offline scores are optimistic.
The last one is easy to misjudge. It does not make production features wrong. It makes the training features too good, so the model learns a shortcut that is unavailable when it is served.
Skew is a property of the pipeline, not the model
A useful habit is to treat skew as a question about the feature pipeline. Ask: for one entity at one timestamp, would the batch path and the online path produce byte-for-byte the same feature vector? If the answer is "probably", you have a risk. If the answer is "I can test that", you have a control.
This framing also tells you where fixes belong. Retraining on more data does not repair skew, because the new training data still comes from the batch path. The mismatch has to be removed in the pipeline.
Summary of key ideas
- Skew is a difference in feature values between training and serving for the same input.
- It is caused by your own pipelines, which makes it preventable.
- It fails silently because the model accepts any valid number, offline metrics never exercise the serving path, and labels arrive late.
- It is found by comparing feature values or distributions, not by watching errors and latency.
Exercise
A fraud model has a validation AUC of 0.94. After deployment, latency and error rate are normal, but the fraud team reports it is catching far fewer cases. The training code fills a missing "transactioncount7d" with the column median, and the serving code fills it with 0. Explain why no alarm fired, and name one inexpensive check that would have exposed the problem.
Show answer
No alarm fired because 0 is a valid number, so the model returned normal-looking scores and the service returned 200. The validation AUC was computed from features built by the training code, so it never exercised the serving fill rule. Operational metrics (latency, errors) only show that the service runs, not that its inputs match training. A cheap check is to log the served feature values and compare their distribution with the training set. A spike of exact zeros in "transactioncount7d" would show up immediately. Rebuilding the features for a few logged requests with the training code and diffing the vectors would also find it.
Exercise
Why does retraining the model on fresh data not fix training-serving skew caused by two different missing-value rules?
Show answer
The retraining data is still produced by the batch path, so the model again learns from features filled the training way. The serving path still fills values the other way, so the mismatch remains. The fix is to make both paths use one missing-value rule, not to change the amount or freshness of the training data.