Add grad_accum: effective batch 256 on small GPUs via micro-batching

TrainConfig.grad_accum (default 1, behaviour unchanged) splits the
batch into batch_size // grad_accum loader micro-batches; train_probe
accumulates their gradients before each optimiser step (clip and fp16
unscale at window boundaries, scheduler steps per update). The Stage-A
ladder's largest points need ~15+ GiB activations at batch 256, which
no longer fits a 16 GB RTX 4060 Ti; accumulation keeps the spec's
uniform effective batch while micro-batches stay under ~8 GiB.

Tests: first-update gradient of accum=3 matches full-batch exactly;
loader micro-batch sizing; suite green (52 passed).
This commit is contained in:
Tom Kasper
2026-11-04 08:35:03 +01:00
parent 86af080e87
commit cda6cfd34e
5 changed files with 121 additions and 25 deletions
+71
View File
@@ -303,6 +303,77 @@ def test_trainability_duty_cycle(tmp_path: Path) -> None:
assert val_payload["closed"]["recall_macro"] >= 0.9
def test_grad_accum_first_update_matches_full_batch(tmp_path: Path, monkeypatch) -> None:
"""``grad_accum`` micro-batches must reproduce the full-batch first update.
Same seed/store/data order: with batch 6 the first optimiser step sees
the gradient of the mean loss over the first six shuffled windows; with
``grad_accum=3`` that is three micro-batches of two, each divided by 3 —
algebraically the same gradient.
"""
store_dir = tmp_path / "s"
synthetic_store(
store_dir, n_genera=2, reads_per_genus=12, window_samples=1200, shard_windows=12
)
def first_step_grad(grad_accum: int) -> torch.Tensor:
captured: dict[str, torch.Tensor] = {}
real_adamw = torch.optim.AdamW
class SpyAdamW(real_adamw): # type: ignore[misc, valid-type]
def step(self, closure=None): # type: ignore[no-untyped-def]
if "grad" not in captured:
captured["grad"] = torch.cat(
[
p.grad.detach().flatten()
for group in self.param_groups
for p in group["params"]
if p.grad is not None
]
).clone()
return super().step(closure)
monkeypatch.setattr(torch.optim, "AdamW", SpyAdamW)
cfg = RunConfig(
run_id="",
stage="ladder_point",
store_dir=store_dir,
data=DataConfig(
genera=(), val_fraction=0.25, test_fraction=0.25,
min_test_windows_per_genus=1, seed=0,
),
model=ModelConfig(arch="cnn", param_budget=50_000, stride=4),
train=TrainConfig(
max_epochs=1, patience=1, num_workers=0, amp="off", device="cpu",
batch_size=6, grad_accum=grad_accum,
),
out_dir=tmp_path / f"run-{grad_accum}",
)
train_run(cfg)
return captured["grad"]
full = first_step_grad(1)
accum = first_step_grad(3)
assert torch.allclose(full, accum, atol=1e-5)
def test_make_loaders_uses_micro_batch(fast_store: Path) -> None:
"""Loaders emit ``batch_size // grad_accum`` micro-batches."""
from custom_models.data import make_loaders
store = SignalStore(fast_store)
splits = make_splits(
store.manifest(),
DataConfig(val_fraction=0.25, test_fraction=0.25, min_test_windows_per_genus=0, seed=0),
)
base = TrainConfig(num_workers=0, device="cpu", batch_size=8)
train_loader, val_loader, _ = make_loaders(store, splits, base)
assert train_loader.batch_size == 8 and val_loader.batch_size == 8
accum = TrainConfig(num_workers=0, device="cpu", batch_size=8, grad_accum=4)
train_loader, val_loader, _ = make_loaders(store, splits, accum)
assert train_loader.batch_size == 2 and val_loader.batch_size == 2
def test_control_run_lands_at_chance(tmp_path: Path) -> None:
seed_everything(1)
store_dir = tmp_path / "s"