Concept Explanation
The training loop is the heart of deep learning, and it is short enough to memorise. Everything else — architectures, schedulers, augmentation — is decoration around these six lines:
for epoch in range(epochs):
for batch_X, batch_y in train_loader:
optimiser.zero_grad() # 1. clear old gradients
predictions = model(batch_X) # 2. forward pass
loss = criterion(predictions, batch_y) # 3. how wrong were we?
loss.backward() # 4. gradients for every parameter
optimiser.step() # 5. nudge parameters downhill
The Vocabulary
| Term | Meaning |
|---|---|
| Batch | A group of samples processed together before one update |
| Iteration / step | One batch: one forward, one backward, one update |
| Epoch | One complete pass over the training set |
| Learning rate | How far each update moves the parameters |
With 10,000 samples and a batch size of 32, one epoch is 313 iterations — 313 parameter updates, not one.
Why Batches at All?
| Batch size | Trade-off |
|---|---|
| 1 (stochastic) | Noisy gradients, slow, escapes bad minima |
| 32–256 (mini-batch) | The practical sweet spot |
| Whole dataset | Smooth gradients, may not fit in memory, fewer updates |
Batching is a compromise between gradient quality and update frequency. 32 or 64 is a safe default; larger batches often need a proportionally larger learning rate.
DataLoader Does the Plumbing
from torch.utils.data import TensorDataset, DataLoader
train_ds = TensorDataset(X_train, y_train)
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)
shuffle=True on the training set is not optional. Without it, the model sees samples in the same order every epoch and can latch onto that order. Never shuffle validation or test data — there is no benefit and it makes debugging harder.
train() vs eval()
model.train() # dropout active, batchnorm updating its statistics
model.eval() # dropout off, batchnorm using stored statistics
These flags do not touch gradients — they change layer behaviour. Forgetting model.eval() before validation means dropout randomly deletes neurons during evaluation, so your validation loss looks worse than it is and jumps around between runs. Pair model.eval() with torch.no_grad(); they solve different problems.
Reading the Two Curves
The whole point of tracking validation loss is to see this pattern:
epoch train val
1 0.681 0.664 both falling -> learning
5 0.402 0.398 both falling -> still learning
12 0.221 0.243 val flattening -> approaching the limit
20 0.098 0.281 val RISING -> overfitting starts here
35 0.021 0.377 val much worse -> memorising the training set
The best model is the one from around epoch 12, not epoch 35. Training longer made it worse. This is why early stopping and checkpointing the best validation loss matter more than any architectural tweak.
The Fixes for Overfitting, In Order of Value
| Fix | How |
|---|---|
| More data | Always first if available |
| Data augmentation | Flips, crops, noise — free extra data |
| Early stopping | Stop when validation stops improving |
| Dropout | nn.Dropout(0.3) between layers |
| Weight decay | Adam(..., weight_decay=1e-4) |
| Smaller model | Fewer parameters to memorise with |
Optimisers and Learning Rate
Adam at lr=1e-3 is the default that works. SGD with momentum can generalise slightly better but needs more tuning. The learning rate is the single most important hyperparameter: too high and the loss oscillates or becomes NaN; too low and it crawls. A scheduler such as ReduceLROnPlateau cuts the rate when validation stalls, which is usually worth two or three points of accuracy.
Code Example #1 (Basic)
A complete loop with validation tracking, on a small tabular problem.
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
X, y = make_classification(n_samples=4000, n_features=20, n_informative=10,
n_classes=2, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=0)
scaler = StandardScaler().fit(X_train)
to_t = lambda a, dt: torch.tensor(a, dtype=dt)
train_loader = DataLoader(
TensorDataset(to_t(scaler.transform(X_train), torch.float32),
to_t(y_train, torch.float32).unsqueeze(1)),
batch_size=64, shuffle=True)
val_loader = DataLoader(
TensorDataset(to_t(scaler.transform(X_val), torch.float32),
to_t(y_val, torch.float32).unsqueeze(1)),
batch_size=256, shuffle=False) # never shuffle validation
model = nn.Sequential(
nn.Linear(20, 64), nn.ReLU(), nn.Dropout(0.2),
nn.Linear(64, 32), nn.ReLU(),
nn.Linear(32, 1), # raw logits, no sigmoid
).to(device)
criterion = nn.BCEWithLogitsLoss() # sigmoid + BCE, numerically stable
optimiser = torch.optim.Adam(model.parameters(), lr=1e-3)
print(f"{'epoch':>5} {'train':>8} {'val':>8} {'val acc':>8}")
for epoch in range(1, 21):
model.train() # dropout ON
train_loss = 0.0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
optimiser.zero_grad()
loss = criterion(model(xb), yb)
loss.backward()
optimiser.step()
train_loss += loss.item() * len(xb) # .item(), not the tensor
train_loss /= len(train_loader.dataset)
model.eval() # dropout OFF
val_loss, correct = 0.0, 0
with torch.no_grad(): # no graph needed
for xb, yb in val_loader:
xb, yb = xb.to(device), yb.to(device)
logits = model(xb)
val_loss += criterion(logits, yb).item() * len(xb)
correct += ((logits > 0).float() == yb).sum().item()
val_loss /= len(val_loader.dataset)
acc = correct / len(val_loader.dataset)
if epoch % 2 == 0 or epoch == 1:
print(f"{epoch:>5} {train_loss:>8.4f} {val_loss:>8.4f} {acc:>8.3f}")
Two details worth copying: BCEWithLogitsLoss instead of a Sigmoid layer plus BCELoss (it is numerically stable, and the two-step version silently loses precision), and multiplying by len(xb) when accumulating so the final average is correct even though the last batch is smaller.
Code Example #2 (Intermediate)
Early stopping, best-model checkpointing, and a learning-rate scheduler.
import copy
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
torch.manual_seed(1)
device = "cuda" if torch.cuda.is_available() else "cpu"
# Deliberately small and noisy so overfitting is visible within 60 epochs
X, y = make_classification(n_samples=900, n_features=40, n_informative=12,
flip_y=0.08, random_state=1)
X_tr, X_va, y_tr, y_va = train_test_split(X, y, test_size=0.25,
random_state=1, stratify=y)
sc = StandardScaler().fit(X_tr)
def loader(Xa, ya, bs, shuffle):
return DataLoader(TensorDataset(
torch.tensor(sc.transform(Xa), dtype=torch.float32),
torch.tensor(ya, dtype=torch.float32).unsqueeze(1),
), batch_size=bs, shuffle=shuffle)
train_loader = loader(X_tr, y_tr, 32, True)
val_loader = loader(X_va, y_va, 256, False)
def build(dropout=0.0):
return nn.Sequential(
nn.Linear(40, 256), nn.ReLU(), nn.Dropout(dropout),
nn.Linear(256, 128), nn.ReLU(), nn.Dropout(dropout),
nn.Linear(128, 1),
).to(device)
def run(model, epochs=60, lr=1e-3, weight_decay=0.0, patience=None):
criterion = nn.BCEWithLogitsLoss()
optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimiser, mode="min", factor=0.5, patience=4)
history = []
best_val, best_state, best_epoch, stale = float("inf"), None, 0, 0
for epoch in range(1, epochs + 1):
model.train()
tl = 0.0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
optimiser.zero_grad()
loss = criterion(model(xb), yb)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 5.0) # guards against spikes
optimiser.step()
tl += loss.item() * len(xb)
tl /= len(train_loader.dataset)
model.eval()
vl, correct = 0.0, 0
with torch.no_grad():
for xb, yb in val_loader:
xb, yb = xb.to(device), yb.to(device)
logits = model(xb)
vl += criterion(logits, yb).item() * len(xb)
correct += ((logits > 0).float() == yb).sum().item()
vl /= len(val_loader.dataset)
acc = correct / len(val_loader.dataset)
scheduler.step(vl)
history.append((epoch, tl, vl, acc))
if vl < best_val - 1e-4:
best_val, best_epoch, stale = vl, epoch, 0
best_state = copy.deepcopy(model.state_dict()) # checkpoint the BEST
else:
stale += 1
if patience and stale >= patience:
print(f" early stop at epoch {epoch} "
f"(no improvement for {patience} epochs)")
break
model.load_state_dict(best_state) # restore the best, not the last
return history, best_val, best_epoch
print("=== No regularisation, trained to the bitter end ===")
hist, best, at = run(build(dropout=0.0), epochs=60, patience=None)
print(f"{'epoch':>6} {'train':>8} {'val':>8} {'acc':>7}")
for e, tl, vl, acc in hist:
if e in (1, 5, 10, 20, 40, 60):
print(f"{e:>6} {tl:>8.4f} {vl:>8.4f} {acc:>7.3f}")
print(f"best val {best:.4f} at epoch {at} -- training past it made things worse\n")
print("=== Dropout + weight decay + early stopping ===")
hist2, best2, at2 = run(build(dropout=0.3), epochs=60,
weight_decay=1e-4, patience=10)
print(f"{'epoch':>6} {'train':>8} {'val':>8} {'acc':>7}")
for e, tl, vl, acc in hist2:
if e % 10 == 0 or e == 1 or e == hist2[-1][0]:
print(f"{e:>6} {tl:>8.4f} {vl:>8.4f} {acc:>7.3f}")
print(f"best val {best2:.4f} at epoch {at2}")
final_acc = max(h[3] for h in hist2)
print(f"\nRegularised best accuracy: {final_acc:.3f}")
print(f"Improvement in val loss: {best - best2:+.4f}")
The copy.deepcopy(model.state_dict()) line is the one people leave out and regret. Without it you finish training and keep whatever the last epoch produced, which — as the first run's numbers show — is often much worse than what you had twenty epochs earlier.
Common Mistakes
- Forgetting
optimiser.zero_grad(): gradients accumulate across batches and training diverges. The most common bug in PyTorch code. - Not calling
model.eval()before validation: dropout stays active, so validation loss is noisy and pessimistic. - Not calling
model.train()again at the top of the next epoch: dropout stays off and regularisation quietly stops working. - Validating without
torch.no_grad(): builds a graph you throw away, wasting memory and risking OOM. - Shuffling the validation set: no benefit, and it makes per-batch debugging impossible.
- Accumulating
lossinstead ofloss.item(): keeps every batch's graph in memory. Guaranteed OOM on a long epoch. - Keeping the final model instead of the best one: checkpoint on validation improvement.
- Adding
Sigmoidthen usingBCELoss: useBCEWithLogitsLosson raw logits instead — same maths, numerically stable. - Applying
SoftmaxbeforeCrossEntropyLoss: it applies log-softmax internally. Doing both flattens your gradients. - Judging progress by training loss: it almost always keeps falling. Only validation loss tells you whether the model is improving.
- A learning rate that produces
NaN: if loss becomesNaNon the first few steps, divide the learning rate by 10.
Best Practices
- Write the loop the same way every time: zero, forward, loss, backward, step. Consistency prevents the subtle bugs.
- Track training and validation loss every epoch and print them side by side. The gap is your diagnosis.
- Checkpoint the best validation loss with
copy.deepcopy(model.state_dict()), and restore it at the end. - Use early stopping with patience of 5–15 epochs — it saves compute and lands on a better model.
- Pair
model.eval()withtorch.no_grad()for every evaluation block. - Start with
Adamatlr=1e-3, batch size 32–64. Tune only after you have a working baseline. - Add
ReduceLROnPlateaubefore you add layers; a schedule is usually cheaper than capacity. - Clip gradients with
clip_grad_norm_for RNNs and any model where loss occasionally spikes. - Overfit a single batch first: if the model cannot drive loss to near zero on 32 samples, the bug is in your code, not your hyperparameters.
- Weight the running loss by batch size so the epoch average is correct despite a short final batch.
- Seed everything while debugging so a change in the numbers means a change in your code.
Practice Exercises
- The Overfitting Demo: Train an oversized network on fewer than 500 samples for 100 epochs with no regularisation, recording train and validation loss each epoch. Print the epoch where validation loss bottomed out and how much worse it got by epoch 100.
- The Single-Batch Sanity Check: Take one batch of 32 samples and train on only that batch for 200 steps. Confirm the loss approaches zero, then write a comment explaining what it means if it does not.
- The Checkpoint: Add best-validation checkpointing and early stopping with
patience=8to any training loop. Print the final validation loss both with and without restoring the best state, and compare.