Sub-Chapter 6.7

Training, Epochs & Mini-Batches

The choreography of learning — how networks see data, update weights, and converge over time. From a single iteration to a full training run.

22 min read Core mechanics 2 demos 4 quiz questions
Scroll
Orientation

Why “training” needs vocabulary

In the last sub-chapter we walked through a single backprop step. Real models take millions of those steps. To talk about that process precisely, engineers use three words constantly: iteration, epoch, and batch size. Get these straight and the rest of training is mostly bookkeeping.

The training loop — one beat at a time

Every modern deep-learning trainer, whether 50 lines of NumPy or a 100k-line PyTorch project, executes this same five-step rhythm:

  1. Load a batch — pull B examples from the training set.
  2. Forward pass — compute predictions for those B examples.
  3. Compute loss — compare predictions to ground truth.
  4. Backward pass — compute gradients of loss w.r.t. every weight.
  5. Update weights — nudge weights in the direction that reduces loss.

That five-step cycle is one iteration. Repeat it until you’ve seen every training example once — that’s one epoch. Repeat epochs until the validation loss stops improving.

Civil-engineering analogy

Training a network is like calibrating a draft structural-design code from historical project data:

  • One mini-batch = updating provisions after reviewing a small handful of past projects.
  • One epoch = re-reading the entire case database front to back.
  • Validation set = a separate set of independent bridges held aside to test whether the code generalizes.
  • Test set = a sealed envelope of cases opened only once at the very end — the final, unbiased report card.
Vocabulary

Iteration, epoch, batch size

These three numbers are tied by a simple equation. Memorize it.

The fundamental relation

iterations per epoch  =  ceil( Ntrain / batch_size )

If you have 50,000 training examples and a batch size of 64, one epoch is ceil(50000 / 64) = 782 iterations. Train for 30 epochs and the optimizer takes 782 × 30 = 23,460 weight updates.

Iteration (a.k.a. step)

One forward + backward + update on a single mini-batch. The smallest atomic unit of training.

When you read “loss at step 5,000,” this is what is meant.

Epoch

One complete pass through the entire training dataset. The model has now “seen” every example exactly once (assuming no oversampling).

Most papers report results “after N epochs.”

Batch size B

Number of examples processed together in a single iteration. The gradient is averaged across these B examples before the update.

Common values: 8, 16, 32, 64, 128, 256, 512, 1024.

Dataset size N

The total number of training examples. Distinct from the validation and test counts, which are held out.

Modern image datasets: 104–109 examples.

Quick sanity check. If someone says “we trained for 100k steps” without telling you the batch size or dataset size, you cannot convert that to epochs. Always ask for all three.
Data splits

Train / Validation / Test

You never train on all your data. A portion is sacrificed for honest evaluation — otherwise you cannot tell whether your model has actually learned something or simply memorized the answers.

The three-way split

Typical ratios: 70/15/15 or 80/10/10 for medium datasets, and as little as 98/1/1 when you have millions of examples (1% of 10M is still 100k — plenty for evaluation).

  • Training set: the model learns from these. Weights are updated using their gradients.
  • Validation set: the model is evaluated on these every epoch. Used to pick the best epoch, tune learning rate, decide when to stop. The model never trains on them, but you (the engineer) do use them to make decisions — so they become contaminated over time.
  • Test set: opened exactly once, at the end, to report the final number. Never used for any tuning.

Why a separate validation set?

Because any decision you make using the test set turns it into a validation set. You only get one truly clean estimate of generalization — protect it.

Stratified sampling

For imbalanced datasets (95% safe / 5% defective), random splitting can leave the rare class missing from validation. Stratified sampling preserves the class ratio inside each split.

Time-based splits

For time-series (e.g., concrete-curing sensor data), random splitting leaks the future into the past. Always split chronologically: train on weeks 1–30, validate on 31–33, test on 34–36.

Group-aware splits

If multiple photos of the same bridge appear in your dataset, all of them must go to the same split. Otherwise the model sees the same bridge in training and validation — an instant leak.

Data leakage is the #1 cause of “impossibly good” results that fail in production. Whenever your validation accuracy looks too good, suspect a leak first.
Diagnostics

Reading learning curves

Plot training loss and validation loss against epochs. The shape of those two lines tells you everything you need to know about the health of your training run.

Underfitting

Both train and validation loss are high and barely decreasing. The model lacks the capacity (or hasn’t trained long enough) to fit the data.

Fix: bigger model, longer training, better features, lower regularization.

Just right

Both losses decrease together and plateau close to each other. The small gap between them is normal and represents the model’s honest generalization error.

Action: stop training, save model.

Overfitting

Train loss keeps falling but validation loss bottoms out and starts rising. The model is memorizing training noise.

Fix: more data, regularization, dropout, early stopping (we cover these in 6.8).

Early stopping — the simplest regularizer

Watch the validation loss every epoch. The moment it stops improving for, say, 5 epochs in a row (the “patience”), kill the run and load the weights from the best epoch. That’s it. Free regularization.

training_loop.py
best_val = float("inf")
patience, bad = 5, 0

for epoch in range(max_epochs):
    model.train()
    for xb, yb in train_loader:        # one iteration each
        pred = model(xb)
        loss = loss_fn(pred, yb)
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

    model.eval()
    val_loss = evaluate(model, val_loader)

    if val_loss < best_val:
        best_val = val_loss
        save_checkpoint(model)
        bad = 0
    else:
        bad += 1
        if bad >= patience:
            print(f"Early stop at epoch {epoch}")
            break
Interactive demo 1

Training Loop Visualizer

Watch a small synthetic regression model train in real time. Pick a model complexity and see whether the curves stay flat (underfit), converge nicely (just right), or diverge (overfit).

Epoch0
Train loss—
Val loss—
Val accuracy—
Statusidle

The blue curve is training loss; the orange curve is validation loss. Try High complexity and watch the orange curve eventually rise — classic overfitting.

Tradeoffs

Batch size: small vs. large

Batch size is one of the few hyperparameters that touches everything: speed, memory, gradient quality, generalization, and required learning rate. Here’s the cheat sheet.

Small batches (8 – 32)

  • Noisy gradients — each step jitters around the “true” gradient.
  • Often better generalization — the noise acts like a regularizer.
  • Slower per-epoch wall-clock time on GPU (under-utilized hardware).
  • Lower memory footprint.
  • Can use a higher learning rate without diverging.

Large batches (256 – 1024+)

  • Smooth gradients — closer to the true full-dataset gradient.
  • Faster per-epoch on modern GPUs (better parallelism).
  • Often worse final generalization without careful tuning.
  • Higher memory footprint — can blow up VRAM.
  • Usually need to scale the learning rate up proportionally (linear-scaling rule).
Linear-scaling rule (Goyal et al. 2017). If you double the batch size, double the learning rate (up to a limit). Roughly preserves training dynamics.
Interactive demo 2

Batch Size Effect

Three identical models trained on the same data with three different batch sizes. Watch the texture of each loss curve — B=8 jitters wildly, B=256 glides.

B = 8 (noisy) B = 64 B = 256 (smooth)
Iter0
B=8 loss—
B=64 loss—
B=256 loss—

All three runs use the same learning rate and dataset. Notice how B=8 takes more iterations but its noisy descent often reaches a better final loss.

Pipeline hygiene

Shuffling, stratification, augmentation

Three habits that separate a working training pipeline from a broken one.

Shuffle every epoch

If your dataset is sorted by class (all cracks first, then all spalls, then all corrosion), an unshuffled iterator hands the model an entire epoch of one class before showing any of the next. The result is wild oscillation in the loss and unstable training. Shuffling at the start of every epoch fixes this.

The validation and test sets are not shuffled — consistency matters more than order there.

Stratified sampling for imbalanced data

If 95% of your bridge inspections are “safe” and 5% are “defective,” a random batch of 32 will sometimes contain zero defective examples — the loss on that step says nothing about the rare class. Stratified samplers ensure each batch contains a controlled mix.

Data augmentation in the pipeline

For images, the same example is resampled with random crop, flip, brightness, and rotation each time it’s loaded. The model effectively sees a different version every epoch, multiplying the apparent dataset size. This is the single most effective regularizer for vision models — we explore it in detail in 6.8.

Augment training only. Validation and test data must remain untouched, otherwise your evaluation numbers are meaningless.

Civil Engineering Application

Iterative Design Process

Neural network training mirrors the iterative analysis cycle in structural design: assume dimensions → compute forces → check adequacy → adjust → repeat. Each epoch is one full design iteration. Batch size is how many load cases you check before making adjustments.

Overfitting on Limited Field Data

CE datasets are often small (30-100 borehole logs, 50-200 concrete tests). Training too many epochs causes the model to memorize noise in test results rather than learning true material behavior. The validation curve is your early warning system — when it starts rising, stop training.

Check your understanding

Quiz

Four short questions. Click any option to reveal the explanation.

1 You have 80,000 training examples and a batch size of 32. How many iterations is one epoch?

  • 32
  • 800
  • 2,500
  • 80,000
80,000 / 32 = 2,500 iterations per epoch.

2 Training loss keeps falling but validation loss is rising. What is happening?

  • Underfitting — the model needs more capacity
  • Overfitting — the model is memorizing training noise
  • The optimizer is broken
  • The learning rate is too low
A growing gap between falling train loss and rising val loss is the textbook signature of overfitting. Time for early stopping or regularization.

3 Why hold out a separate test set in addition to a validation set?

  • Because the GPU needs more data to warm up
  • Because every decision made using the validation set contaminates it; the test set is opened only once for an unbiased final estimate
  • To double the size of the training set
  • It is a backup in case the validation set is lost
You tune learning rate, architecture, and stopping epoch using validation feedback. That gradually overfits the validation set. The test set is kept sealed to give one honest final number.

4 A colleague switches from batch size 32 to 256 with no other changes and the model now diverges. What is the most likely fix?

  • Reduce the dataset size
  • Disable shuffling
  • Increase the learning rate (roughly proportionally)
  • Train for fewer epochs
Larger batches give smaller-magnitude weight updates per epoch. The linear-scaling rule says: scale the learning rate up roughly in proportion to the batch-size increase.
Recap

What you should walk away with

  • Training is a tight five-step loop: load → forward → loss → backward → update.
  • One iteration = one mini-batch. One epoch = one pass over the whole training set.
  • iterations_per_epoch = ceil(N / batch_size).
  • Always split data into train, validation, and test — and respect the boundaries.
  • Diagnose runs by reading the train/val loss curves: flat = underfit, diverging = overfit, parallel = healthy.
  • Small batches generalize better but train slower; large batches need scaled-up learning rates.
  • Shuffle every epoch, stratify when classes are imbalanced, and augment only the training set.
Up next — 6.8 Regularization & Generalization. We’ve seen overfitting; now we fight it with weight decay, dropout, early stopping, and data augmentation.
Try it interactively

Tune epochs and batch size — watch the loss curve respond

Larger batches → smoother loss. Smaller batches → noisier but often faster generalisation. Slide both and watch the live training curve confirm the textbook.

Open Lab
Mini case study

Mini-batches, epochs & early stopping at planetary scale: DeepMind GraphCast

GraphCast (DeepMind, Nature 2023) forecasts global weather 10 days ahead in under a minute on a single TPU — beating the European Centre’s flagship HRES numerical model on the majority of variables. ECMWF deployed GraphCast in operational evaluation in 2024. The model is enormous (36.7 M parameters on a 0.25° mesh) but the engineering interest is the training schedule: a 4-week curriculum of growing mini-batches and lengthening rollouts, with early stopping on a held-out year.

0Model parameters
0Years ERA5 training data
0Variables beat HRES
0Inference time, 10-day forecast

You can’t train a global weather model in one pass — the network has to first learn the next-step Jacobian, then learn to chain its own predictions for 40 autoregressive 6-h steps. Naive long-rollout training collapses; naive short-rollout training never learns long-range dynamics. The schedule is the model.

“Curriculum + early stopping is what made GraphCast deployable.”

  • Stage 1 — train 1-step prediction with batch size 32, 300 epochs, learning rate 1e-3 warmed-up over 1 epoch.
  • Stage 2 — gradually extend the rollout length from 1 to 12 6-hour steps over 11 epochs, halving the learning rate at each step.
  • Stage 3 — fine-tune with the full 10-day rollout, batch size 4 (memory), LR 3e-7.
  • Early stopping on a held-out year by RMSE on Z500 (500 hPa geopotential) — the standard meteorological skill metric.
Held-out Z500 validation RMSE across the 3-stage curriculum (lower is better)

The validation curve flattens in stage 3 and starts to drift up — classic early-stopping trigger. GraphCast checkpoints the model at the validation minimum and stops.

  • Beats HRES on ~90% of variables and lead times — landmark independent validation by ECMWF.
  • 1-min inference per 10-day forecast vs ~hours of HPC time for the numerical model.
  • Operational deployment by ECMWF alongside their AIFS in-house model.
  • Mini-batch size is a memory–throughput trade-off. Smaller batches help on long-rollout fine-tunes; larger batches stabilise the early epochs.
  • Curriculum learning is real. Easy → hard schedules are the only way to train autoregressive long-horizon models.
  • Early stopping is non-negotiable — train loss keeps falling long after val loss starts climbing.