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

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 g_i \sim \mathrm{Uniform}(D_4) (four rotations, each with or without a flip; exact pixel permutations at 28 pixels).

\mathcal{L}(\theta) = -\frac{1}{B}\sum_{i=1}^{B} \log \mathrm{softmax}\big(f_\theta(g_i \cdot x_i)\big)_{y_i}

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

\mathrm{BN}(z) = \gamma\,\frac{z - \mu_{\mathcal{B}}}{\sqrt{\sigma^{2}_{\mathcal{B}} + \epsilon}} + \beta

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.

F1_k = \frac{2\,TP_k}{2\,TP_k + FP_k + FN_k},\qquad \text{macro-F1} = \frac{1}{K}\sum_{k=1}^{K} F1_k

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:

\delta \ge \max\!\Big(2\,\mathrm{sd}_b\big(m^{*}_b\big),\ \tfrac{1}{2}\,\mathrm{range}_b\big(m^{*}_b\big)\Big)

Here m^{*}_b is the macro-F1 on bootstrap re-draw b 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.

Histogram of 1000 bootstrap macro-F1 values for the anchor with the range arrow
Item-bootstrap distribution of the anchor's development macro-F1 (1000 re-draws, registered sweep item_bootstrap, development split). Half of the range is the keep bar of 0.0438; this is the ruler against which every later candidate is judged. Close

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 W is applied at every position,

(W \star x)[c', i, j] = b_{c'} + \sum_{c=1}^{C}\sum_{u,v=0}^{k-1} W[c', c, u, v]\, x[c,\, i+u,\, j+v]

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

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)

ExpTrackKindMetricStatusDescription
E0001primarydevelopment0.718932keepanchor: recipe SmallCNN, width 32, 1,500 steps; first valid result on this track
E0002primarydevelopment0.69032discardpixel-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
E0003primarydevelopment0.300538333333discardBatchNorm2d after each conv (normalization), anchor otherwise; did not improve track frontier 0.718932 by minimum_delta=0.0438435
E0004primarydevelopment0.896005333333keepBatchNorm2d 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
E0005primarydevelopment0.889297666667discardD4 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
E0006primarydevelopment0.928632discardthird 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
E0007primarydevelopment0.924003666667discard4,000 steps instead of 1,500 (schedule only) on the BN incumbent; did not improve track frontier 0.896005333333 by minimum_delta=0.0438435
E0008primarydevelopment0.946093333333keepP3 bundle: three conv blocks + BN (train-set running stats) + D4 augmentation + 4,000 steps; frontier improvement over 0.896005333333 with minimum_delta=0.0438435
E0009primaryfinal_test0.946519666667discardsealed 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

Step plot of the development frontier with the keep bar, discard circles, keeps and the sealed star
Decision trajectory of track primary: seed-mean macro-F1 per run (development for E0001 to E0008, sealed test for E0009), the best-keep frontier and the keep bar above it. The y axis starts at zero; two keeps came in eight development arrays and the sealed star is not on the frontier. Close

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

Horizontal bars of each candidate's change against its incumbent with the keep bar line
Change in seed-mean development macro-F1 of each candidate against the incumbent it faced, bars starting at zero, with the 0.0438 keep bar drawn. E0006 (+0.0326) and E0007 (+0.0280) are positive but fall short of the bar; only E0004 and E0008 cleared it. Close

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

Left: four seed-block means of the anchor. Right: every seed of every array
Left: three-seed means of the anchor config over four seed blocks (development, registered sweep fit_noise plus E0001). Right: every seed of every array that trained properly, with the keep bar drawn as a scale arrow. The anchor's 0.7189 was the best of four blocks, so a one-block read would have been luck. Close

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
17 locked in claims.lock
by strength
confirmed 2 · exploratory 15
by class
empirical-description 8 · mechanism-interpretation 2 · procedural-verdict 1 · research-discipline 6
errata
0 of 17 claims tagged · 0 erratum record(s) in the lock
locked at
eea959838d12 · klein 2.2.0
label
confirmed
referee
PASS-WITH-NOTES — klein-referee (Claude Code subagent, model: claude-opus-5-5) · independent of the experimenter: yes

Verdicts

Per-class effects are uneven

Grouped bars of per-class recall for E0001, E0004, E0008 and the sealed E0009
Per-class recall (three-seed mean) at the anchor, the BN keep, the incumbent (all development) and the sealed test run, bars from zero. Basophil and immature-granulocyte recall rose most; monocyte recall fell from E0004 to E0008 within per-class noise. Close

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.

Two row-normalised confusion matrices, development incumbent and sealed test
Row-normalised confusion matrices summed over three seeds: E0008 on the development split (left) and the sealed E0009 on the test split (right). The one visible off-diagonal mass is monocytes called immature granulocytes, on both partitions. Close

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

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

  1. Default BatchNorm inference cost a candidate. E0003 added BatchNorm2d and 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.
  2. One bundle, one unattributed gain. E0008 changed four levers together. Budget the single-lever cells inside the phase cap, or the gain stays unattributed.
  3. 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.
  4. 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.
  5. 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.
  6. Per-seed tables, not one aux row. The aux rows of the earliest runs hold only the last seed; read runs/E####/seeds.tsv for seed means.
  7. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.