Sub topic 1
Two Paths to the Same Model: Training and Serving
Prerequisites
This chapter assumes you can read basic Python and pandas, and that you know the supervised learning workflow of train, validate, and predict. You should also have a general idea of what it means to put a model behind an API or a batch job. Basic statistics (mean, variance, histograms) help in the later examples. You do not need any experience with feature stores or monitoring tools.
Why this chapter comes first
Most bugs in a machine learning system are not in the model. They are in the data that reaches the model. A model is a function that was fitted on inputs of one particular shape, scale, and meaning. If production hands it inputs with a different shape, scale, or meaning, it still returns an answer. It does not raise an error.
To see how that happens, you need a clear picture of the two paths that data takes to reach the same model. This chapter builds that picture. Later chapters in this tutorial use it to define training-serving skew and to examine its causes.
The two paths
A model artifact, such as a saved set of weights, is produced once and used many times. Data reaches it by two different routes.
- The training path reads historical data, turns it into features, and fits the model. It runs offline, usually in batch, and it can take minutes or hours.
- The serving path receives new data, turns it into the same features, and asks the model for a prediction. It runs online (one request at a time, under a latency limit) or in a scheduled batch job.
A feature is a numeric or categorical input derived from raw data, such as "logins in the last 30 days" or "age after filling missing values". Both paths must produce the same features from the same underlying facts. If they do not, the model sees something it was not trained on.
The diagram shows two places where the paths can diverge: the feature code boxes and the data sources feeding them. The model artifact in the middle is the only component that both paths share by default.
How the paths usually differ
The two paths have different jobs, so teams build them with different tools. The differences are normal and often reasonable. They are also where problems start.
| Aspect | Training path | Serving path |
|---|---|---|
| Data source | Warehouse tables, data lake files | Request payload, operational database, cache |
| Volume | Millions of rows at once | One row, or a small batch |
| Latency | Minutes to hours is fine | Milliseconds to seconds |
| Typical tools | SQL, Spark, pandas | A web service, a stream processor, a lightweight handler |
| Time view | Historical: all events are already known | Live: only events up to now exist |
| Who writes it | Data scientists | Software or platform engineers |
| Failure signal | Job fails or metrics look wrong | Often none |
Each row is a possible source of mismatch. A SQL aggregation in the warehouse and a Python function in the service may both claim to compute "average order value", yet round, filter, or handle nulls differently. The warehouse may contain corrected records that the live system had not yet received when the prediction was made. Different authors may read the same specification in different ways.
A small example of divergence
The next snippet shows the problem at its simplest. The feature is age. In training, missing ages are filled with the training mean. In serving, a separately written handler fills them 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}The training set never contains an age near 0. The model learned a relationship over ages from 30 to 50. In production, every request with a missing age arrives as 0, far outside anything the model saw. For a linear model, that value pushes the score a long way in one direction. For a tree, it falls into the lowest branch. In both cases the result is a confident prediction that is wrong.
Nothing in this code fails. Both functions run and both return valid numbers. The mismatch is only visible if you compare the two outputs side by side.
Why the mismatch is silent
Several properties of the two-path design make these errors hard to notice.
- Types still match. Both paths produce a number in the
agecolumn. A schema check on type alone passes. - The model does not validate inputs. It was fitted to accept any numeric vector of the right length.
- Labels arrive late. In many systems you only learn whether a prediction was right days or weeks later, so accuracy drops appear slowly and are easy to blame on something else.
- Offline metrics look fine. Validation runs through the training path, so it never exercises the serving code.
The last point is important. A held-out test set measured through the training path tells you how the model performs on training-path features. It says nothing about how the serving path will feed it.
The model is only half the artifact
It is natural to think of "the model" as the weights file. For serving, what matters is the model plus everything that turns raw input into the vector the weights expect. That includes:
- the feature logic itself (filters, joins, aggregations, windows);
- values learned during training, such as imputation means, scaling statistics, and category vocabularies;
- decisions about missing or unknown values;
- the order and names of columns.
If these pieces live in two separate codebases, they must be kept identical by hand. Manual synchronization breaks over time as people change one side and forget the other. The prevention chapters later in this tutorial focus on removing that duplication.
Mapping the paths to your own system
Before you can look for skew, you need to know where your two paths actually are. A practical way to do this is to answer five questions for each feature the model uses.
- Where does the raw data come from in training, and where does it come from in serving?
- Which code turns the raw data into the feature in each path? Is it the same code?
- Which values were computed during training and must be reused (means, vocabularies)? Where are they stored?
- At what point in time is the feature computed for a training row, and at what point for a live request?
- What happens in each path when the value is missing, malformed, or new?
Write the answers in a table with one row per feature. Rows where the two columns differ, or where nobody knows the answer, are the first places to inspect.
import pandas as pd
audit = pd.DataFrame([
{
"feature": "age",
"train_source": "warehouse.users",
"serve_source": "request payload",
"same_code": False,
"missing_rule_train": "fill with training mean",
"missing_rule_serve": "fill with 0",
},
{
"feature": "logins_30d",
"train_source": "warehouse.events",
"serve_source": "events cache",
"same_code": False,
"missing_rule_train": "count is 0",
"missing_rule_serve": "count is 0",
},
])
suspects = audit[
(~audit["same_code"])
| (audit["missing_rule_train"] != audit["missing_rule_serve"])
]
print(suspects[["feature", "same_code", "missing_rule_train", "missing_rule_serve"]])This script lists every feature whose code is not shared or whose missing-value rules differ. For this audit, both features are flagged: age for both reasons, and logins_30d because its code is not shared. That is the correct outcome. Matching missing-value rules do not prove that the code agrees in every other case.
Batch and online serving are both serving
Serving does not always mean a real-time API. A nightly batch scoring job is also a serving path. It often reads from different tables than training does, applies its own SQL, and runs on a different schedule. Teams sometimes assume batch scoring cannot have skew because "it uses the same warehouse". The shared warehouse removes one source of difference, but not code, time, or fitted-state differences. Treat any code that produces features for a prediction outside the training job as a serving path.
Key points
- A trained model is consumed through two paths: training builds features from history, and serving builds them from live data.
- The paths differ in data source, tooling, latency, time view, and ownership, so they tend to diverge.
- Divergence causes no error, because types and shapes still match and offline validation never touches serving code.
- The deployable unit is the weights plus the feature logic and fitted values that feed them.
- A per-feature audit of source, code, fitted state, timing, and missing-value handling shows where to look first.
Exercise
A team validates a churn model with a held-out test set and gets an AUC of 0.91. After deployment, business results are much worse than expected, yet the service reports no errors. Give two reasons the offline AUC does not rule out a serving problem, and name one audit question from this chapter that would help find the cause.
Show answer
First, the test set passes through the training path, so the score measures the model on training-path features and never exercises the serving feature code. Second, the model accepts any numeric vector of the right shape, so a serving feature with a different meaning or fill value produces no error, only worse predictions. Useful audit questions include "Which code turns the raw data into the feature in each path, and is it the same code?" and "What happens in each path when the value is missing, malformed, or new?" Either one would expose a difference such as a different missing-value rule.
Exercise
In the age example, training fills missing ages with 40.0 and serving fills them with 0. Why is this a problem for a model trained on ages between 30 and 50, even though both values are valid numbers?
Show answer
The model only learned the relationship between age and the label over the range of values it saw, roughly 30 to 50. A value of 0 lies far outside that range, so the model extrapolates or lands in an unintended branch, and it gives a confident but unreliable prediction for every request with a missing age. The values are valid numbers, so no type or shape check detects the problem.