pytorch-training-loop · git:20261120.76a1b83 · 2026-11-20 · sha256 82f4dd76cf509106

pytorch-training-loop git:20261120.76a1b83A

Immutable. This exact content never changes and is served at /api/v1/blob/82f4dd76cf509106.

No tool to install first
claude plugin marketplace add https://markdownregistry.com/mp/a/art_f7hdcezqmaeb5sk7/82f4dd76cf5091064adb1e2aec1b5a10e3c11468cb17eb659812ce7849326b84.json

Then /plugin install pytorch-training-loop@markdownregistry-f7hdcezqmaeb5sk7 in Claude Code. It installs this exact version, the one graded A here, pinned to the commit it was graded at, and leaves it there.

---
name: pytorch-training-loop
description: Writes a correct PyTorch training loop with seeding, mixed precision, clipping and resumable checkpoints. Use it to start or fix a training script.
---

# PyTorch training loop

Get the loop right on tiny data before spending hours on big data.

## Steps

1. Seed everything from one function: `random`, `numpy`, `torch.manual_seed`, and `torch.cuda.manual_seed_all`. For a worker-based `DataLoader`, pass a `worker_init_fn` and a seeded `generator`.
2. Pick the device once and move the model and each batch with `.to(device, non_blocking=True)`. Use `pin_memory=True` on CUDA.
3. Per step, in this order: `optimizer.zero_grad(set_to_none=True)`, forward, loss, backward, gradient clipping with `clip_grad_norm_`, `optimizer.step()`, then `scheduler.step()` at the interval the scheduler expects.
4. Mixed precision: wrap the forward and loss in `torch.autocast`, use `GradScaler` for float16 (not needed for bfloat16), and unscale before clipping.
5. Call `model.train()` before training and `model.eval()` with `torch.no_grad()` for validation. Switch back afterwards.
6. Checkpoint model, optimizer, scheduler, scaler, epoch and RNG state to a temp file, then rename it over the last one, so a crash never leaves a half-written file. Keep the best by validation metric.
7. Log training loss, validation metric, learning rate and gradient norm every N steps.
8. Sanity check first: overfit 8 samples to near zero loss. If it cannot, fix the loop before touching hyperparameters.

## Rules

- Never call `.item()` on every step in a hot loop; accumulate tensors and sync periodically.
- Never evaluate on the training split.

## Report

The files written, the overfit test result, and how to resume from a checkpoint.