From cda6cfd34e6dbe01a7b6fd450f196beeea5655ce Mon Sep 17 00:00:00 2001 From: Tom Kasper Date: Wed, 4 Nov 2026 08:35:03 +0100 Subject: [PATCH] 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). --- src/custom_models/cli.py | 7 ++++ src/custom_models/config.py | 5 +++ src/custom_models/data.py | 11 ++++-- src/custom_models/train.py | 52 +++++++++++++++------------ tests/test_pipeline.py | 71 +++++++++++++++++++++++++++++++++++++ 5 files changed, 121 insertions(+), 25 deletions(-) diff --git a/src/custom_models/cli.py b/src/custom_models/cli.py index 2ce0671..6505c3b 100644 --- a/src/custom_models/cli.py +++ b/src/custom_models/cli.py @@ -76,6 +76,12 @@ def _add_train_args(parser: argparse.ArgumentParser) -> None: """ parser.add_argument("--batch", type=int, default=None) + parser.add_argument( + "--grad-accum", + type=int, + default=None, + help="micro-batches accumulated per optimiser step (effective batch = --batch)", + ) parser.add_argument("--lr", type=float, default=None) parser.add_argument("--weight-decay", type=float, default=None) parser.add_argument("--epochs", type=int, default=None) @@ -206,6 +212,7 @@ def _run_config_from_args(args: argparse.Namespace) -> RunConfig: device = None train = TrainConfig( batch_size=_pick(args.batch, base_train.batch_size if base_train else None, 256), + grad_accum=_pick(args.grad_accum, base_train.grad_accum if base_train else None, 1), lr=_pick(args.lr, base_train.lr if base_train else None, 3e-4), weight_decay=_pick( args.weight_decay, base_train.weight_decay if base_train else None, 0.01 diff --git a/src/custom_models/config.py b/src/custom_models/config.py index ec13533..40631a7 100644 --- a/src/custom_models/config.py +++ b/src/custom_models/config.py @@ -73,6 +73,11 @@ class TrainConfig: """Training semantics (GATE ZERO §5.1; restated in the torch model spec §5).""" batch_size: int = 256 + # Effective optimiser batch stays ``batch_size``; the loaders emit + # micro-batches of ``batch_size // grad_accum`` and gradients are + # accumulated over ``grad_accum`` of them before each step, so small + # GPUs (16 GB) can honour the spec's batch 256. + grad_accum: int = 1 lr: float = 3e-4 weight_decay: float = 0.01 max_epochs: int = 40 diff --git a/src/custom_models/data.py b/src/custom_models/data.py index 0647b8c..7bbc805 100644 --- a/src/custom_models/data.py +++ b/src/custom_models/data.py @@ -326,12 +326,16 @@ def make_loaders( ``drop_last=True`` (stable step counts) and per-worker seeding. Val/test: unshuffled and complete. ``pin_memory`` only when the resolved device is CUDA; ``persistent_workers`` only when - ``num_workers > 0``. + ``num_workers > 0``. Loaders emit *micro-batches* of + ``batch_size // grad_accum``; ``train_probe`` accumulates gradients + over ``grad_accum`` of them so the effective optimiser batch stays + ``batch_size`` (16-GB-GPU support for the spec's batch 256). Args: store: The signal store both splits read from. splits: Split window ids and labels. - cfg: Training config (batch size, workers, seed, device). + cfg: Training config (batch size, grad accumulation, workers, + seed, device). Returns: ``(train_loader, val_loader, test_loader)``. @@ -343,8 +347,9 @@ def make_loaders( pin = device.type == "cuda" generator = torch.Generator() generator.manual_seed(cfg.seed) + micro_batch = max(1, cfg.batch_size // max(1, cfg.grad_accum)) common: dict = { - "batch_size": cfg.batch_size, + "batch_size": micro_batch, "collate_fn": collate_windows, "num_workers": cfg.num_workers, "pin_memory": pin, diff --git a/src/custom_models/train.py b/src/custom_models/train.py index 84048d4..c7e587f 100644 --- a/src/custom_models/train.py +++ b/src/custom_models/train.py @@ -241,7 +241,9 @@ def train_probe( Per epoch: full train pass (AMP per the resolved policy, GradScaler for fp16, unscaled L2 grad clipping), then validation via :func:`predict`; the early-stop metric improves or the patience - counter advances. The best epoch's weights are copied to CPU and + counter advances. Gradients accumulate over ``grad_accum`` loader + micro-batches before each optimiser step (effective batch stays + ``batch_size``; a trailing short window steps with what it has). The best epoch's weights are copied to CPU and restored into the probe before returning. If the projected wall time over ``max_epochs`` exceeds 3 h, a warning is printed (the GPU-hour budget is a constraint, not a suggestion). @@ -280,11 +282,13 @@ def train_probe( ) device = select_device(cfg.device) amp = resolve_amp(cfg.amp, device) + grad_accum = max(1, cfg.grad_accum) train_loader, val_loader, _ = make_loaders(store, splits, cfg) probe = probe.to(device) - steps_per_epoch = len(train_loader) - if steps_per_epoch == 0: + micro_steps = len(train_loader) + if micro_steps == 0: raise ValueError("train loader is empty") + steps_per_epoch = -(-micro_steps // grad_accum) # ceil: optimiser updates optimizer, scheduler = build_optimizer(probe, cfg, steps_per_epoch) scaler = torch.amp.GradScaler(device.type) if amp == "fp16" else None maximize = cfg.early_stop_metric == "val_recall_macro" @@ -301,35 +305,39 @@ def train_probe( probe.train() running_loss = 0.0 n_seen = 0 - for windows, labels in train_loader: + optimizer.zero_grad(set_to_none=True) + for micro_index, (windows, labels) in enumerate(train_loader, start=1): windows = windows.to(device, non_blocking=device.type == "cuda") labels = labels.to(device, non_blocking=device.type == "cuda") - optimizer.zero_grad(set_to_none=True) with autocast_context(amp, device): logits = probe(windows) loss = F.cross_entropy( logits, labels, label_smoothing=cfg.label_smoothing - ) + ) / grad_accum if scaler is not None: scaler.scale(loss).backward() - scaler.unscale_(optimizer) - if cfg.grad_clip > 0: - torch.nn.utils.clip_grad_norm_( - (p for g in optimizer.param_groups for p in g["params"]), - cfg.grad_clip, - ) - scaler.step(optimizer) - scaler.update() else: loss.backward() - if cfg.grad_clip > 0: - torch.nn.utils.clip_grad_norm_( - (p for g in optimizer.param_groups for p in g["params"]), - cfg.grad_clip, - ) - optimizer.step() - scheduler.step() - running_loss += float(loss.item()) * windows.shape[0] + if micro_index % grad_accum == 0 or micro_index == micro_steps: + if scaler is not None: + scaler.unscale_(optimizer) + if cfg.grad_clip > 0: + torch.nn.utils.clip_grad_norm_( + (p for g in optimizer.param_groups for p in g["params"]), + cfg.grad_clip, + ) + scaler.step(optimizer) + scaler.update() + else: + if cfg.grad_clip > 0: + torch.nn.utils.clip_grad_norm_( + (p for g in optimizer.param_groups for p in g["params"]), + cfg.grad_clip, + ) + optimizer.step() + scheduler.step() + optimizer.zero_grad(set_to_none=True) + running_loss += float(loss.item()) * grad_accum * windows.shape[0] n_seen += windows.shape[0] train_loss = running_loss / max(1, n_seen) val_logits, val_y = predict(probe, val_loader, device, amp) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 271eeed..306fb20 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -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"