The question
A practitioner trains a small CNN on a benchmark of blood-cell photographs, changes one thing at a time, and watches a number go up. The decision this study informs is: when is a change a real improvement and not seed luck or the wobble of a small evaluation set? The concrete task is BloodMNIST, eight classes of normal blood cells at 28 × 28 pixels, official split, on a CPU budget. The registered questions ask how far a linear softmax on raw pixels gets (RQ1), whether the recipe two-block CNN clears it by more than the measured floor (RQ2), which single change earns a keep once a CNN is in place (RQ3), and whether the final incumbent holds on the sealed official test split and how it sits against MedMNIST v2's ResNet-18 (28) accuracy of 0.958 (RQ4).
Takeaways
- The recipe CNN barely beat a linear model. The anchor scored a macro-F1 of 0.7189 against 0.6903 for pixel-linear softmax, a gap of 0.65 keep bars. Prediction P2 (at least 0.85) was refuted.
- Two changes earned a keep. Batch normalization, once a running-statistics bug was repaired (E0004, 0.8960), and a four-lever bundle (E0008, 0.9461) whose gain cannot be attributed to any single lever.
- The sealed run held. One access to the official test split scored a macro-F1 of 0.9465 and an accuracy of 0.9527, 0.0053 below the published 0.958, which is indistinguishable from ResNet-18 (28) at this test size.
Scope travels with every number on this page: all scores are image-level. The official MedMNIST split is not grouped by patient or smear, so nothing here estimates performance on a new patient. The final records (claim totals, the referee verdict, the finalization label) are copied from the study's state files into the evidence block in section 5.
The method taught
Intuition: stencils, then sliding stencils
BloodMNIST is photographs of single cells, centre-cropped and shrunk to 28 × 28 RGB. The classes differ by colour, size and nucleus shape. A linear softmax on pixels gives each class one template image; a cell is called whatever template it overlaps best. A convolution is a small learned stencil applied at every position (weight sharing), so features need not be relearned per location, and stacking layers lets later filters combine earlier ones. Counted from model.py, the linear model has 18,824 parameters and the anchor CNN 19,912, so the first comparison spends the same budget two ways.
The load-bearing math
Training minimizes softmax cross-entropy, with augmentation stated as a prior: each training image is replaced by a random member of its dihedral orbit (four rotations, each with or without a flip; exact pixel permutations at 28 pixels).
Batch normalization standardizes each channel per mini-batch, then learns a scale and shift back. At evaluation the batch statistics are replaced by population statistics. The way those are obtained turns out to be the study's most expensive lesson (section 6).
The primary metric is macro-F1, an unweighted mean of per-class F1 scores, each read off the confusion table. Accuracy is a prevalence-weighted mean of recalls. Macro-F1 is a ratio of sums per class, not a mean over items, so a bootstrap of it must recompute it on every re-draw.
Two noises, one keep bar
Fit noise is how much a score moves when the seeds are redrawn: the instability of the fitting procedure. Item noise is how much it moves had the development images been another draw from the same smears: the precision of the ruler. A seed array shrinks the first, not the second, because every seed is scored on the same images. The keep bar is therefore set from an item bootstrap of the anchor's pinned confusion tables:
Here is the macro-F1 on bootstrap re-draw of the development items. The measured bar is 0.0438, and the half-range term, not twice the standard deviation, is the one that binds.
The from-scratch pieces
The study is run through a notary: every candidate is a three-seed array (seeds 0, 1, 2), and the decision is made on the seed mean against the bar. The weight-sharing idea is one line: the same filter is applied at every position,
and a third conv-pool block raises the receptive field from 8 to 18 pixels, about the whole cell, which is why depth was a candidate lever and not just more capacity.
The data story
Shape
The source is MedMNIST v2's bloodmnist.npz: uint8 images of shape 28 × 28 × 3, eight classes of expert-labelled normal blood cells, with the official 7:1:2 partitions kept (data.split.kind: predefined). Train has 11,959 images, development 1,709 and the sealed test split 3,413, after removal of near-duplicates (below). Class imbalance is moderate, about 2.7 to 1 between the largest and smallest class, so macro-F1 is the primary and accuracy is printed beside it. Two development classes (basophil and lymphocyte) have only 122 items, so per-class recall there is coarse.
Gotchas the audit caught
- Near-duplicates across partitions (a blocker, repaired). The dHash audit at 4 bits found 3 of 1,712 development and 7 of 3,421 test images with a copy in train (nine byte-identical groups span splits, and one cross-split pair carries conflicting labels). The decision was to remove them, not tolerate them:
prepare.pydrops 3 development and 8 test items, and the re-run audit passes 8 of 8. Published MedMNIST numbers are on 1,712 / 3,421 images, a difference every comparison here states. - The split is image-level. MedMNIST describes a random 7:1:2 split with no patient or slide identifier, so group overlap is unknown and cannot be audited. Scores answer “new cells from the same smears and lab”, never “a new patient”.
- Unnormalized uint8 pixels. Channel standard deviations differ (blue is far narrower than green); normalization is a training choice, not a data property.
The call
The data card's decision is GO with cautions: the one blocker was removed before the gate, and the two cautions (image-level scope, imbalance with coarse per-class estimates) travel with every claim. The data card's clean-room leakage row 4 asked for a label-shuffled harness control to be reproduced from train.py; that control was never run and is a disclosed gap (see sections 5 and 7). The harness is checked only by the analytic chance levels and the notary's rejection of near-constant predictions.
The experiment journey
One track (primary, a frontier track) carries the whole study. Each development candidate is a three-seed array judged by the notary against the incumbent with the measured keep bar of 0.0438; the ledger below lists every run. Development evidence (E0001 to E0008, scored on the 1,709 development images) is kept apart from the single sealed confirmation run (E0009), which is excluded from the adaptive frontier by design and appears as a discard row.
Tracks: primary — val_macro_f1 (higher is better)
| Exp | Track | Kind | Metric | Status | Description |
|---|---|---|---|---|---|
| E0001 | primary | development | 0.718932 | keep | anchor: recipe SmallCNN, width 32, 1,500 steps; first valid result on this track |
| E0002 | primary | development | 0.69032 | discard | pixel-linear baseline: Flatten + Linear softmax on raw pixels, same loop/optimizer/steps as the anchor; did not improve track frontier 0.718932 by minimum_delta=0 |
| E0003 | primary | development | 0.300538333333 | discard | BatchNorm2d after each conv (normalization), anchor otherwise; did not improve track frontier 0.718932 by minimum_delta=0.0438435 |
| E0004 | primary | development | 0.896005333333 | keep | BatchNorm2d after each conv with running statistics recomputed on the training set before eval (normalization, repaired); frontier improvement over 0.718932 with minimum_delta=0.0438435 |
| E0005 | primary | development | 0.889297666667 | discard | D4 flip/rot90 augmentation on the training batch (own RNG) on the BN incumbent; did not improve track frontier 0.896005333333 by minimum_delta=0.0438435 |
| E0006 | primary | development | 0.928632 | discard | third conv block (conv-BN-ReLU-pool x2 then conv-BN-ReLU; receptive field 8 -> 18 px) on the BN incumbent; did not improve track frontier 0.896005333333 by minimum_delta=0.0438435 |
| E0007 | primary | development | 0.924003666667 | discard | 4,000 steps instead of 1,500 (schedule only) on the BN incumbent; did not improve track frontier 0.896005333333 by minimum_delta=0.0438435 |
| E0008 | primary | development | 0.946093333333 | keep | P3 bundle: three conv blocks + BN (train-set running stats) + D4 augmentation + 4,000 steps; frontier improvement over 0.896005333333 with minimum_delta=0.0438435 |
| E0009 | primary | final_test | 0.946519666667 | discard | sealed confirmation of the selected incumbent E0008 config (3 blocks + BN + D4 + 4,000 steps); sealed final-test evidence; excluded from the adaptive frontier |
Development frontier
Phase 0 measured the floor on the anchor (E0001) and set the bar. The pixel-linear baseline (E0002) came in 0.65 bars below the anchor, so the recipe CNN barely beat a stencil model. Plain batch normalization (E0003) collapsed to a macro-F1 of 0.3005: a bug in inference, not a verdict on the idea. Recomputing the running statistics on the training set (E0004) scored 0.8960, a gain of 4.04 bars over the anchor and the first keep.
What each candidate did, against its bar
After E0004, flip/rotation augmentation alone (E0005) moved the score by -0.0067, unresolved at this budget. A third conv block (E0006, +0.0326) and 4,000 steps (E0007, +0.0280) were positive on every seed pair but short of the bar by 0.0112 and 0.0158; the bar was not relaxed after the fact. The registered bundle of all four levers (E0008) scored 0.9461, +0.0501 over E0004 and 0.0062 above the bar, but its margins over the depth-only and schedule-only runs (+0.0175 and +0.0221) are inside the bar. The bundle's gain cannot be attributed to any one lever.
Seed spread: why the bar is not the whole story
The anchor's seed-block spread (sd 0.0472) is 3.94 times the item-bootstrap sd of 0.0120 that sets the bar, which falsified a prior from the method card. Once batch normalization was in, per-candidate seed sds fell to about 0.007 to 0.015, so the anchor's fit noise does not describe the incumbent.
Sealed confirmation (separate evidence)
After a mandatory dry run, the incumbent configuration was run once on the sealed official test split (E0009). The run refits the same recipe on train plus development, so it scores E0008's recipe, not E0008's weights. It scored a macro-F1 of 0.9465, +0.0004 against development, and the incumbent replicated with difference 0 (klein replicate). The final headroom of 1.23 means a further keep would need a macro-F1 of 0.9899, so the frontier is nearly closed under the anchor's bar. The bar was measured at the anchor, not at the incumbent (see section 7).
Findings and insights
- claims
17locked inclaims.lock- by strength
- confirmed
2· exploratory15 - by class
- empirical-description
8· mechanism-interpretation2· procedural-verdict1· research-discipline6 - errata
0of17claims tagged ·0erratum record(s) in the lock- locked at
eea959838d12· klein2.2.0- label
- confirmed
- referee
- PASS-WITH-NOTES —
klein-referee (Claude Code subagent, model: claude-opus-5-5)· independent of the experimenter: yes
Verdicts
- RQ1 (C1). Pixel-linear softmax reached 0.6903 macro-F1 (accuracy 0.7353), far above the chance controls (prior-matched random 0.125, majority class 0.0408) and inside the prior range of 0.50 to 0.85. P1 supported.
- RQ2 (C2). The recipe CNN cleared pixel-linear by only 0.0286, inside the bar, and far below the prior of 0.85. P2 refuted.
- RQ3 (C3, C4). Working batch normalization is the only single change to earn a keep; depth and schedule are positive but sub-bar, augmentation alone is unresolved, and the bundle is supported but not attributable. P3 supported (the verdict is about the bundle).
- RQ4 (C5). On the sealed test split the incumbent configuration scored a macro-F1 of 0.9465 and an accuracy of 0.9527. P4 supported. P5 is supported arithmetically (below 0.958), but the gap of 0.0053 is about 1.5 binomial standard errors, so the honest reading is indistinguishable from ResNet-18 (28). This is the only level the study confirms: development-to-development comparisons stay exploratory.
Per-class effects are uneven
From E0001 to E0008 basophil recall rose from 0.2562 to 0.9201 and immature-granulocyte recall from 0.7046 to 0.9149. Monocyte recall fell from 0.8345 at E0004 to 0.7949 at E0008, and monocytes remain the weakest class on the sealed test (0.8582). That drop is not an established effect: on 143 development monocytes it is about 1.2 to 1.3 binomial standard errors of one recall (not a test statistic for the difference), and the per-seed recalls of the two runs overlap widely. Its cause is unresolved.
Calibration came along: expected calibration error fell from 0.0828 at the anchor to 0.0125 at E0008 (0.0086 on the sealed test), and log-loss from 0.6660 to 0.1333, so no recalibration step was needed.
Surprises, with their status
- Seed luck exceeded item noise. Measured: fit noise was 3.94 times item noise at the anchor. The mechanism proposed in the findings (unstable, under-trained optimisation, claim C11) is untested: the learning-rate schedule was never varied.
- Batch normalization first measured as a catastrophe. Measured: recomputing the statistics (E0004) scored 0.5955 higher than E0003. The explanation that the default running averages lag weights that are still moving (claim C7) rests on an off-loop seed-0 diagnostic that is not evidence, so it stays an untested interpretation.
- Different failure patterns for the linear model and the anchor. Measured per-class recall differs; reading it as “colour stencils versus local texture” is an untested interpretation, since no run probed what either model uses.
- No development-to-test drop after selection (+0.0004). Selection optimism and the larger refit push in opposite directions and one sealed number cannot separate them; this is unresolved, not “no optimism”.
Scope and the control that does not exist
Everything above is image-level on the official split, not patient-grouped, and the sealed comparison with MedMNIST is on 3,413 rather than 3,421 test images, a three-seed mean, and a train-plus-development refit. The label-shuffled harness control was never run; this is a disclosed gap, the harness resting on analytic chance levels alone. The study counts seven frontier comparisons with no family-wise correction, which is why every development comparison is exploratory. Four of five method-card priors about noise and class difficulty were falsified.
Vision-model coding advice
This section walks the source that was actually executed. model.py and train.py are the mutable surface, which the notary restores after every non-keep, so the files on disk are not a reliable witness. Each listing below is read from the candidate commit a named run executed: the incumbent E0008 (development) and the sealed E0009 (test). E0009's candidate diff was empty, so its train.py is byte-identical to E0008's; the two provenance lines show the same hash. No verifier script is declared: the metric comes from the library evaluator kleinlib.eval_multiclass.evaluate_multiclass, which refuses non-finite probabilities and collapsed single-class predictions, prints the metric block and pins the confusion table.
The network: model.py at E0008
Three conv-BN-ReLU blocks (32, 64, 128 channels), max-pool after the first two, global average pooling and a linear head. The third block lifts the receptive field to about the whole cell, and global pooling makes the head independent of the image size.
model.py · executed by E0008 (development, track primary) at commit 80be6152e0b1 · sha256 1321e4543b8a…
"""The network (part of the mutable surface, recipe cv-classify)."""
from __future__ import annotations
import torch
from torch import nn
class SmallCNN(nn.Module):
"""Two conv blocks + a linear head — the honest small baseline for small images."""
def __init__(self, in_channels: int, n_classes: int, width: int = 32) -> None:
super().__init__()
self.body = nn.Sequential(
nn.Conv2d(in_channels, width, 3, padding=1),
nn.BatchNorm2d(width),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(width, 2 * width, 3, padding=1),
nn.BatchNorm2d(2 * width),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(2 * width, 4 * width, 3, padding=1),
nn.BatchNorm2d(4 * width),
nn.ReLU(),
nn.AdaptiveAvgPool2d(1),
nn.Flatten(),
nn.Linear(4 * width, n_classes),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.body(x)
The recipe: train.py at E0008
Four things deserve a close read. (1) d4 applies the dihedral symmetries to the training batch, inside the loop, from its own generator (SEED + 10_000), so the batch order stays identical to the anchor's at the same seed and an augmentation run is a paired comparison. (2) The budget is optimizer steps, not epochs, so runs compare across devices. (3) Batches come from iterate_minibatches, a streamed index shuffle, never a DataLoader over a TensorDataset. (4) After training, the BatchNorm running statistics are reset, set to a cumulative average (momentum = None) and recomputed over one pass of the training set in train mode with no gradient, before eval(). That block is the whole difference between E0003 and E0004.
train.py · executed by E0008 (development, track primary) at commit 80be6152e0b1 · sha256 134b0b84fcbe…
"""The per-candidate training recipe (mutable surface with model.py; recipe cv-classify).
One run of this file is ONE seed of the candidate: `klein run-one` runs every seed
in `entrypoint.seeds` (setting KLEIN_SEED) and decides on the aggregate. Training
chatter may be printed freely before the final block (`entrypoint.printed: block`).
The budget is in optimizer STEPS, so CPU and GPU runs are comparable.
"""
from __future__ import annotations
import os
import time
import numpy as np
import torch
from kleinlib.data import load_items
from kleinlib.dl import report_usage, seed_everything
from kleinlib.eval_multiclass import evaluate_multiclass
from kleinlib.torch_device import pick_device
from kleinlib.torch_loop import iterate_minibatches
from model import SmallCNN
SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
SEED = int(os.environ.get("KLEIN_SEED", "0"))
RECIPE = {"steps": 200 if SMOKE else 4000, "batch_size": 64, "lr": 3e-3, "weight_decay": 1e-4, "width": 32}
def load(ids: list[str]) -> tuple[np.ndarray, np.ndarray]:
import pandas as pd
index = pd.read_csv("data/prepared/index.csv", dtype={"id": str})
images = np.load("data/prepared/images.npy", mmap_mode="r")
rows = index.reset_index().set_index("id").loc[ids, "index"].to_numpy()
x = np.asarray(images[rows], dtype=np.float32)
if images.dtype == np.uint8:
x /= 255.0 # prepare.py keeps the source's uint8 pixels
if x.ndim == 3:
x = x[:, None, :, :] # (N, 1, H, W)
elif x.shape[-1] in (1, 3, 4):
x = np.moveaxis(x, -1, 1)
return x, index.set_index("id").loc[ids, "label"].to_numpy()
def d4(xb: torch.Tensor, aug_rng: np.random.Generator) -> torch.Tensor:
"""Random element of the dihedral group D4 per image (exact pixel permutations)."""
k = aug_rng.integers(0, 4, len(xb))
flip = aug_rng.random(len(xb)) < 0.5
out = xb.clone()
for r in (1, 2, 3):
m = torch.from_numpy(k == r)
if m.any():
out[m] = torch.rot90(out[m], r, dims=(2, 3))
m = torch.from_numpy(flip)
if m.any():
out[m] = out[m].flip(3)
return out
def main() -> None:
if EXPERIMENT_ID is None:
raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
t0 = time.time()
seed_everything(SEED)
fit_ids, eval_ids = load_items()
x_fit, y_fit = load(fit_ids)
x_eval, y_eval = load(eval_ids)
classes = np.unique(np.concatenate([y_fit, y_eval]))
device = pick_device()
model = SmallCNN(x_fit.shape[1], len(classes), RECIPE["width"]).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=RECIPE["lr"], weight_decay=RECIPE["weight_decay"])
loss_fn = torch.nn.CrossEntropyLoss()
xt, yt = torch.from_numpy(x_fit), torch.from_numpy(y_fit.astype(np.int64))
rng = np.random.default_rng(SEED)
aug_rng = np.random.default_rng(SEED + 10_000) # its own generator: batch order matches the anchor
step, fit_start = 0, time.time()
while step < RECIPE["steps"]:
for batch in iterate_minibatches(len(xt), RECIPE["batch_size"], shuffle=True, generator=rng):
optimizer.zero_grad()
loss = loss_fn(model(d4(xt[batch], aug_rng).to(device)), yt[batch].to(device))
loss.backward()
optimizer.step()
step += 1
if step % 250 == 0:
print(f"step: {step} loss: {loss.item():.4f}") # chatter: outside the final block
if step >= RECIPE["steps"]:
break
# BatchNorm: recompute the running statistics as a cumulative average over one pass of the
# TRAINING set (no grad), so inference does not depend on a lagging momentum average.
bns = [mod for mod in model.modules() if isinstance(mod, torch.nn.BatchNorm2d)]
for mod in bns:
mod.reset_running_stats()
mod.momentum = None
model.train()
with torch.no_grad():
for batch in iterate_minibatches(len(xt), 256, shuffle=False, generator=None):
model(xt[batch].to(device))
model.eval()
with torch.no_grad():
proba = torch.softmax(model(torch.from_numpy(x_eval).to(device)), dim=1).cpu().numpy().astype(np.float64)
proba /= proba.sum(axis=1, keepdims=True)
report_usage(steps=step)
evaluate_multiclass(
y_eval,
proba,
labels=classes.tolist(),
exp_id=EXPERIMENT_ID,
metric_name="val_macro_f1",
t0=t0,
fit_seconds=time.time() - fit_start,
train_n=len(fit_ids),
extra={"steps": step, "seed": SEED},
study_dir=".",
)
if __name__ == "__main__":
main()
The sealed cell: train.py at E0009
The same bytes, run once on the official test split after a dry run. The sealed refit trains on train plus development (13,668 rows against 11,959), a difference that comes from the contract's partition and not from the code.
train.py · executed by E0009 (final_test, track primary) at commit 4507eae87522 · sha256 134b0b84fcbe…
"""The per-candidate training recipe (mutable surface with model.py; recipe cv-classify).
One run of this file is ONE seed of the candidate: `klein run-one` runs every seed
in `entrypoint.seeds` (setting KLEIN_SEED) and decides on the aggregate. Training
chatter may be printed freely before the final block (`entrypoint.printed: block`).
The budget is in optimizer STEPS, so CPU and GPU runs are comparable.
"""
from __future__ import annotations
import os
import time
import numpy as np
import torch
from kleinlib.data import load_items
from kleinlib.dl import report_usage, seed_everything
from kleinlib.eval_multiclass import evaluate_multiclass
from kleinlib.torch_device import pick_device
from kleinlib.torch_loop import iterate_minibatches
from model import SmallCNN
SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
SEED = int(os.environ.get("KLEIN_SEED", "0"))
RECIPE = {"steps": 200 if SMOKE else 4000, "batch_size": 64, "lr": 3e-3, "weight_decay": 1e-4, "width": 32}
def load(ids: list[str]) -> tuple[np.ndarray, np.ndarray]:
import pandas as pd
index = pd.read_csv("data/prepared/index.csv", dtype={"id": str})
images = np.load("data/prepared/images.npy", mmap_mode="r")
rows = index.reset_index().set_index("id").loc[ids, "index"].to_numpy()
x = np.asarray(images[rows], dtype=np.float32)
if images.dtype == np.uint8:
x /= 255.0 # prepare.py keeps the source's uint8 pixels
if x.ndim == 3:
x = x[:, None, :, :] # (N, 1, H, W)
elif x.shape[-1] in (1, 3, 4):
x = np.moveaxis(x, -1, 1)
return x, index.set_index("id").loc[ids, "label"].to_numpy()
def d4(xb: torch.Tensor, aug_rng: np.random.Generator) -> torch.Tensor:
"""Random element of the dihedral group D4 per image (exact pixel permutations)."""
k = aug_rng.integers(0, 4, len(xb))
flip = aug_rng.random(len(xb)) < 0.5
out = xb.clone()
for r in (1, 2, 3):
m = torch.from_numpy(k == r)
if m.any():
out[m] = torch.rot90(out[m], r, dims=(2, 3))
m = torch.from_numpy(flip)
if m.any():
out[m] = out[m].flip(3)
return out
def main() -> None:
if EXPERIMENT_ID is None:
raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
t0 = time.time()
seed_everything(SEED)
fit_ids, eval_ids = load_items()
x_fit, y_fit = load(fit_ids)
x_eval, y_eval = load(eval_ids)
classes = np.unique(np.concatenate([y_fit, y_eval]))
device = pick_device()
model = SmallCNN(x_fit.shape[1], len(classes), RECIPE["width"]).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=RECIPE["lr"], weight_decay=RECIPE["weight_decay"])
loss_fn = torch.nn.CrossEntropyLoss()
xt, yt = torch.from_numpy(x_fit), torch.from_numpy(y_fit.astype(np.int64))
rng = np.random.default_rng(SEED)
aug_rng = np.random.default_rng(SEED + 10_000) # its own generator: batch order matches the anchor
step, fit_start = 0, time.time()
while step < RECIPE["steps"]:
for batch in iterate_minibatches(len(xt), RECIPE["batch_size"], shuffle=True, generator=rng):
optimizer.zero_grad()
loss = loss_fn(model(d4(xt[batch], aug_rng).to(device)), yt[batch].to(device))
loss.backward()
optimizer.step()
step += 1
if step % 250 == 0:
print(f"step: {step} loss: {loss.item():.4f}") # chatter: outside the final block
if step >= RECIPE["steps"]:
break
# BatchNorm: recompute the running statistics as a cumulative average over one pass of the
# TRAINING set (no grad), so inference does not depend on a lagging momentum average.
bns = [mod for mod in model.modules() if isinstance(mod, torch.nn.BatchNorm2d)]
for mod in bns:
mod.reset_running_stats()
mod.momentum = None
model.train()
with torch.no_grad():
for batch in iterate_minibatches(len(xt), 256, shuffle=False, generator=None):
model(xt[batch].to(device))
model.eval()
with torch.no_grad():
proba = torch.softmax(model(torch.from_numpy(x_eval).to(device)), dim=1).cpu().numpy().astype(np.float64)
proba /= proba.sum(axis=1, keepdims=True)
report_usage(steps=step)
evaluate_multiclass(
y_eval,
proba,
labels=classes.tolist(),
exp_id=EXPERIMENT_ID,
metric_name="val_macro_f1",
t0=t0,
fit_seconds=time.time() - fit_start,
train_n=len(fit_ids),
extra={"steps": step, "seed": SEED},
study_dir=".",
)
if __name__ == "__main__":
main()
Pitfalls and war stories that bit this study
- Default BatchNorm inference cost a candidate. E0003 added
BatchNorm2dand scored 0.3005 because evaluation used momentum-0.1 running averages. An off-loop diagnostic (one seed, not evidence) showed batch-statistics accuracy staying high while eval-mode accuracy collapsed, which points at the inference path. Before calling a normalization candidate a failure, compare train-mode and eval-mode outputs, and recompute the statistics on the training set. The mechanism (averages lagging weights that are still moving at a constant learning rate) is an untested interpretation. - One bundle, one unattributed gain. E0008 changed four levers together. Budget the single-lever cells inside the phase cap, or the gain stays unattributed.
- Measure fit noise, not only item noise. The bar came from an item bootstrap; the seed-block spread was several times larger at the anchor. Read each keep together with its seed spread.
- A near-duplicate audit before training. Eleven cross-split near-duplicates were removed from the evaluation partitions; state that the official split is image-level, not patient-grouped.
- Compare a sealed number with a published one in standard errors. A gap under two binomial standard errors is “indistinguishable” whatever the arithmetic verdict of a rule says.
- Per-seed tables, not one aux row. The aux rows of the earliest runs hold only the last seed; read
runs/E####/seeds.tsvfor seed means. - Run the label-shuffled control. This study did not; the harness check therefore rests on analytic chance levels alone.
Next steps and references
What to try next
- Decompose E0008. Three registered cells of three seeds each: E0008 minus augmentation, minus the extra steps, minus the third block. This is the only way to attribute the bundle's gain and to resolve augmentation, which E0005 left open.
- Re-measure the keep bar at the incumbent. The item bootstrap ran on the anchor's confusion tables; rerun it on E0008's pinned tables before attempting another keep. At a headroom of 1.23 the frontier is nearly closed under the anchor's bar, and a bar measured near 0.95 is expected to be narrower.
- Run the missing harness control (label-shuffled training through
train.py), and a learning-rate decay at matched steps, the one recipe difference to the MedMNIST ResNet that the study never varied. - Measure transfer, not only fit: a patient-grouped or other-site blood-smear set, to answer the question that this image-level split cannot.
References
All rows below are verified in the method card (each read against a fetched record on 2026-11-03); none is promoted beyond that status. The last row is a url-only reference.
- Yang et al. 2023, MedMNIST v2: a large-scale lightweight benchmark for 2D and 3D biomedical image classification. Scientific Data 10:41. doi:10.1038/s41597-022-01721-8; arXiv:2110.14795.
- Acevedo et al. 2020, A dataset of microscopic peripheral blood cell images for development of automatic recognition systems. Data in Brief 30:105474. doi:10.1016/j.dib.2020.105474.
- Acevedo et al. 2019, Recognition of peripheral blood cell images using convolutional neural networks. Comput. Methods Programs Biomed. 180:105020. doi:10.1016/j.cmpb.2019.105020.
- LeCun, Bottou, Bengio and Haffner 1998, Gradient-based learning applied to document recognition. Proc. IEEE 86(11). doi:10.1109/5.726791.
- He, Zhang, Ren and Sun 2016, Deep residual learning for image recognition. CVPR 2016. doi:10.1109/CVPR.2016.90; arXiv:1512.03385.
- Ioffe and Szegedy 2015, Batch normalization. ICML 2015, PMLR 37. arXiv:1502.03167.
- Santurkar, Tsipras, Ilyas and Madry 2018, How does batch normalization help optimization? NeurIPS 2018. arXiv:1805.11604.
- Kingma and Ba 2015, Adam. ICLR 2015. arXiv:1412.6980.
- Loshchilov and Hutter 2019, Decoupled weight decay regularization. ICLR 2019. arXiv:1711.05101.
- Shorten and Khoshgoftaar 2019, A survey on image data augmentation for deep learning. J. Big Data 6:60. doi:10.1186/s40537-019-0197-0.
- Cohen and Welling 2016, Group equivariant convolutional networks. ICML 2016, PMLR 48. arXiv:1602.07576.
- Veeling, Linmans, Winkens, Cohen and Welling 2018, Rotation equivariant CNNs for digital pathology. MICCAI 2018. doi:10.1007/978-3-030-00934-2_24; arXiv:1806.03962.
- Bouthillier et al. 2021, Accounting for variance in machine learning benchmarks. MLSys 2021. arXiv:2103.03098.
- Picard 2021, Torch.manual_seed(3407) is all you need. arXiv:2109.08203 (preprint).
- Varoquaux and Cheplygina 2022, Machine learning for medical imaging: methodological failures and recommendations for the future. npj Digit. Med. 5:48. doi:10.1038/s41746-022-00592-y.
- Efron 1979, Bootstrap methods: another look at the jackknife. Ann. Statist. 7(1). doi:10.1214/aos/1176344552.
- Guo, Pleiss, Sun and Weinberger 2017, On calibration of modern neural networks. ICML 2017, PMLR 70. arXiv:1706.04599.
- Doerrich, Di Salvo, Brockmann and Ledig 2025, Rethinking model prototyping through the MedMNIST+ dataset collection. Sci. Rep. 15:7669. doi:10.1038/s41598-025-92156-9; arXiv:2404.15786.
- MedMNIST package metadata,
medmnist/info.py(label index map, split sizes). github.com/MedMNIST/MedMNIST (url-only, read 2026-11-03).