
7 Interlude: Learning by Experiment
The preceding chapters established how to build, train, and audit a neural network. We now face the practical question that follows: how do we refine a model and determine whether a design decision helped? We might adjust the learning rate, add regularization, train longer, or replace an entire layer. Each choice requires a comparison, and the structure of that comparison governs what we can conclude.
Chapter 6 illustrated this diagnostic loop. When the fitted MLP’s accuracy dropped sharply under a two-pixel shift, we designed targeted experiments to probe the failure. Evaluating the fixed model on displaced images measured its shift tolerance, while retraining on transformed images showed what the same recipe can learn in the new coordinates. The permutation argument established a symmetry of the dense model family. Neither result alone identifies why the clean-trained model is sensitive to shifts. Chapter 8 takes up the architectural change that those probes motivate, building locality and translation equivariance into the network through convolution. Throughout this book, progress follows the same sequence: a diagnostic test, then a design change that addresses what the test found. Before we move to vision, this interlude establishes the discipline that makes such comparisons credible.
This is central to the work of a machine learning engineer. We establish a working baseline, formulate a hypothesis, and design a controlled experiment to test it. We decide what to change, what to hold fixed, and which outcome would support or challenge the claim. The result of one run should inform the choice of the next.
Two goals recur across the discipline. Hyperparameter optimization seeks an effective configuration within a declared training and search budget. Ablation isolates and tests the causal contribution of a specific component under controlled conditions. A configuration that achieves a strong score and an explanation of why it achieved that score require different kinds of evidence.
Both depend on careful experimental design and execution. Data splits must retain their intended statistical roles, evaluation must run in the appropriate model mode, and the reported checkpoint must match the declared selection rule. Repeated runs over a seed panel, a fixed set of random seeds that every configuration uses, reveal background variation. Saved configurations and auditable outputs make the comparison reproducible.
Within a run, the optimizer fits parameters. Across runs, we evaluate choices.
Figure 7.1 places the familiar training loop inside this broader cycle. We will practice these principles with a small MLP on our Fashion-MNIST subset, keeping the model familiar so that we can concentrate on the mechanics of designing, running, and auditing an experiment.
7.1 Training runs and experimental decisions
During one training run, the optimizer updates the model’s parameters, including its weights and biases, using the gradients developed in Chapter 5. The training configuration determines how those updates are computed and applied.
Hyperparameters (learning rate, batch size, weight decay, and training schedule, for example) control the learning process from outside that inner loop. An architectural choice, such as whether to include BatchNorm, can also sit outside the weight update. Whether we call it a hyperparameter or an experimental factor depends on the question we ask of it.
- A run trains one design (under one configuration, seed, data split, and budget) once.
- An experiment compares runs to answer a predeclared question.
- A study is the larger collection of experiments from which we draw a scientific conclusion.
Ten runs are not automatically an experiment. Without a question and a controlled comparison, they are only ten observations.
Write \(a\) for a design choice (BatchNorm on or off, for example) and \(\vect{\lambda}\) for the training configuration. Let \(s\) be the random seed and \(b\) the budget. Training returns weights
\[ \vect{w}^{*}(a,\vect{\lambda},s,b) = \operatorname{Train}(a,\vect{\lambda},s,b). \]
If \(J_{\mathcal{D}}\) is a metric on dataset \(\mathcal{D}\), one run produces
\[ J_{\mathcal{D}}(a,\vect{\lambda},s,b) = \operatorname{Metric}\!\left( f_{\vect{w}^{*}(a,\vect{\lambda},s,b)},\mathcal{D} \right). \]
The optimizer produces \(\vect{w}^{*}\). We choose \(a\), search over \(\vect{\lambda}\), decide which seeds and budget are credible, and interpret the result. Those outer choices are part of the claim; they do not disappear when a library automates them. The estimands of the next section and the search of the hyperparameter-optimization section are written in this notation.
7.2 Claim types and comparisons
Suppose a new normalization layer improves accuracy by two points. What does that result support? The answer depends on what stayed fixed and what was tuned. Table 7.1 separates four types of claim, and the rest of the chapter relies on them. The worked experiment makes two of them, a fixed-protocol ablation and a tuned comparison. The protocol for experimental claims begins by naming one, and the same section labels the book’s own experiments with them.
| Claim | What is held fixed? | What it can support |
|---|---|---|
| Mechanism demonstration | A small, transparent regime | “This behavior can occur, and here is why.” |
| Fixed-protocol ablation | One training recipe, paired seeds and data | “Under this recipe, changing this component changed the outcome.” |
| Tuned design comparison | Search space and search budget, with each design tuned separately | “Under equal tuning opportunity, this design achieved this result.” |
| Benchmark estimate | Locked method, metric, split, and reporting protocol | “This complete procedure attained this performance in the declared regime.” |
A single seeded run can be entirely legitimate, sometimes ideal, for a mechanism demonstration. It is not enough to estimate an average effect of a stochastic training procedure. Likewise, a benchmark table can rank complete systems without isolating which component caused the difference. We therefore state the claim before running the experiment.
“Fair” has more than one meaning
The quantity a comparison is intended to estimate is its estimand. Below, \(J\) is a higher-is-better score, such as accuracy. Consider two designs, \(a_0\) and \(a_1\). A fixed-protocol ablation uses one configuration \(\vect{\lambda}_0\) for both. Its target is
\[ \Delta_{\mathrm{fixed}}(\vect{\lambda}_0) = \E_s\!\left[ J(a_1,\vect{\lambda}_0,s,b) -J(a_0,\vect{\lambda}_0,s,b) \right]. \]
This asks a clean local question: what is the effect of the design change at this training recipe? Pairing the seeds (a common-randomness design) makes the contrast easier to read because both designs encounter corresponding random conditions. The answer can still change at another learning rate.
A tuned comparison asks a different question. Let \(\Lambda_0\) and \(\Lambda_1\) be declared search spaces. Ideally, we want the contrast between the best expected outcomes available to each design:
\[ \Delta_{\mathrm{tuned}} = \max_{\vect{\lambda}\in\Lambda_1} \E_s[J(a_1,\vect{\lambda},s,b)] - \max_{\vect{\lambda}\in\Lambda_0} \E_s[J(a_0,\vect{\lambda},s,b)]. \]
In practice we only approximate these maxima with a finite search. A finite seed panel \(\mathcal{S}\) and the configurations \(\widetilde{\Lambda}_0\subseteq\Lambda_0\) and \(\widetilde{\Lambda}_1\subseteq\Lambda_1\) that a budgeted search tries replace the expectations and maxima:
\[ \widehat{\Delta}_{\mathrm{tuned}} = \max_{\vect{\lambda}\in\widetilde{\Lambda}_1} \frac{1}{|\mathcal{S}|}\sum_{s\in\mathcal{S}} J_{\mathrm{val}}(a_1,\vect{\lambda},s,b) - \max_{\vect{\lambda}\in\widetilde{\Lambda}_0} \frac{1}{|\mathcal{S}|}\sum_{s\in\mathcal{S}} J_{\mathrm{val}}(a_0,\vect{\lambda},s,b). \]
Each maximum is optimistic. Because the maximum is convex, Jensen’s inequality gives \(\E[\max_{\vect{\lambda}}\hat{J}(\vect{\lambda})]\geq\max_{\vect{\lambda}}\E[\hat{J}(\vect{\lambda})]\) for noisy estimates \(\hat{J}\): on average, the maximum validation score overestimates what the selected configuration achieves on fresh runs. In \(\widehat{\Delta}_{\mathrm{tuned}}\) the two selection biases need not cancel, and their difference can distort the tuned contrast in either direction. The search spaces, number of trials, seeds, and per-trial budget therefore belong in the result. Consider an analogy from physical measurement. Comparing an internal combustion engine and an electric motor at one shared shaft speed is not a fair comparison of power. Each machine has its own power curve, and a speed near one machine’s peak can sit far from the other’s. One learning rate likewise imposes a single operating point that may sit in one architecture’s sweet spot while choking another.
Neither estimand is universally fair. A shared recipe is fair to a question about a controlled intervention, whereas separate tuning is fair to a question about attainable performance. The error is to run one and write the conclusion of the other.
We use BatchNorm, a layer that rescales each hidden unit’s values using statistics of the current batch, as an on/off design choice in an otherwise familiar MLP. Its mechanism is developed in Chapter 10. Here we need only to distinguish the two model variants and compare them under clearly specified training conditions.
7.3 A worked experiment: BatchNorm and learning rate
We use the Fashion-MNIST subset from Chapter 6 to practice two comparisons. First, does adding BatchNorm improve validation accuracy when both models use the same training configuration? Second, how do the models compare when each receives the same opportunity to tune its learning rate?
The measured outcome here is classification accuracy under the study’s data splits. The experiment demonstrates how to distinguish a component comparison from a configuration search. Before running either, we specify the choices in Table 7.2:
| Item | Predeclared choice |
|---|---|
| Development data | 1,200 stored images: 1,000 for fitting and 200 for validation |
| Locked endpoint data | 600 stored test images, already used by earlier studies in the book |
| Design factor | BatchNorm after each hidden affine layer: absent or present |
| Shared architecture | \(784\rightarrow128\rightarrow64\rightarrow10\), ReLU |
| Optimizer and budget | SGD with momentum 0.9, batch 100, at most 20 epochs |
| Learning-rate search | \(\{0.003,0.01,0.03,0.1\}\) |
| Search seeds | Five seeds, paired across all configurations |
| Audit seeds | Five fresh seeds, fixed before endpoint results are evaluated |
| Selection rule | Highest mean validation accuracy, restoring each run’s best checkpoint |
Notice what has not happened: we have not chosen a result and then invented a protocol around it. We fix the split, search space, seeds, metric, budget, and selection rule first.
No decision in this study depends on the 600 test images, and we evaluate on them only after the designs and learning rates are locked. We make no change afterward. Chapters 9 and 10 will reuse them later. This is a demonstration of the protocol, not a claim that reused public data became untouched again. A new project should reserve a test set that no earlier decision has touched.
The next cell loads only the development data and defines one typed training function. Comments record the tensor shapes.
- Implement the paired Fashion-MNIST experiment.
- Define the reusable helpers:
TinyMLP,accuracy, andrun_once.
Experiment 7.A · print companion
from __future__ import annotations
import itertools
from copy import deepcopy
import matplotlib.pyplot as plt
import torch
from torch import Tensor, nn
import torch.nn.functional as F
# [1]
torch.set_num_threads(4)
development = torch.load("../../data/fashion-train.pt")
X_dev = development["X"].float().unsqueeze(1) / 255.0 # (1200, 1, 28, 28)
y_dev = development["y"] # (1200,)
split = torch.randperm(
len(X_dev), generator=torch.Generator().manual_seed(6050)
)
fit_idx, val_idx = split[:1000], split[1000:]
X_fit, y_fit = X_dev[fit_idx], y_dev[fit_idx]
X_val, y_val = X_dev[val_idx], y_dev[val_idx]
# [2]
class TinyMLP(nn.Module):
def __init__(self, use_batchnorm: bool) -> None:
super().__init__()
self.fc1 = nn.Linear(28 * 28, 128)
self.bn1 = nn.BatchNorm1d(128) if use_batchnorm else nn.Identity()
self.fc2 = nn.Linear(128, 64)
self.bn2 = nn.BatchNorm1d(64) if use_batchnorm else nn.Identity()
self.out = nn.Linear(64, 10)
def forward(self, x: Tensor) -> Tensor:
x = x.flatten(1) # (B, 1, 28, 28) -> (B, 784)
x = F.relu(self.bn1(self.fc1(x))) # (B, 784) -> (B, 128)
x = F.relu(self.bn2(self.fc2(x))) # (B, 128) -> (B, 64)
return self.out(x) # (B, 64) -> (B, 10)
@torch.no_grad()
def accuracy(model: nn.Module, x: Tensor, target: Tensor) -> float:
model.eval() # freeze BatchNorm statistics
return (model(x).argmax(1) == target).float().mean().item()
def run_once(
seed: int,
use_batchnorm: bool,
learning_rate: float,
endpoint: tuple[Tensor, Tensor] | None = None,
epochs: int = 20,
) -> tuple[float, float]:
torch.manual_seed(seed)
model = TinyMLP(use_batchnorm)
optimizer = torch.optim.SGD(
model.parameters(), lr=learning_rate, momentum=0.9
)
batch_rng = torch.Generator().manual_seed(seed + 100_000)
best_validation = 0.0
best_state = deepcopy(model.state_dict())
for _ in range(epochs):
model.train()
order = torch.randperm(len(X_fit), generator=batch_rng)
for idx in order.split(100):
loss = F.cross_entropy(model(X_fit[idx]), y_fit[idx])
optimizer.zero_grad()
loss.backward()
optimizer.step()
validation = accuracy(model, X_val, y_val)
if validation > best_validation:
best_validation = validation
best_state = deepcopy(model.state_dict())
model.load_state_dict(best_state) # evaluate the selected checkpoint
endpoint_score = (
accuracy(model, *endpoint) if endpoint is not None else best_validation
)
return best_validation, endpoint_scoreThere are two easy-to-miss hygiene details. Evaluation switches the model to eval(), so BatchNorm uses the averages it stored during training and stops updating them. More subtly, each run restores the checkpoint that actually won on validation. Reporting the last epoch after saying “best validation” would be a mismatch between the selection rule and the code.
Now we run the complete validation search. Five seeds (no magic threshold) form a small panel that makes run-to-run variation visible while keeping this example comfortably on a CPU.
- Fix the learning-rate candidates and the five search seeds, and start an empty list of result rows.
- Search four learning rates with paired seeds.
- Print validation mean and standard deviation per configuration, then pick each design’s highest-mean row.
# [1]
learning_rates = (0.003, 0.01, 0.03, 0.1)
search_seeds = tuple(range(6050, 6055))
search_rows: list[dict[str, float | bool | Tensor]] = []
# [2]
for use_batchnorm, learning_rate in itertools.product(
(False, True), learning_rates
):
scores = torch.tensor([
run_once(seed, use_batchnorm, learning_rate)[0]
for seed in search_seeds
])
search_rows.append({
"batchnorm": use_batchnorm,
"learning_rate": learning_rate,
"scores": scores,
"mean": scores.mean().item(),
"sd": scores.std(unbiased=True).item(),
})
# [3]
for row in search_rows:
label = "with BN" if row["batchnorm"] else "no BN "
print(
f"{label} lr={row['learning_rate']:<5} "
f"validation={100 * row['mean']:.1f}% +/- {100 * row['sd']:.1f}%"
)
best_row = {
use_batchnorm: max(
(row for row in search_rows if row["batchnorm"] == use_batchnorm),
key=lambda row: row["mean"],
)
for use_batchnorm in (False, True)
}no BN lr=0.003 validation=54.5% +/- 1.5%
no BN lr=0.01 validation=68.9% +/- 0.5%
no BN lr=0.03 validation=74.5% +/- 1.4%
no BN lr=0.1 validation=78.8% +/- 1.9%
with BN lr=0.003 validation=77.3% +/- 1.3%
with BN lr=0.01 validation=79.1% +/- 1.2%
with BN lr=0.03 validation=78.7% +/- 0.6%
with BN lr=0.1 validation=77.6% +/- 1.7%
Holding the recipe fixed does not produce one universal BatchNorm effect; it produces one estimate at each of the four predeclared learning rates. The paired BatchNorm-minus-no-BatchNorm validation differences are \(+22.800\) points at 0.003 (sample SD \(1.643\)), \(+10.200\) at 0.01 (SD \(1.681\)), \(+4.200\) at 0.03 (SD \(1.681\)), and \(-1.200\) at 0.1 (SD \(3.402\)). The large low-rate contrast is therefore one end of an interaction curve, and BatchNorm has no single effect across rates.
The learning-rate sweep changes the conclusion. The unnormalized MLP rises from 54.5% to a best mean of 78.8% at learning rate 0.1. The BatchNorm MLP peaks at 79.1% at learning rate 0.01. After equal, design-specific tuning, the two selected means differ by only 0.3 points. That gap is too small to rank the designs on its own, so we read it together with the paired differences and the fresh-seed evaluation below.
Only after those configurations are selected do we evaluate on the shared test images. The endpoint check uses the predeclared fresh seed panel and makes no further design or hyperparameter choices; the checkpoint rule remains the one declared above.
- Load and scale the 600 test images, fix the five audit seeds, and start an empty
auditrecord. - Evaluate the locked configurations on the shared endpoint.
# [1]
holdout = torch.load("../../data/fashion-test.pt")
X_test = holdout["X"].float().unsqueeze(1) / 255.0 # (600, 1, 28, 28)
y_test = holdout["y"] # (600,)
audit_seeds = tuple(range(6060, 6065))
audit: dict[bool, dict[str, float | Tensor]] = {}
# [2]
for use_batchnorm in (False, True):
learning_rate = float(best_row[use_batchnorm]["learning_rate"])
test_scores = torch.tensor([
run_once(
seed, use_batchnorm, learning_rate, endpoint=(X_test, y_test)
)[1]
for seed in audit_seeds
])
audit[use_batchnorm] = {
"learning_rate": learning_rate,
"scores": test_scores,
"mean": test_scores.mean().item(),
"sd": test_scores.std(unbiased=True).item(),
}
label = "with BN" if use_batchnorm else "no BN "
print(
f"{label} locked lr={learning_rate:<4} "
f"test={100 * audit[use_batchnorm]['mean']:.1f}% "
f"+/- {100 * audit[use_batchnorm]['sd']:.1f}%"
)
scores_by_rate = {
(bool(row["batchnorm"]), float(row["learning_rate"])): row["scores"]
for row in search_rows
}
fixed_rate_contrasts = {
learning_rate: (
scores_by_rate[(True, learning_rate)]
- scores_by_rate[(False, learning_rate)]
)
for learning_rate in learning_rates
}
paired_contrasts = {
**{f"shared lr={rate:g}": values
for rate, values in fixed_rate_contrasts.items()},
"tuned validation": best_row[True]["scores"] - best_row[False]["scores"],
"locked endpoint": audit[True]["scores"] - audit[False]["scores"],
}
print("paired BN - no-BN contrasts")
for label, contrasts in paired_contrasts.items():
print(
f"{label:<20} mean={100 * contrasts.mean():+.3f} pp "
f"SD={100 * contrasts.std(unbiased=True):.3f} pp"
)no BN locked lr=0.1 test=78.1% +/- 0.7%
with BN locked lr=0.01 test=76.9% +/- 0.9%
paired BN - no-BN contrasts
shared lr=0.003 mean=+22.800 pp SD=1.643 pp
shared lr=0.01 mean=+10.200 pp SD=1.681 pp
shared lr=0.03 mean=+4.200 pp SD=1.681 pp
shared lr=0.1 mean=-1.200 pp SD=3.402 pp
tuned validation mean=+0.300 pp SD=1.095 pp
locked endpoint mean=-1.267 pp SD=1.146 pp
The endpoint means are 78.1% without BatchNorm and 76.9% with it (sample standard deviations 0.7 and 0.9 points). The apparent ranking reversed between validation and the locked endpoint, illustrating why a small tuned gap within run-to-run spread cannot settle a design comparison. The strongest conclusion is about interaction (under this protocol, the effect of BatchNorm depends strongly on the learning rate, so the two must be interpreted together) and about the limits of the experiment.
With shared seeds, the paired contrast is the summary that matches the question. Across the four shared learning rates, the contrast slides from \(+22.800\) to \(-1.200\) points. After each design is tuned separately it is \(+0.300\) points (paired sample SD \(1.095\)), and at the locked endpoint it is \(-1.267\) (SD \(1.146\)). Pairing reduces variance when the scores of the two arms, with and without BatchNorm, rise and fall together across seeds. Here it removed little: the endpoint’s paired SD is close to the \(\sqrt{0.7^2+0.9^2}\approx1.14\) that independent arms would give. The spread of each arm on its own answers a different question; the code preserves both.

7.4 Ablation studies and controlled comparisons
An ablation (a deliberate removal or substitution) asks whether a component mattered. A useful ablation has five parts:
- Baseline: the complete system against which we compare.
- Hypothesis: the mechanism we believe the component provides.
- Intervention: the smallest change that tests that mechanism.
- Outcome: a predeclared metric, not whichever curve looks favorable afterward.
- Scope: the data, training protocol, seeds, and budget within which the claim holds.
“One change at a time” is the right opening discipline because it preserves attribution. If we remove BatchNorm and change the learning rate simultaneously, the raw difference cannot tell us which change produced it. Our worked example also shows why one-at-a-time is not the end of the story: components can interact.
Suppose \(\bar J_{bd}\) is the mean score with BatchNorm indicator \(b\in\{0,1\}\) and dropout indicator \(d\in\{0,1\}\). The BatchNorm effect without dropout is \(\bar J_{10}-\bar J_{00}\); with dropout it is \(\bar J_{11}-\bar J_{01}\). Their difference is the interaction:
\[ I=(\bar J_{11}-\bar J_{01})-(\bar J_{10}-\bar J_{00}). \]
If \(I\) is far from zero relative to run-to-run variation, the effect of one component depends on the other. A \(2\times2\) design reveals that dependence; two isolated removals do not. This is why an ablation table is best read as a small factorial experiment, in which components can help or hurt one another.
Chapter 6 used the same logic. A fixed model’s accuracy fell under both a two-pixel shift and a pixel scramble, but the two transformations differ in size and in what we require, so that comparison alone could not separate the transformation from the protocol. Completing the two-by-two design (fixed evaluation versus retraining, crossed with shift versus scramble) showed that retraining recovers similar accuracy under both, 76.5% and 77.0%. That result shows what the recipe can learn from transformed data. Why the clean-trained model is sensitive to shifts is a separate question.
If a variant cannot overfit one small batch, produces chance accuracy, or diverges under every reasonable learning rate, diagnose it before interpreting the ablation. A wiring error is not evidence against an idea. First make each variant train. Then decide whether the claim calls for a shared recipe or equal tuning opportunity.
7.5 Hyperparameter optimization is a budgeted outer loop
Hyperparameter optimization (HPO), the systematic form of hyperparameter tuning, chooses the training configuration using validation performance. It is a nested problem:
\[ \hat{\vect{\lambda}}(a) =\argmax_{\vect{\lambda}\in\Lambda(a)} \frac{1}{|\mathcal{S}_{\mathrm{search}}|} \sum_{s\in\mathcal{S}_{\mathrm{search}}} J_{\mathrm{val}}(a,\vect{\lambda},s,b), \]
while each term still requires the inner training defined earlier. There is usually no useful gradient through that whole procedure. Every evaluation (one point in the outer search) costs a training run, observations are noisy, and the search space mixes continuous, discrete, and categorical choices. HPO is therefore not “turn every knob.” It is experimental design under a budget.
Choose the space before choosing the algorithm
Three habits matter more than the choice of search package:
- Search multiplicative quantities such as learning rate and weight decay on a logarithmic scale. A meaningful step is often a factor of ten, \(10^{-3}\rightarrow10^{-2}\).
- Bound the space using the model, the data scale, and short preliminary runs. A search over values known to diverge is not thorough; it is waste.
- Record conditional choices. A momentum value applies only to an optimizer that uses momentum; it should not silently carry over when the optimizer family changes.
For a small discrete space, a grid is transparent. In a higher-dimensional space where only a few knobs strongly affect the score, random search explores more distinct values along each important dimension for the same number of trials. Adaptive search uses earlier outcomes to choose the next trial. No search method compensates for a badly specified search space.
Spend small budgets before large ones
When partial learning curves are informative, successive halving starts many configurations with small training budgets, keeps a fraction, and increases the survivors’ budgets. For example, 27 configurations run for one epoch, nine continue to a cumulative three, three continue to nine, and one continues to 27. With resumed checkpoints, the cost is \(27+9(2)+3(6)+1(18)=81\) epoch-units, where an epoch-unit is one configuration trained for one epoch. Training all 27 for 27 epochs would cost 729.
The saving comes from pruning. Whether the strongest final configuration is kept depends on how informative the early rankings are. A slow-starting configuration can be pruned before its advantage appears. The pruning policy is therefore part of the method and must be logged. In sequence models later in the book, early curves can cross; “losing at epoch three” and “inferior after convergence” are not synonyms.
Sanity check \(\rightarrow\) broad, short search \(\rightarrow\) narrow, longer search \(\rightarrow\) lock the configuration \(\rightarrow\) fresh-seed audit. If the broad search ends on a boundary, expand that boundary before declaring an optimum.
Search can also have more than one objective. Accuracy, latency, memory, and model size may trade against one another. In that case there may be no single winner, only a Pareto frontier: designs for which improving one objective requires worsening another. State the operating constraint before selecting a point from that frontier.
Animation 7.A · print companion
Watch the mechanism: a search that spends unevenly
Twenty-seven configurations, each deserving twenty-seven epochs, is 729 epoch-units. Successive halving still takes one of them all the way to 27 epochs. What does it spend?
The interlude's successive-halving example drawn as the area it buys: configurations across the bottom, epochs up the side, and the shape the budget actually takes inside the square that training everything would fill.
\( \class{hv-rung}{n_r\,b_r} = 27 \quad\text{at every rung} \)\( 27 + 9(2) + 3(6) + 1(18) = \class{hv-total}{81} \quad\text{against}\quad \class{hv-full}{729} \)
The staircase is 81 of the square’s 729: the search spent one ninth.
The calculation is readable without playback. Opening this panel loads the optional controls.
The saving assumes early rank predicts late rank well enough; a slow-starting configuration can be pruned before its advantage appears, which is why pruning policy is part of the method and must be logged.
Scope and caveats
Nothing here is trained and no configuration is better than another: the columns are places in a budget, not measured results, and which third survives each round is left deliberately unlabelled. The surviving columns are drawn at the left only so the staircase reads as one shape; a real bracket keeps whichever configurations rank highest, scattered across the space.
The staircase is the cost with resumed checkpoints, which is the interlude's own assumption: a survivor is not retrained from scratch, so each round pays only for the epochs it adds. Without checkpoints the same schedule would pay for the whole cumulative budget every round, and the four rungs would cost 27 each rather than 27, 18, 18 and 18.
The square is the alternative the interlude names — all 27 configurations trained for 27 epochs — drawn to the same scale so the comparison is area against area. The running totals 45 and 63 are partial sums of the chapter's own cost expression, and the ratio of nine is 729 divided by 81; the chapter prints the two endpoints and not the steps between them. Grey is the budget that has been spent, and the pale outline the budget that was never needed.
Check yourself. Same rule — keep a third, triple the budget — but start from 81 configurations at one epoch. How many rounds until one survives, what budget does it reach, and what does the whole search cost?
Five rounds, 81 epochs, and 297 epoch-units. The counts run 81, 27, 9, 3, 1 and the budgets 1, 3, 9, 27, 81, so the rounds cost 81, then 54 four times over. Training all 81 for 81 epochs would cost 6561, so the saving grows to about 22 times.
Transcript and keyboard help
- Predict. An empty square: 27 configurations across the bottom, 27 epochs up the side, so its area is the 729 epoch-units that training everything would cost. Nothing has been spent.
- One epoch each. A single band fills the whole width: every one of the 27 configurations runs for one epoch. Spent so far, 27.
- Keep a third. The frontier narrows from 27 columns to nine, and those nine grow from one epoch to a cumulative three. The round adds 18; spent so far, 45.
- Again. Three survive and grow from three epochs to nine. The block is a third as wide and three times as tall, so this round adds the same 18; spent so far, 63.
- Hold. One configuration is left, and it is about to run to the full 27 epochs. Predict the total before releasing it.
- The last rung. The single survivor climbs from nine epochs to 27, adding 18. The whole search cost 81 epoch-units, the number the interlude prints.
- Compare. The square behind the staircase lights up: 729 epoch-units for training all 27 configurations to 27 epochs.
- The shape of the spending. The staircase is one ninth of the square. Every rung held the same product of configurations and budget, 27, which is why each round after the first cost the same.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber and speed menu also work by keyboard. Reduced-motion mode holds each beat's finished state instead of moving between them.
7.6 Roles of the training, validation, and test sets
The three-way split is not ceremonial:
- We compute gradients on the training set and fit \(\vect{w}\) to it.
- We use the validation set to make decisions about the learning rate, architecture, checkpoint, early stopping, and search-space revisions.
- We use the test set to audit the locked procedure after those decisions are complete.
Every look at the validation set informs a choice, so after hundreds of trials the selected configuration may partly fit quirks of that finite validation set. This is validation overtuning. A larger search budget can improve the chosen validation score while making the score a more optimistic estimate of performance on new data from the same data-generating distribution. Keep a test set sealed, and for high-stakes comparisons consider nested resampling or a fresh external audit.
The test set (the only split not used for decisions) must stay out of the selection loop. If the test result disappoints and we return to change the model, that test set has joined the development process. It can still be useful, but it can no longer audit the revised procedure.
7.7 Seed panels and run-to-run variation
Random initialization, batch order, dropout masks, and other stochastic choices can change the outcome. A seed makes one run reproducible, and the run still depends on the random choices that the seed selects. Another seed gives another run. The scientific target is usually an expectation over plausible runs. Both estimands of the claim-types section, \(\Delta_{\mathrm{fixed}}\) and \(\Delta_{\mathrm{tuned}}\), are built from expectations over the seed \(s\). One seed gives a single observed contrast, which is enough for a mechanism demonstration. A seed panel gives several contrasts and shows how much they vary from run to run.
For a controlled comparison, use the same seed set and data split in both arms. Then report the per-seed differences as well as the means. This paired-seed design often removes background variation. If one seed is hard for both models, pairing keeps that shared difficulty out of the design effect.
Be precise about the uncertainty summary:
- A sample standard deviation across seeds describes the run-to-run spread in the chosen seed panel.
- A confidence interval for a population mean needs more.
- Five seeds can expose a fragile ranking, and they cannot turn a toy subset into a broad benchmark.
- Never infer an average stochastic effect from one seed. A labeled one-seed mechanism demonstration is still useful when the claim stays that narrow.
Keep the source of variation distinct. Re-seeding varies the stochastic choices of training (here the initial weights and the minibatch order) on one fixed training set. It never draws a fresh training sample from the data-generating distribution. A narrow seed spread shows that this training procedure is repeatable on this dataset. It says nothing about how the result would change with a different training sample. Appendix E separates these sources of variation.
In our Fashion-MNIST figure, the error bars are sample standard deviations, and the conclusion is claimed only for this CPU-scale teaching regime.
7.8 What each run should record
A result that cannot be reconstructed cannot be audited. At minimum, each run should preserve the following records:
| Record | Why it matters |
|---|---|
| Question and hypothesis | Prevents choosing the claim after seeing the metric |
| Code revision | Distinguishes an algorithmic change from a software change |
| Data version and split seed | Makes leakage and split drift auditable |
| Design and full configuration | Reconstructs both the outer and inner choices |
| Training seed and budget | Defines the stochastic run and resources spent |
| Metric definition and checkpoint rule | Prevents silent changes in what “best” means |
| Curves, final values, and failures | Keeps inconvenient trials in the evidence |
| Software and execution environment | Explains numerical and performance differences |
Do not overwrite failed runs. A run that diverges at a large learning rate marks a boundary of the search space; deleting it makes the next search less informed. Give every run a stable identifier, save the full resolved configuration with every setting filled in, and make every plot from saved data rather than from memory.
This is also good coding hygiene. Separate data loading, model construction, training, and evaluation so a sweep changes configuration rather than copying a notebook. Assert tensor shapes, evaluate under the correct model mode, and stop immediately on a NaN. Experiment-management software can automate launches and logging later; it cannot decide what the comparison means.
7.9 A protocol for experimental claims
To test a claim that one idea matters, work through these steps:
- Name the question. Use Table 7.1: mechanism, fixed-protocol effect, tuned performance, or benchmark?
- Debug before searching. Check shapes, chance baselines, and whether the model can overfit one small batch.
- Fix the choices first. Split, metric, seed panel, budget, search space, and selection rule.
- Run the smallest decisive comparison. A good experiment isolates the question before scaling it.
- Inspect interactions. If the result changes across learning rates or companion components, say so and test the relevant grid.
- Lock, then audit. Select on validation, then evaluate the locked procedure with fresh seeds on the sealed test set.
- Report the scope. Means, spread, failures, resources, and what the experiment did not establish.
This protocol will return repeatedly. The optimizer experiment in Chapter 4 is a mechanism comparison with declared optimizer-specific learning rates and a shared update budget, so its conclusion holds for that setup only. The seeded sweep of Chapter 6 is a mechanism demonstration, and it estimates no scaling law. Chapter 8 builds the local sliding operation with fixed filters, and Chapter 9 makes those filters learnable and repeats the shift test of Chapter 6 on the same images. Chapter 12 reports recall for six recurrent configurations over three seeds. Chapter 16 trains a Transformer with and without its sinusoidal position code from the same initial weights on the same sequence of training windows, an exact paired ablation. None of these is a publication-scale benchmark, and none needs to be. The aim is a conclusion no larger than its evidence.
Deep Learning: Making It Trainable (Shakeri, 2026) gives further treatment of estimator assumptions and experimental diagnostics in Chapter 13 and of structured records of model failures in Appendix D. The first asks what one batch estimates at the current state, and the second diagnoses a training symptom before a remedy is chosen.
Close the book and audit one comparison you have run.
- What estimand did the comparison actually identify?
- Which choices were tuned on validation, and which result remained sealed?
- What interaction or failure could reverse the conclusion?
7.10 Okay, so: tune for performance, ablate to test the claim
- Training and experimentation operate at different levels. The optimizer fits parameters within a run. Comparisons across runs guide configuration and design choices.
- Begin with an estimand. A fixed recipe and a tuned-per-design comparison answer different questions, so “fair” must be defined rather than assumed.
- Ablation tests a claim. Baseline, hypothesis, intervention, outcome, and scope turn a removal into an argument. Factorial comparisons reveal interactions.
- HPO spends a declared budget. Search space, sampling rule, pruning, seeds, and per-run resources are part of the result.
- Select on validation and audit on test. Repeated validation queries can overfit, and a disappointing test result cannot be tuned away while keeping the same test set sealed.
- Seed spread describes run-to-run variation. Report the whole panel, distinguish standard deviation from a confidence interval, and keep conclusions inside the tested regime.
We now have a procedure for investigating the models that follow: establish a working baseline, state the hypothesis, choose the comparison, and separate selection from final evaluation. Chapter 8 returns to the spatial structure examined in Chapter 6. Part II begins with local filters and convolution, then makes the filters learnable. As the architectures change, these experimental practices will help us determine what each change contributes.
Sources and further reading
- Bergstra and Bengio, “Random Search for Hyper-Parameter Optimization” (JMLR 2012), the primary source for random search’s marginal-coverage argument.
- Li et al., “Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization” (JMLR 2018), the primary source for budgeted successive-halving brackets.
- Cawley and Talbot, “On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation” (JMLR 2010), a primary treatment of selection-induced optimism.
- Hardt and Recht, Patterns, Predictions, and Actions: Datasets (2022), which quantifies nonadaptive best-of-\(k\) selection and shows why adaptive holdout reuse can lose its guarantee much faster.
- Shakeri, Deep Learning: Making It Trainable (2026), Chapter 13 and Appendix D: further treatment of estimator assumptions, experimental diagnostics, and structured records of model failures.
Exercises
- (Pencil.) A paper compares two optimizers under one learning rate and claims that optimizer A is intrinsically better. Write the fixed-protocol estimand it actually estimated. Then write a tuned-performance estimand and state the narrower claim it could support within declared search spaces and budgets. Which additional budget must the paper report?
- (Code.) Extend the worked experiment to learning rates 0.001 and 0.3 without changing any other choice in Table 7.2. Do the selected rates land on a search boundary? Report the new validation table, but do not reinterpret the already-opened test set as a fresh audit.
- (Code.) Add dropout as a second binary factor and run the \(2\times2\) fixed-recipe design over paired seeds. Compute the displayed interaction contrast. Then tune the learning rate for each cell and explain why the two interaction estimates answer different questions.
- (Code.) On a synthetic classification problem, compare a nine-point grid with nine random configurations over learning rate and weight decay. Repeat the entire search across several search seeds. Plot both the best-so-far curve and its spread. Do not infer a ranking from one search seed.
- (Audit.) Choose one ablation table from a deep-learning paper. For each row, record the hypothesis, intervention, training recipe, tuning opportunity, seed count, and uncertainty summary. State the narrowest conclusion the evidence supports and one interaction the table cannot reveal.
- (Audit.) With a fixed seed, evaluate \(k=1,\ldots,200\) independently generated random binary classifiers on one fixed \(n=1000\) holdout set. Plot the best reported accuracy against \(k\) and compare its optimism with a \(\sqrt{\log(k)/n}\) envelope. Then implement an adaptive analyst whose next classifier hill-climbs using earlier holdout feedback, and compare the gap with the nonadaptive envelope over at least 100 simulation repeats. Preserve a fresh test set that neither analyst queries. Common misconception: “the validation set remains unbiased because no gradient was trained on it.” One predetermined estimate may be unbiased, but selection by its reported values changes the chosen model.