Sign in

Preprocess

Serve-time preprocessing

A serve-time preprocessor that applies exactly the training transforms to each request, shipped as a fingerprinted artifact so the two sides cannot drift apart.

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

  1. Call fit on 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.
  2. transform_one turns one record into a feature vector: fill, then scale each number, then set a 1 in the position of each category.
  3. The batch transform used in training calls transform_one for every record, so training and serving share one code path.
  4. save writes the fitted state as JSON and returns a SHA-256 fingerprint of it. Store the fingerprint with the model.
  5. The serving process calls load(path, expected=fingerprint). It raises SkewError if the file was edited or is not the one the model was trained with.
  6. 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_missing to 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

IfUse instead
Features need history or aggregates, such as a count over the last hourA feature store or a precomputed table built by batch inference
Training and scoring happen in the same processThe cleaning, scaling and encoding lessons fitted and applied directly
Incoming requests may be malformedSchema-first data validation in front of this step

Math foundations

  1. Scaling with training statistics

    zj=x~j−μjtrainσjtrain,x~j={xjif presentmjtrainif missingz_j = \frac{\tilde{x}_j - \mu_j^{\text{train}}}{\sigma_j^{\text{train}}}, \qquad \tilde{x}_j = \begin{cases} x_j & \text{if present} \\ m_j^{\text{train}} & \text{if missing} \end{cases}

    Every number in the formula except xjx_j was fixed at training time. Serving must not recompute any of them from live data.

  2. One-hot block of a categorical field

    ek={1if the value equals the k-th known category0otherwisee_k = \begin{cases} 1 & \text{if the value equals the } k\text{-th known category} \\ 0 & \text{otherwise} \end{cases}

    One position per category seen in training. A value never seen sets no position, which gives an all-zero block.

  3. Width of the feature vector

    d=nnum+∑f=1ncat∣Cf∣d = n_{\text{num}} + \sum_{f=1}^{n_{\text{cat}}} |C_f|

    One output per numeric field plus one per known category of each categorical field. The order is fixed, so position ii means the same thing in training and serving.

  4. The fingerprint

    h=SHA256⁡(canonical JSON⁡(state)),load succeeds  ⟺  hartifact=hexpectedh = \operatorname{SHA256}\big(\operatorname{canonical\ JSON}(\text{state})\big), \qquad \text{load succeeds} \iff h_{\text{artifact}} = h_{\text{expected}}

    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

xjx_j
raw value of numeric field j in a request
x~j\tilde{x}_j
the value after filling a missing one
mjtrainm_j^{\text{train}}
training median or mean used to fill field j
μjtrain, σjtrain\mu_j^{\text{train}},\, \sigma_j^{\text{train}}
offset and scale of field j learned in training
zjz_j
scaled feature
CfC_f
set of categories of field f seen in training
dd
number of output features
hh
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.

μage=40,σage=102+102+023=8.165,zage=40−408.165=0\mu_{\text{age}} = 40, \qquad \sigma_{\text{age}} = \sqrt{\frac{10^2 + 10^2 + 0^2}{3}} = 8.165, \qquad z_{\text{age}} = \frac{40 - 40}{8.165} = 0
mincome=5000,μincome=5000,σincome=1000,zincome=5000−50001000=0m_{\text{income}} = 5000, \quad \mu_{\text{income}} = 5000, \quad \sigma_{\text{income}} = 1000, \qquad z_{\text{income}} = \frac{5000 - 5000}{1000} = 0
plan=gold∉{free, pro}  ⇒  (0,  0)\text{plan} = \text{gold} \notin \{\text{free},\, \text{pro}\} \;\Rightarrow\; (0,\; 0)
d=2+2=4,output=(0,  0,  0,  0)d = 2 + 2 = 4, \qquad \text{output} = (0,\; 0,\; 0,\; 0)

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 plan
Read 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

  1. 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.

  2. Why does the batch transform call transform_one row 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.

  3. 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_missing setting.

  4. 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.

  5. 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.