Sub topic 2
Breaking Training into Stages with Clear Interfaces
This chapter assumes you can write Python functions and dataclasses, know the train/validate/test workflow, and have used scikit-learn. It covers how to split a training notebook into stages. A stage is a unit of work with declared inputs and outputs. The chapter also covers the mistakes that make stages hard to test and reuse.
Why stage boundaries matter
A notebook usually runs top to bottom in one namespace. A variable defined in cell 3 gets used in cell 17, and nothing records that dependency. You can run cells out of order, rerun one cell after editing another, and end up with a model that no saved code can reproduce.
A stage replaces that shared namespace with a contract:
- The stage receives everything it needs as arguments.
- The stage returns everything it produces as return values.
- The stage reads no global state and changes none.
This contract gives you three things. You can test a stage alone with small fake inputs. You can see what each stage depends on, which later chapters use to build a dependency graph and to cache results. You can replace one stage, such as the model, without touching the others.
The stage contract
In this tutorial a stage is a plain Python function. The rules below keep it testable.
- Explicit inputs. Every value the stage uses is a parameter. This includes the configuration.
- Explicit outputs. Results leave through the return value, not through assignment to a module-level variable.
- No hidden state. The stage does not read environment variables, the clock, or global random state unless you pass the value in.
- Narrow responsibility. A stage does one thing that you can name in a short phrase: "load data", "split", "train", "evaluate".
The configuration used in this chapter is the frozen dataclass from the plan:
import dataclasses
import hashlib
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
min_accuracy: float = 0.8
def config_fingerprint(cfg: TrainConfig) -> str:
payload = json.dumps(dataclasses.asdict(cfg), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:12]Setting frozen=True means a stage cannot change the configuration while it runs. If a stage tries to assign cfg.seed = 7, Python raises FrozenInstanceError. A later chapter covers configuration in more detail. Here it matters only as an argument that every stage can receive safely.
Four stages for a classifier
A small classification workflow breaks into four stages. Each is a function:
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
def load_data():
X, y = load_iris(return_X_y=True)
return X, y
def split(X, y, cfg):
return train_test_split(
X, y, test_size=cfg.test_size, random_state=cfg.seed, stratify=y
)
def train(X_train, y_train, cfg):
model = RandomForestClassifier(
n_estimators=cfg.n_estimators, random_state=cfg.seed
)
return model.fit(X_train, y_train)
def evaluate(model, X_test, y_test):
return {"accuracy": accuracy_score(y_test, model.predict(X_test))}Each function's signature is its interface. The table lists what each stage consumes and produces.
| Stage | Inputs | Output | Uses config? |
|---|---|---|---|
| `load_data` | none | features `X`, labels `y` | no |
| `split` | `X`, `y`, `cfg` | `X_train`, `X_test`, `y_train`, `y_test` | yes: `test_size`, `seed` |
| `train` | `X_train`, `y_train`, `cfg` | fitted model | yes: `n_estimators`, `seed` |
| `evaluate` | model, `X_test`, `y_test` | metrics dictionary | no |
Notice what evaluate does not take: the configuration. It needs only a model and test data, so it asks for only those. A stage that asks for the whole configuration when it needs two fields is harder to reason about, because a reader cannot tell which fields matter. The stages here take the whole cfg for brevity. When a stage grows, pass only the fields it uses, or define a smaller dataclass for it.
Notice also that load_data takes no arguments. That works for the bundled iris dataset. For real data, the loader would receive a data location and a version identifier. The reproducibility chapter returns to this point, because an unversioned data source is a hidden input.
Where the seed goes
Both split and train use cfg.seed. Passing the seed explicitly as random_state is the point of the interface. If a stage used NumPy's global random state instead, two calls with the same arguments could give different results, and the signature would hide the reason. A seed in the signature, or in a configuration the signature includes, keeps the stage a function of its arguments.
Composing the stages
A pipeline function calls the stages in order and passes each output to the stages that need it:
def run_pipeline(cfg):
X, y = load_data()
X_train, X_test, y_train, y_test = split(X, y, cfg)
model = train(X_train, y_train, cfg)
metrics = evaluate(model, X_test, y_test)
if metrics["accuracy"] < cfg.min_accuracy:
raise ValueError(
f"accuracy {metrics['accuracy']:.3f} is below the gate of {cfg.min_accuracy}"
)
return model, metricsAll data flow is visible in this one function. You can read it and see that train never touches the test set. That is a property you would otherwise have to check by scanning a notebook. The check against min_accuracy at the end is an evaluation gate. A later chapter treats gates properly. It appears here only because it shows why the pipeline function, not the stages, owns the decision to stop.
Run it like this:
cfg = TrainConfig()
print(config_fingerprint(cfg))
model, metrics = run_pipeline(cfg)
print(metrics)The fingerprint is a short hash of the configuration. Two runs with identical settings print the same fingerprint, and changing any field changes it.
The diagram below shows the data flow.
Designing good interfaces
Splitting code into functions is easy. Splitting it so the interfaces stay useful takes some care. The points below cover the decisions that come up most often.
Choose boundaries where data changes form
A good boundary sits where the kind of data changes: raw records to features, features to a model, a model to metrics. A poor boundary sits in the middle of a computation, such as a stage that does half of the feature scaling. Ask whether the output of a stage is something you would want to inspect, save, or reuse. If it is not, the boundary is probably in the wrong place.
Keep stages the right size
Too coarse, and one stage does loading, cleaning, splitting, and training. You lose the ability to test or cache the parts. Too fine, and you have twenty one-line functions and a pipeline function that is longer than the original notebook. A workable rule is one stage per step you could describe to a teammate as a separate task, and no stage you could not test with a short example.
Return values that are easy to pass on
Return types affect every later stage. Some practical guidance:
- Return plain, serializable things where you can: arrays, data frames, dictionaries of numbers. A metrics dictionary is easy to log and to compare. A custom object with open file handles is not.
- Return tuples only for a few closely related values, as
splitdoes. Beyond four or five values, group them in a dataclass so call sites do not depend on position. - Return a fitted model rather than mutating one passed in. The
trainstage returnsmodel.fit(...), which returns the fitted estimator itself.
Avoid side effects, or isolate them
Stages that write files, call databases, or log to a server are harder to test and to retry. This does not mean a pipeline never does these things. It means you should put them in dedicated stages, such as save_model, and keep computation stages pure. A pure stage gives the same output for the same input, so rerunning it is always safe.
Common errors
These are the mistakes that turn a staged pipeline back into a notebook in disguise.
Reading globals inside a stage. A stage that uses a module-level DATA_PATH or SEED looks self-contained but is not. Changing the global changes the result, and the signature gives no sign of it. Pass the value in.
Mutating inputs. A stage that sorts, scales, or drops columns in place on an array it received changes data that other stages also hold. Copy first, or build a new object. This bug is hard to find because the stage that breaks is often not the one that mutated.
Leaking test data into training. If scaling or feature selection runs before split, the test rows influence the statistics the model learns from. Keep fitting steps after the split, and fit them only on training data. With scikit-learn, a Pipeline object that bundles a scaler and a model is one way to enforce this inside the train stage.
Passing everything through one dictionary. A single state dict that every stage reads and writes brings back the shared namespace. A stage signature of def train(state) tells you nothing. Use named arguments.
Relying on call order that the signatures do not show. If evaluate only works after a separate function has set up something internally, the dependency is hidden. Anything a stage needs must arrive through its arguments.
Putting the gate in a stage that cannot stop the run. If evaluate logs a warning and returns, nothing blocks a weak model. In this design evaluate reports and run_pipeline decides.
Checking that an interface holds
You can test an interface without a real dataset. Because evaluate takes a model and arrays, you can pass a trivial model and a handful of rows:
import numpy as np
class AlwaysZero:
def predict(self, X):
return np.zeros(len(X), dtype=int)
def test_evaluate_reports_accuracy():
X_test = np.zeros((4, 2))
y_test = np.array([0, 0, 0, 1])
assert evaluate(AlwaysZero(), X_test, y_test) == {"accuracy": 0.75}The test runs in milliseconds, needs no training, and checks the stage's contract: a model and test data go in, a dictionary with an accuracy key comes out. You can write the equivalent for split by asserting that the shapes of the four outputs add up to the input size. The testing chapter develops this approach, including a check that two runs with the same configuration give equal metrics:
def test_pipeline_is_deterministic():
cfg = TrainConfig()
_, first = run_pipeline(cfg)
_, second = run_pipeline(cfg)
assert first == secondThat second test only passes if every stage obeys the contract, which is why the contract matters.
Summary of the working model
- A stage is a function whose behavior depends only on its arguments, and whose results leave only through its return value.
- The signature is the interface. Read it to know what a stage needs and gives.
- The pipeline function composes stages and owns control flow, including stopping the run.
- Boundaries belong where data changes form, and stages should be small enough to test and large enough to be meaningful.
- Hidden inputs (globals, in-place mutation, unseeded randomness, unversioned data) are the main way staged code loses its benefits.
Exercise
A teammate's train stage runs StandardScaler().fit_transform(X) on the full feature array before splitting, then trains on the training rows. Name the problem, say which stage boundary it violates, and describe one way to fix it while keeping split as the stage that produces the train and test sets.
Show answer
The scaler learns the mean and variance from all rows, including the test rows, so information from the test set leaks into training and the test metric is too optimistic. It breaks the boundary between preparing data and holding out data: any fitted transformation must come after split. Fix it by calling split first, then fitting the scaler on X_train only and applying it to X_test with transform. A clean way is to build a scikit-learn Pipeline([("scale", StandardScaler()), ("model", RandomForestClassifier(...))]) inside train, so the scaler is fitted only on the training data when fit is called, and evaluate calls predict on raw test data.
Exercise
The function below is meant to be a stage. List two ways it violates the stage contract. SEED = 7 def train(Xtrain, ytrain): Xtrain.sort(axis=0) return RandomForestClassifier(randomstate=SEED).fit(Xtrain, ytrain)
Show answer
First, it reads the module-level global SEED, so the result depends on state that is not in the signature. The seed should come from the configuration passed as an argument. Second, X_train.sort(axis=0) sorts the caller's array in place, which mutates an input other code may still use. Sorting each column independently also breaks the pairing between rows and the labels in y_train, so the model trains on scrambled data. Remove the sort, or work on a copy if a transformation is genuinely needed.