Skip to content
AI.info

How machines learn

Gradients, Batches, Epochs, and Learning Rate

Develop beginner-level intuition for gradients, update steps, mini-batches, epochs, learning rate, and the diagnostics used to tune them.

By the end you can

Analogy

Local direction, not a route to the global destination

You are on a foggy hillside with an instrument that estimates the local uphill direction. To descend, you step roughly the opposite way, measure again, and continue.

A gradient plays a similar role by describing local loss change around current parameters. Loss surfaces are stranger than a hillside: many dimensions, noisy batch estimates, flat regions, saddles, and coordinate scaling effects.

Which of those obstacles actually stalls a run is not folklore. Dauphin, Bengio and four colleagues put the question at the centre of a NeurIPS 2014 paper on saddle points in high-dimensional non-convex optimization. Their abstract states the case directly: “Here we argue, based on results from statistical physics, random matrix theory, neural network theory, and empirical evidence, that a deeper and more profound difficulty originates from the proliferation of saddle points, not local minima, especially in high dimensional problems of practical interest.” The saddles come surrounded by high-error plateaus. That is why a run can look stuck without being trapped.

A second group reached a compatible conclusion by a different route. Choromanska and LeCun, with three co-authors, argued from spin-glass theory in 2015 that the number of poor local minima falls off exponentially as the network grows. The fog on the hillside is real. The pit under it is mostly not.

What one gradient-based update means

The model predicts on a batch. The loss summarizes the error. Differentiation estimates how small parameter changes would affect that loss. The optimizer then combines this information with a learning rate, and possibly with memory from previous updates.

The parameters then move by a limited step. Repeating this procedure can reduce the training objective. No individual step guarantees a better validation result.

The optimizer in question is rarely anonymous in practice. Kingma and Ba published Adam in 2014, and the caption of Algorithm 1 hands the reader the numbers outright: “Good default settings for the tested machine learning problems are α = 0.001, β1 = 0.9, β2 = 0.999 and ϵ = 10−8.” The α is the learning rate. The two β values are the memory of previous updates. Mainstream tooling still ships exactly that: keras.optimizers.Adam defaults to learning_rate=0.001, beta_1=0.9, beta_2=0.999. A beginner's first script takes a step of 0.001 because a 2014 paper suggested it. Nothing about their problem was measured.

A gradient describes local sensitivity; the learning rate decides how strongly to act on it.

Visual

The vocabulary of iterative fitting

These terms describe different parts of the same process. The batch is the set of examples used to estimate one update. A step, or iteration, is one cycle that computes feedback and changes parameters. An epoch is enough steps to process approximately one full pass through the training set. The learning rate is a control on update magnitude, and it is often changed during training.

FigureHierarchy · 4 levels
  • Batch

    The examples used to estimate one update.

    • Step or iteration

      One cycle that computes feedback and changes parameters.

      • Epoch

        Enough steps to process approximately one full pass through the training set.

        • Learning rate

          A control on update magnitude, often changed during training.

Comparison

Batch size changes noise, memory, and throughput

Batch size is not simply a quality dial. A small batch uses fewer examples per update. It needs less memory per step, produces a noisier gradient estimate, and gives more updates per epoch. A large batch averages feedback over more examples. It smooths the estimate, demands more memory, uses parallel hardware efficiently — and may need a learning-rate adjustment. A full batch has low sampling noise and few updates per epoch, and is expensive enough to be rare in modern large-scale training.

That last caution on the large-batch side is not a vague warning. It has a name, a rule and a measured cost. In 2017 Facebook trained ResNet-50 on ImageNet with a minibatch of 8,192 on 256 GPUs, in one hour. Goyal and eight colleagues state the whole method in one line: “Linear Scaling Rule: When the minibatch size is multiplied by k, multiply the learning rate by k.” Moving from 64 to 8,192 examples per update means multiplying the learning rate by the same factor, with a gradual warmup over the first 5 epochs to survive the start.

The result: 23.74% ±0.09 top-1 validation error against a 23.60% ±0.12 small-minibatch baseline. A batch multiplied by 32, a learning rate multiplied by 32, and an accuracy gap inside the run-to-run error bars. Shallue and colleagues at Google Brain later restated that 64→8,192 result along with its limit: the same heuristic broke down for even larger batch sizes. The rule is real and it is bounded. That is a different sentence from “may need learning-rate adjustment”.

FigureComparison · 3 columns

Small batch

Uses fewer examples per update.

  • Lower memory per step
  • Noisier gradient estimate
  • More updates per epoch
  • May improve responsiveness to varied examples

Large batch

Averages feedback over more examples.

  • Smoother gradient estimate
  • Higher memory requirement
  • Can use parallel hardware efficiently
  • May need learning-rate adjustment

Full batch

Uses the entire training set for one update.

  • Low sampling noise
  • Expensive for large datasets
  • Few updates per epoch
  • Rare in modern large-scale training

Example

Three ways the step size shows up in curves

Optimization problems often reveal themselves before final evaluation. Two of the patterns below are not lore passed between practitioners. They are dated, published schedules with step counts attached.

  • Too small: loss declines very slowly, and a short budget may make a viable model look incapable.
  • Too large: loss oscillates, explodes, becomes non-finite, or repeatedly overshoots useful regions.
  • Reasonable initial rate: loss falls quickly enough while remaining stable — for most first scripts that is the 0.001 Kingma and Ba printed as Adam's default.
  • Late-stage schedule: a smaller rate can support finer adjustments after broad progress. Loshchilov and Hutter gave that decay an explicit curve in 2016, annealing the rate by a half-cosine within each run and then restarting it. Their abstract reports the outcome: “We empirically study its performance on the CIFAR-10 and CIFAR-100 datasets, where we demonstrate new state-of-the-art results at 3.14% and 16.21%, respectively.” It is now stock tooling rather than an idea. Keras's CosineDecay implements 0.5 * (1 + cos(pi * step / decay_steps)) and cites their paper by name.
  • Warm-up: some systems begin with smaller updates to avoid instability at the start. The original Transformer was one of them. Vaswani and seven co-authors described the schedule in 2017: “This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.” Xiong and colleagues later supplied the reason the ramp is needed at all. In the Post-LN design the gradients near the output layer are large at initialisation, and moving layer normalisation inside the residual block removes the need for warm-up entirely.

Key idea

An epoch does not have a universal meaning

One epoch over ten thousand examples and one epoch over ten billion examples represent radically different amounts of computation and parameter updates. Data augmentation and sampling can also make “one pass” ambiguous.

What a further pass is worth has been measured rather than argued. Muennighoff and co-authors ran 400 training runs in 2023, reaching up to 900 billion tokens and 9-billion-parameter models. Their abstract reports the finding: “We find that with constrained data for a fixed compute budget, training with up to 4 epochs of repeated data yields negligible changes to loss compared to having unique data.” Past that point the return on added compute decayed toward zero. Xue and four colleagues at the National University of Singapore studied repetition independently and found the overfitting it induces. So an epoch can be nearly free or nearly worthless. Which one it is depends on the data regime, not on the count.

Compare steps, examples processed, compute, wall-clock time, and validation behavior. Do not assume that epoch counts transfer between projects.

Epoch is a dataset-relative accounting unit, not a universal measure of learning.

Poor training fit has several possible causes

High training error can indicate insufficient capacity, weak features, noisy targets, a poorly aligned loss, or optimization that never found a good fit. Increasing model size without separating these causes can waste time.

A tiny-sample fit and a learning-rate sweep help distinguish implementation and optimization problems from representational limits. So do gradient checks and a simpler baseline.

The cheapest version of that sweep was published in 2015. Leslie Smith, at the US Naval Research Laboratory, called it the “LR range test”. It runs the model for a few epochs. During the run the learning rate rises linearly from a low value to a high one. Then it plots accuracy against rate. Read off the rate at which accuracy “starts to increase”, and the rate at which it “slows, becomes ragged, or starts to fall”. Those two numbers bracket the usable range. On CIFAR-10 with Caffe's stock architecture that gave him 0.001 and 0.006. One short run separates a model that looks incapable of learning from a model whose step size was simply wrong. It does that before anyone buys more parameters.

Steps

Run a disciplined optimization probe

A probe should produce a diagnosis. It should not produce a pile of unrelated runs. Fix the evidence — one dataset version, split, model and metric. Choose a rate range spanning several orders of magnitude rather than tiny cosmetic differences. Watch the early curves, recording loss, gradient or update norms, and numerical warnings. Compare equal budgets, meaning the same steps or examples processed. Then confirm generalization with validation evidence rather than training speed alone.

The last two are the steps people skip, and there is a large piece of evidence about what skipping them costs. One Google Brain study measured 71,638,836 loss values across 168,160 trained models and 454 workload/batch-size combinations. Shallue and five co-authors published it in 2019, and they say what all that measurement was for: “Specifically, we show that assumptions about computational budgets and the procedures for selecting metaparameters at different batch sizes can explain many of the disagreements in the literature.”

Underneath the disagreements they found one universal shape. Raising the batch size first cuts the required steps proportionally, then hits diminishing returns, then buys nothing at all. The turning point is set by the workload rather than by any fixed number. OpenAI researchers arrived at the same boundary from another direction in 2018, predicting the largest useful batch size from a measurable gradient noise scale. Holding the budget and the tuning procedure fixed is therefore not fastidiousness. It is the difference between producing a result and producing a disagreement.

FigureProcess · 5 steps
  1. 1. Fix the evidence

    Use one dataset version, split, model, and metric.

  2. 2. Choose a rate range

    Test several orders of magnitude rather than tiny cosmetic differences.

  3. 3. Watch early curves

    Record loss, gradient or update norms, and numerical warnings.

  4. 4. Compare equal budgets

    Use the same steps or examples processed for fair comparison.

  5. 5. Confirm generalization

    Select promising settings with validation evidence, not training speed alone.

Key idea

When training produces NaN or infinity

Non-finite values often point to extreme inputs, unstable calculations, excessive learning rate, invalid logarithms, division by tiny numbers, or exploding gradients. Silently replacing them can hide the root cause.

The boundary that produces them is written down. IEEE 754 half precision (binary16) carries 11 bits of significand. It represents normalized values only from 2⁻¹⁴ up to 65,504, with subnormals reaching 2⁻²⁴ — a total dynamic range of 40 powers of two. The GNU Compiler Collection manual states the same limits: the format “can represent normalized values in the range of 2^{-14} to 65504” with “11 bits of significand precision”. Anything above the top of that range becomes an infinity. Anything below the bottom becomes a zero. Both then propagate.

NVIDIA's own guide shows the cost on a real network. Profiling the activation gradients of the Multibox SSD detector, “Train With Mixed Precision” reports: “When converted to FP16, 31% of these values become zeros, leaving only 5.3% as nonzeros which for this network lead to divergence during training.” Nearly a third of the signal did not overflow or blow up. It quietly fell off the bottom of the number format.

Capture the first failing batch. Inspect ranges and operations, and reduce the problem to a reproducible case. Numerical stability is part of correctness, not merely performance tuning.

Case

Half precision: gradients that became zero, and runs rewound

Two mechanisms account for a large share of these failures, and both are documented. In IEEE half precision “any value whose magnitude is smaller than 2⁻²⁴ becomes zero in FP16”. Micikevicius and colleagues at NVIDIA and Baidu reported that at ICLR 2018. About 5 % of weight-gradient values in the network they profiled fell below that line. One detector network “diverges when gradients are not scaled, but scaling them by a factor of 8 (increasing the exponents by 3) is sufficient to match the accuracy achieved with FP32 training”.

The second mechanism turned up at production scale. Training OPT-175B on 992 80GB A100 GPUs, Meta's team recorded what happened when the loss diverged. They recovered by “lowering the learning rate and restarting from an earlier checkpoint”. Resetting the dynamic loss scalar “helped recover some but not all divergences”. Divergence, in other words, was handled by rewinding rather than by fixing the arithmetic.

Optimization is a means, not the definition of learning quality

A perfectly optimized objective on biased, leaked, or outdated data can produce a poor system. Conversely, modest optimization may be sufficient. That is the case when the signal is strong and the baseline is weak.

Later training paths will cover optimizer families and schedules in detail. At this stage, remember that optimization controls how a model fits the specified problem. It does not validate the problem itself.

The gap between the two was made concrete at ICLR 2017. Keskar, Nocedal and three co-authors moved from the customary 32 to 512 examples per update to a much larger batch. They observed “a degradation in the quality of the model, as measured by its ability to generalize”. They presented evidence that large-batch training converges on sharp minimisers of the training and testing functions, while small-batch training settles into flat ones. The training objective was not the thing that failed. Both regimes optimised it. Only one of them produced a model worth shipping.

Key takeaways