Overview
A model learns from features that were prepared in a certain way: missing values filled, numbers scaled, categories turned into 0/1 columns. At serving time each request must be prepared in exactly the same way, with the same numbers. If serving scales with a slightly different mean, the model receives inputs it was never trained on and gets worse without any error. This gap is called training/serving skew. The cure is to fit the preparation once, save it as a file, and have both sides use that file and the same code path.
A short history
This practice answers training-serving skew, the gap that opens when features are computed one way for training and another way in production. It has no single inventor. The 2015 paper Hidden Technical Debt in Machine Learning Systems by Sculley and colleagues at Google drew wide attention to such data dependencies. Common remedies followed: fitted pipeline objects saved with the model, as in scikit-learn, and libraries such as TensorFlow Transform that export the training transforms for serving.
How it works
- Call
fiton the training records with the names of the numeric and categorical fields. It learns a fill value, an offset and a scale per numeric field and the list of categories per categorical field. transform_oneturns one record into a feature vector: fill, then scale each number, then set a 1 in the position of each category.- The batch
transformused in training callstransform_onefor every record, so training and serving share one code path. savewrites the fitted state as JSON and returns a SHA-256 fingerprint of it. Store the fingerprint with the model.- The serving process calls
load(path, expected=fingerprint). It raisesSkewErrorif the file was edited or is not the one the model was trained with. - At request time a missing field is filled with the training statistic and an unseen category becomes an all-zero block, unless the config turns these into errors.
Watch out for
- Reimplementing the transforms in the serving code, even carefully, lets the two versions drift apart over time. Use the saved artifact, not a rewrite.
- Filling a missing field hides the fact that it was missing. If a client stops sending a field, every request is quietly filled and the model degrades. Count imputations, or set
on_missingto error. - An unseen category becomes all zeros, a pattern the model may never have met in training. A rising share of unknowns means the model needs retraining.
- Refitting the preprocessor on new data without retraining the model changes the fingerprint, and the check will refuse it. That is the check working as intended.
- The fingerprint proves the artifact matches. It does not prove the incoming data is still like the training data.
Use cases
When to use it
Whenever a model is trained in one place and served in another. Ship the preprocessing artifact and the model together and check the fingerprint at start-up.
In industry
- Lending
- A credit model is trained by analysts in notebooks and served by a separate application. Shipping one fitted preprocessing artifact keeps both sides computing identical features.
- E-commerce
- A recommendation service checks the fingerprint of its preprocessing artifact at start-up and refuses to run if it does not match the one the model was trained with.
- Mobile and edge
- The scaling constants and category lists learned in training are exported as plain data, so an app on a device applies the same transforms offline.
Choosing it: what must hold
- A model trained in one place and served in another.
- Transforms that depend only on the single record and on values fixed at training time.
- The preprocessing artifact and the model versioned and deployed together.
- Requests that carry the same field names as the training records.
When to choose something else
| If | Use instead |
|---|---|
| Features need history or aggregates, such as a count over the last hour | A feature store or a precomputed table built by batch inference |
| Training and scoring happen in the same process | The cleaning, scaling and encoding lessons fitted and applied directly |
| Incoming requests may be malformed | Schema-first data validation in front of this step |
Math foundations
Scaling with training statistics
Every number in the formula except was fixed at training time. Serving must not recompute any of them from live data.
One-hot block of a categorical field
One position per category seen in training. A value never seen sets no position, which gives an all-zero block.
Width of the feature vector
One output per numeric field plus one per known category of each categorical field. The order is fixed, so position means the same thing in training and serving.
The fingerprint
A hash of the fitted numbers written in a fixed key order. Any change to any number gives a different hash, so equal fingerprints mean identical transforms.
Symbols
- raw value of numeric field j in a request
- the value after filling a missing one
- training median or mean used to fill field j
- offset and scale of field j learned in training
- scaled feature
- set of categories of field f seen in training
- number of output features
- fingerprint of the fitted state
Worked by hand
Training records have ages 30, 50, 40, incomes 4000, 6000 and one missing, and plans free, pro, pro. A request arrives with age 40, no income and the plan gold.
The request maps to four zeros: an average age, an imputed income and an unknown plan. Nothing failed, which is exactly why imputations and unknowns should be counted.
Visual example
Loading the example.
Try this
- Leave the request as it is: an average age, a missing income and an unknown plan give four zeros and no error.
- Choose the edited artifact: load recomputes the fingerprint and refuses to serve.
- Move the age in the request and check the scaled value against the training mean and spread in the fit node.
Code sample
import os, tempfile
from impl import Preprocessor
from config import ServePreprocessConfig
train = [
{"age": 30, "income": 4000.0, "plan": "free"},
{"age": 50, "income": 6000.0, "plan": "pro"},
{"age": 40, "income": None, "plan": "pro"},
]
pre = Preprocessor(ServePreprocessConfig()).fit(train, numeric=["age", "income"], categorical=["plan"])
X_train = pre.transform(train) # shape (3, 4), fit the model on this
path = os.path.join(tempfile.mkdtemp(), "preprocess.json")
fingerprint = pre.save(path) # keep the fingerprint with the model
serving = Preprocessor.load(path, expected=fingerprint) # in the serving process
print(serving.feature_names()) # ['age', 'income', 'plan=free', 'plan=pro']
print(serving.transform_one({"age": "40", "plan": "gold"})) # [0. 0. 0. 0.]: mean age, imputed income, unknown planRead the implementation (175 lines)
"""Serve-time preprocessing that is guaranteed to match training.
Standard library and NumPy only. The transform is fitted ONCE on the training records, saved as a JSON
artifact next to the model, and loaded by the serving process, which then runs the very same code on single
requests. A fingerprint (SHA-256 of the fitted state) is stored with the model so serving can refuse to
start with a preprocessing artifact the model was not trained with. This removes training/serving skew,
the bug where the two sides compute a feature slightly differently.
A record is a dict such as {"age": 31, "income": 5200.0, "plan": "pro"}.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
import numpy as np
try:
from .config import ServePreprocessConfig
except ImportError: # run from the template's own folder
from config import ServePreprocessConfig
class SkewError(RuntimeError):
"""The preprocessing artifact is not the one the model was trained with, or it was altered."""
def _missing(value) -> bool:
return value is None or (isinstance(value, float) and math.isnan(value))
class Preprocessor:
"""Impute and scale numeric fields, one-hot encode categorical fields, in a fixed column order.
After `fit` the whole learned state lives in `state_`, a plain dict:
numeric names of the numeric fields, in output order
categorical names of the categorical fields, in output order
fill per numeric field, the value used for a missing input
offset, scale per numeric field, output = (x - offset) / scale
categories per categorical field, the sorted list of known values (as strings)
"""
def __init__(self, config: ServePreprocessConfig | None = None) -> None:
self.config = config or ServePreprocessConfig()
self.state_: dict | None = None
# ---------------------------------------------------------------------------------------------- fit
def fit(self, records: list[dict], numeric: list[str], categorical: list[str]) -> "Preprocessor":
"""Learn the statistics from training records.
records: list of dicts. numeric / categorical: the field names to use, in output order.
"""
if not records:
raise ValueError("cannot fit on zero records")
cfg = self.config
fill, offset, scale = [], [], []
for name in numeric:
values = np.array([float(r[name]) for r in records if not _missing(r.get(name))])
if values.size == 0:
raise ValueError(f"numeric field {name!r} has no values in the training records")
centre = float(np.median(values) if cfg.numeric_impute == "median" else values.mean())
if cfg.scale == "standard":
shift, spread = float(values.mean()), float(values.std())
elif cfg.scale == "minmax":
shift, spread = float(values.min()), float(values.max() - values.min())
else:
shift, spread = 0.0, 1.0
fill.append(centre)
offset.append(shift)
scale.append(spread if spread > 0 else 1.0) # a constant field maps to a constant
categories = [
sorted({str(r[name]) for r in records if not _missing(r.get(name))}) for name in categorical
]
self.state_ = {
"config": cfg.to_dict(),
"numeric": list(numeric),
"categorical": list(categorical),
"fill": fill,
"offset": offset,
"scale": scale,
"categories": categories,
}
return self
def _state(self) -> dict:
if self.state_ is None:
raise RuntimeError("call fit or load first")
return self.state_
# ---------------------------------------------------------------------------------------- transform
def transform_one(self, record: dict) -> np.ndarray:
"""Feature vector for ONE record, shape (n_features,). This is the serving path."""
state, cfg = self._state(), self.config
out = np.zeros(self.n_features)
for j, name in enumerate(state["numeric"]):
value = record.get(name)
if _missing(value):
if cfg.on_missing == "error":
raise ValueError(f"field {name!r} is missing")
value = state["fill"][j]
try:
value = float(value) # also accepts numbers that arrive as strings, as JSON clients send them
except (TypeError, ValueError):
raise ValueError(f"field {name!r} must be a number, got {value!r}") from None
out[j] = (value - state["offset"][j]) / state["scale"][j]
position = len(state["numeric"])
for name, known in zip(state["categorical"], state["categories"]):
value = record.get(name)
if _missing(value) and cfg.on_missing == "error":
raise ValueError(f"field {name!r} is missing")
label = None if _missing(value) else str(value)
if label in known:
out[position + known.index(label)] = 1.0
elif label is not None and cfg.handle_unknown == "error":
raise ValueError(f"field {name!r} has the unknown category {label!r}")
position += len(known)
return out
def transform(self, records: list[dict]) -> np.ndarray:
"""Feature matrix for many records, shape (n_records, n_features).
It is built by calling `transform_one` per record on purpose: training and serving then share one
code path and cannot drift apart.
"""
return np.stack([self.transform_one(r) for r in records]) if records else np.zeros((0, self.n_features))
@property
def n_features(self) -> int:
state = self._state()
return len(state["numeric"]) + sum(len(known) for known in state["categories"])
def feature_names(self) -> list[str]:
"""Name of every output column, for example ["age", "income", "plan=free", "plan=pro"]."""
state = self._state()
names = list(state["numeric"])
for name, known in zip(state["categorical"], state["categories"]):
names.extend(f"{name}={label}" for label in known)
return names
# ----------------------------------------------------------------------------------------- artifact
def fingerprint(self) -> str:
"""SHA-256 of the fitted state. Equal fingerprints mean identical transforms."""
canonical = json.dumps(self._state(), sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def save(self, path: str) -> str:
"""Write the artifact (state plus fingerprint) as JSON and return the fingerprint.
Store the returned fingerprint with the model so serving can call `load(path, expected=...)`.
"""
mark = self.fingerprint()
with open(path + ".tmp", "w", encoding="utf-8") as handle:
json.dump({"fingerprint": mark, "state": self._state()}, handle, indent=2)
os.replace(path + ".tmp", path)
return mark
@classmethod
def load(cls, path: str, expected: str | None = None) -> "Preprocessor":
"""Rebuild a fitted preprocessor from an artifact.
Raises SkewError when the file was changed after saving, or when `expected` (the fingerprint
recorded with the model at training time) does not match the artifact.
"""
with open(path, encoding="utf-8") as handle:
artifact = json.load(handle)
loaded = cls(ServePreprocessConfig.from_dict(artifact["state"]["config"]))
loaded.state_ = artifact["state"]
actual = loaded.fingerprint()
if actual != artifact["fingerprint"]:
raise SkewError(f"{path} was modified after it was saved")
if expected is not None and actual != expected:
raise SkewError(f"{path} has fingerprint {actual[:12]}, the model was trained with {expected[:12]}")
return loaded- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Fit Preprocessor(ServePreprocessConfig()) on the three training records above, call save(path) and keep the fingerprint. Load it with Preprocessor.load(path, expected=fingerprint) and run transform_one on a request. Then change one number in the JSON file by hand, load again, and read the SkewError.
Check on learning
- Training computed the mean income over one year. The serving team recomputes it from last week's requests because it is fresher. Why is the fresher number worse for the model?
A way to think about it
The model's weights were fitted to inputs scaled with the old number. Ask what a typical customer's scaled income becomes under the new one.
- Why does the batch
transformcalltransform_onerow by row when a vectorised version would be faster?A way to think about it
Two implementations of the same transform are two chances to differ. Weigh the speed against the cost of a difference nobody notices.
- A client's app update stops sending the income field. No request fails. How would the problem show itself, and what could have caught it on day one?
A way to think about it
Every request now carries the same filled income. Think about a counter of imputed fields, and about the
on_missingsetting. - The fingerprints match, yet the live model performs worse than it did offline. Name a cause the fingerprint cannot detect.
A way to think about it
The fingerprint covers the transform, not the data flowing through it. Consider what happens when the customers themselves change.
- An unseen category is encoded as all zeros. When is that a reasonable fallback and when is it dangerous?
A way to think about it
Ask whether the model saw all-zero blocks in training. If it never did, its output for that pattern was never checked.