Training Hyperparameters: Epochs, Learning Rate, Batch Size and More
What exactly is an epoch, a batch, an iteration? What happens when you change the number of epochs, the learning rate, the batch size or the model size — and how these knobs interact. With hands-on experiments in a real training lab.
Training a neural network is a loop: show the model some examples, measure the error, nudge the weights, repeat. A handful of hyperparameters — numbers you choose, not the model — control that loop: how many times the model sees the data (epochs), how many examples it looks at before each nudge (Batch size), how big each nudge is (Learning rate), and how big the model is (capacity). Getting them right is often the difference between a model that learns in minutes and one that never learns at all. This lesson answers the question every beginner asks: “What is an epoch, and what happens if I change it?” — and the same for every other knob.
- Epoch = reading the whole textbook once, cover to cover.
- Batch = the few pages you read before pausing to update your summary notes.
- Iteration (step) = one such pause-and-update of your notes.
- Learning rate = how much you rewrite your notes at each pause: a few words, or the whole page?
- Capacity (hidden units) = how big your notebook is. A tiny notebook can't hold the material (underfitting); a huge one lets you copy the practice questions word-for-word instead of understanding them (overfitting).
The vocabulary of the training loop
| Term | Meaning | Example: N = 50,000 images, batch size 128 |
|---|---|---|
| Sample / example | One input with its label | One image + its class |
| Batch (mini-batch) | A group of samples processed together; their gradients are averaged into one update | 128 images |
| Iteration / step | One forward pass + backward pass + weight update on one batch | 1 update of the weights |
| Epoch | One full pass over the whole training set | ⌈50,000 / 128⌉ = 391 iterations (the last batch has only 80 images) |
| Training run | All epochs together | 20 epochs = 7,820 iterations |
- iterations per epoch
- number of mini-batches (= weight updates) needed to pass over the data once
- total iterations
- all weight updates in the whole training run
- epochs
- number of full passes over the training set (Epoch)
- N
- number of training examples
- B
- Batch size: examples per mini-batch
- ⌈
- ⌈ … ⌉ = ceiling: round up to the next whole number (the last, smaller batch still counts)
- ⌉
- closing bracket of the ceiling
- ×
- multiplication
▸Worked example
from torch.utils.data import DataLoader
loader = DataLoader(train_dataset, batch_size=128, shuffle=True) # reshuffled every epoch
print(len(loader)) # iterations per epoch = ceil(50_000 / 128) = 391
for epoch in range(20): # 20 epochs ...
for xb, yb in loader: # ... x 391 iterations each = 7,820 steps
loss = loss_fn(model(xb), yb)
optimizer.zero_grad()
loss.backward()
optimizer.step() # one iteration = one weight updatelen(DataLoader) gives iterations per epoch[1].Epochs: how long to train
Early in training, both the Training loss and the Validation loss fall: the model is learning general patterns. If you keep going, the training loss keeps falling, but at some point the validation loss flattens and then rises — the model has started memorising noise and quirks of the training set (Overfitting). Too few epochs and you stop while both losses are still high (Underfitting). The sweet spot is the epoch with the lowest validation loss; Early stopping finds it automatically by watching the validation loss and keeping the best Checkpoint. How many epochs that takes depends on everything else: data size, learning rate, batch size, model size and regularization. Tiny datasets may need thousands of epochs; large image models are typically trained for tens to a few hundred; LLM pretraining often sees most of its data only about once.
- What it is
- How many full passes over the training set to make. Together with batch size it fixes the total number of weight updates.
- ↑ If you increase it
- More updates → training loss keeps going down. Validation loss improves at first, then plateaus, then often rises (overfitting) — especially with a big model, a small dataset and little regularization. Training time grows linearly. With early stopping, setting epochs “too high” is cheap insurance.
- ↓ If you decrease it
- Faster runs, but you may stop while the model is still improving (underfitting): both training and validation loss are still high and still falling at the end of the curve.
- Typical values
- Small tabular/toy data: 100–2000. Image classifiers from scratch: ~90–300 (ImageNet ResNet recipes: ~90). Fine-tuning pretrained models: 1–10. LLM pretraining: ~1 pass over most data.
Learning rate: the size of each step
- w
- the weights (all trainable parameters)
- ←
- assignment: replace w with the value on the right (repeated every step)
- η
- eta — the Learning rate, typically 0.0001–0.1
- ∇L(w)
- Gradient of the loss at the current weights: the direction of steepest increase
- ·
- multiply: step = η × gradient
▸Worked example
The learning rate is usually the single most important hyperparameter. Too small and training crawls — after hundreds of epochs the loss has barely moved. Too large and each step overshoots the valley: the loss oscillates, gets stuck high, or explodes to NaN. In between there is a range where loss falls quickly and steadily. A practical way to find it is the LR range test from Leslie Smith's “Cyclical Learning Rates” paper: train briefly while increasing the learning rate exponentially every iteration, plot loss vs. learning rate, and pick a value a bit below where the loss stops falling and starts to blow up[4][5]. Most real training also changes the learning rate over time (warmup then decay) — see the next lesson, learning rate schedules.
- What it is
- The multiplier on the gradient in every update — how far the weights move per iteration.
- ↑ If you increase it
- Faster progress per step, up to a point. Past the stable limit the loss becomes noisy, oscillates, plateaus high, or diverges to NaN; with ReLU, large steps can also kill units. Slightly high learning rates can add useful noise that helps generalization.
- ↓ If you decrease it
- Smoother, more stable curves but slow progress: you need many more epochs to reach the same loss, and you may get stuck on plateaus. Very small values look like “the model isn't learning”.
- Typical values
- SGD + momentum: 0.01–0.1 (ResNet on ImageNet: 0.1 at batch 256). Adam/AdamW: 1e-4–3e-3 (default 1e-3). Fine-tuning pretrained Transformers: 1e-5–5e-5. Always search on a log scale (1e-4, 3e-4, 1e-3, …).
Batch size: how many examples per update
The gradient of a mini-batch is an estimate of the gradient over the whole dataset. A bigger batch gives a more accurate estimate (less noise), but the improvement is slow: noise shrinks only with √B, so going from 32 to 128 examples halves the noise while costing 4× the compute per step. Batch size also decides how many updates you get per epoch — that is often the bigger effect. Batch size 1 is classic stochastic gradient descent; using all N samples is full-batch gradient descent; everything in between is mini-batch SGD, the standard.
- Var
- variance: average squared deviation from the mean — a measure of spread (noise)
- ĝ_B
- “g-hat”: the Gradient estimated from one mini-batch of B examples (the average of B per-example gradients)
- σ²
- sigma squared: variance of the gradient computed from a single example
- B
- Batch size
- ≈
- approximately (exact when examples are drawn independently)
- ⇒
- “therefore / which implies”
- noise (std)
- standard deviation = √variance: the typical size of the random error in the gradient
- ∝
- “is proportional to”: changes by the same factor
- √
- square root
▸Worked example
Does the noise matter? Keskar et al. (2016) found that very large batches tend to converge to sharp minima that generalize worse than the flatter minima found by small-batch training — a “generalization gap”[3]. Masters & Luschi (2018) reported the best results with small batches (often 2–32) for a fixed number of epochs[6]. On the other hand, Goyal et al. (2017) trained ResNet-50 on ImageNet with batches of 8,192 in one hour with no loss of accuracy — if the learning rate is scaled up with the batch and warmed up gradually[2]. The lesson: batch size can't be changed in isolation.
- What it is
- Number of samples whose gradients are averaged for one weight update.
- ↑ If you increase it
- Smoother, less noisy gradients and better GPU utilisation (more samples/second), but fewer updates per epoch — at the same learning rate and epochs, the model may end up undertrained. Memory grows linearly. Very large batches can generalize worse (sharp minima) unless the learning rate and warmup are adjusted.
- ↓ If you decrease it
- More updates per epoch and noisier gradients — the noise acts as a regularizer and often helps generalization. But each step uses the hardware less efficiently (slower wall-clock), curves look jagged, and BatchNorm statistics become unreliable below ~8–16. Usually needs a smaller learning rate.
- Typical values
- 32–256 for most vision/tabular work (powers of 2 are conventional, not required). LLM pretraining: millions of tokens per batch. Limited by GPU memory — use Gradient accumulation to simulate bigger batches.
Iterations (steps): the real clock
Because the weights only change at each iteration, experienced practitioners often think in steps rather than epochs. Learning-rate schedules, warmup, logging and checkpointing in large projects are usually defined in steps. When you compare two runs with different batch sizes or dataset sizes, comparing them “at epoch 10” compares runs that made different numbers of updates. Example: N = 24 samples, 500 epochs. Batch 1 → 24 × 500 = 12,000 updates; batch 8 → 3 × 500 = 1,500; full batch → 500. Same epochs, 24× difference in updates.
- What it is
- Total number of weight updates = epochs × ⌈N / B⌉. Some frameworks (e.g. Hugging Face
max_steps) let you set it directly instead of epochs. - ↑ If you increase it
- More optimisation: lower training loss; validation loss follows until overfitting begins. Costs proportionally more compute. With a schedule defined over total steps, the whole schedule stretches.
- ↓ If you decrease it
- Less compute, but risk of stopping before convergence (underfitting). If you raised the batch size, you silently reduced iterations — compensate with more epochs or a larger learning rate.
- Typical values
- Ranges from a few hundred (fine-tuning) to hundreds of thousands (training from scratch).
Capacity: hidden units and layers
- What it is
- The number of neurons in the hidden layer(s) — how flexible a function the network can represent. Depth (number of layers) is the other capacity knob.
- ↑ If you increase it
- Can fit more complex patterns; training loss can go lower and usually drops faster per epoch. On small or noisy data it reaches the overfitting point sooner (validation loss turns upward earlier), so pair it with weight decay, dropout or early stopping. More memory and compute per step.
- ↓ If you decrease it
- Too few units → the model is too simple (underfitting): training loss plateaus high no matter how many epochs you run. With 1–2 tanh units, the lab's curve can only make one or two bends.
- Typical values
- Start reasonably big and regularize, rather than tiny and underfit (a common recipe). In the lab, 8–32 units fit the curve well.
How the knobs interact
| If you change… | …this also changes | What to do |
|---|---|---|
| Batch size ×2 | Iterations per epoch ÷2; gradient noise ÷√2 | Scale learning rate ×2 (linear scaling rule) with warmup, or train for more epochs |
| Epochs ×2 | Iterations ×2; an epoch-based LR schedule stretches | Watch validation loss for overfitting; rely on early stopping |
| Learning rate ×10 | Step size; stability | Fewer epochs may suffice — or it diverges. Re-check with a short run; consider warmup |
| Hidden units ×4 | Capacity; overfitting starts at an earlier epoch | Add regularization; sometimes lower LR for very wide/deep models |
| Training set ×4 | Iterations per epoch ×4; overfitting is reduced | Fewer epochs needed for the same number of steps; a bigger model may now pay off |
- η_new
- Learning rate to use with the new batch size
- η_base
- a learning rate known to work well at the base batch size
- B_new
- the new Batch size
- B_base
- the base (reference) batch size
- ×
- multiplication
- η
- the resulting learning rate in the worked instance
▸Worked example
Why does the rule work? With SGD, k small steps of size η on k different batches move the weights roughly as far as one big step of size kη on one batch k times bigger — as long as the gradient doesn't change much over those k steps. That assumption fails at the very start of training (weights change fast), which is exactly why warmup is needed[2].
- Baseline. Hidden units 16, learning rate ≈ 0.01–0.03, batch 8, epochs 500, weight decay 0. Press Train. Note the final train/val loss, the best-val epoch marker and the iteration count (with 24 training points: 3 iterations/epoch × 500 = 1,500).
- Epochs — too few. Change only epochs to 20. The fitted curve is still a rough, flattened line and both losses are still falling at the end: underfitting. The diagnosis should agree.
- Epochs — too many. Set hidden units to 64, epochs to 2000, add more noise. Watch train loss keep dropping while val loss bottoms out and climbs: the marker shows where early stopping would have stopped. The fitted curve starts wiggling through individual noisy points.
- Learning rate. Back to the baseline. Try 1e-4: the diagnosis says “too slow” — 500 epochs aren't enough. Then try 0.3–1: the loss oscillates, or explodes (diverged). Find the largest value that still gives a smooth curve — that is roughly your best learning rate.
- Batch size and iterations. Keep 500 epochs and compare batch 1 vs full batch. Batch 1 does 24× more updates and gets far lower loss, with a noisier curve; full batch is smooth but slow. Now raise the learning rate for full batch (e.g. ×4–×8) and see how much of the gap closes — the linear scaling rule in miniature.
- Capacity. Set hidden units to 1 or 2: the curve can't bend enough no matter how long you train (underfitting). Then 64 units with a small training set: overfitting. Finally keep 64 units but set weight decay to 0.001–0.01 — the val curve stops rising as much.
- More data. With the overfitting setup, increase the training-set size. The gap between train and val loss shrinks, and the best-val epoch moves later: more data is the most reliable cure for overfitting.
| Other knob in the lab | Raise it | Lower it |
|---|---|---|
| Weight decay | Smoother fit, less overfitting; too much → underfits (curve flattens) | More freedom to fit noise |
| Training-set size | Less overfitting; more iterations per epoch | Overfits sooner; fewer iterations per epoch |
| Noise | Higher achievable val loss; overfitting more visible | Easier problem; even big models overfit less |
- Sanity check: make the model overfit a single small batch (loss → ~0). If it can't, there's a bug.
- Batch size: pick the largest that fits comfortably in memory, or a standard value like 32–256.
- Learning rate: run an LR range test or a quick log-scale sweep (1e-4 … 1e-1) for a few hundred steps; take the best.
- Epochs: set generously and use early stopping on the validation loss.
- Capacity & regularization: if underfitting, make the model bigger; if overfitting, add data/augmentation, weight decay or dropout.
- Changing batch size later? Rescale the learning rate (linear rule + warmup) rather than starting over.
import math, copy, torch
N, batch_size, epochs = len(train_ds), 64, 200
base_lr, base_batch = 1e-3, 64
lr = base_lr * batch_size / base_batch # linear scaling if you change batch_size
steps_per_epoch = math.ceil(N / batch_size)
total_steps = epochs * steps_per_epoch
print(f"{steps_per_epoch} iterations/epoch, {total_steps} total")
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)
best_val, best_state, patience, bad_epochs = float("inf"), None, 20, 0
for epoch in range(epochs):
model.train()
for xb, yb in train_loader: # steps_per_epoch iterations
loss = loss_fn(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
val = sum(loss_fn(model(xb), yb).item() for xb, yb in val_loader) / len(val_loader)
if val < best_val: # early stopping bookkeeping
best_val, best_state, bad_epochs = val, copy.deepcopy(model.state_dict()), 0
else:
bad_epochs += 1
if bad_epochs >= patience:
print(f"stopping at epoch {epoch}, best val {best_val:.4f}")
break
model.load_state_dict(best_state) # keep the best-validation weights- Changing batch size without touching the learning rate and concluding “bigger batches are worse”. You also changed the number of updates.
- Comparing runs by epoch when batch size or dataset size differ — compare by steps (and wall-clock time).
- Choosing the number of epochs on the test set. Use the validation set; the Test set is for the final report only.
- Not shuffling the training data each epoch: batches become correlated (e.g. sorted by class) and training oscillates.
- Loss becomes NaN: usually the learning rate is too high (or there's no warmup); also check for bad inputs and consider Gradient clipping.
- Calling a schedule's `step()` per epoch when it was configured in iterations (or vice versa) — the LR decays 391× too fast or too slow.
▸Go deeper: noise scale, sharp minima and the critical batch size
- g
- the noise scale: one number summarising how random the SGD updates are (here g is not the gradient)
- ≈
- approximately — the exact expression is η·(N/B − 1)
- η
- Learning rate
- N
- number of training examples
- B
- Batch size
- ≪
- “much smaller than”
▸Worked example
Keskar et al. measured the sharpness of the minima reached with small vs large batches and linked sharpness to the generalization gap[3]; later work showed much of the gap can be closed by adjusting learning rate, warmup and training length. McCandlish et al. (An Empirical Model of Large-Batch Training, 2018) introduced the critical batch size: below it, doubling the batch nearly halves the number of steps needed (perfect scaling); above it, bigger batches mostly waste compute. The critical batch size grows as the loss gets lower, which is one reason large-model training ramps up the batch size over time.
Quiz
References
- [1]torch.utils.data — DataLoaderDocsPyTorchdocs.pytorch.org
- [2]Accurate, Large Minibatch SGD: Training ImageNet in 1 HourPaperGoyal et al.2017arxiv.orgLinear scaling rule and gradual warmup.
- [3]On Large-Batch Training for Deep Learning: Generalization Gap and Sharp MinimaPaperKeskar et al.2016arxiv.org
- [4]Cyclical Learning Rates for Training Neural NetworksPaperSmith2015arxiv.orgIntroduces the LR range test.
- [5]
- [6]Revisiting Small Batch Training for Deep Neural NetworksPaperMasters & Luschi2018arxiv.org