Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsOptimization

Stochastic and mini-batch gradient descent

P1.F430 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Real training sets have millions or billions of examples, so computing the slope from all of them at every step is too slow. Estimating it from a small random batch makes each step far cheaper, and the price is noise that you can measure and control.

  • Every training loop you will write loops over batches of data and takes one optimizer step per batch. (P2.7: The PyTorch training loop)
  • Adam and the other optimizers used for most modern networks are built on mini-batch gradients: they take the noisy batch gradient and add momentum or a separate step size for each parameter. (P4.13: Optimizers)
  • Large language models are trained with very large batches that are split across many devices, and the batch size and the learning rate have to be chosen together. (P10.B6: Distributed training, coming soon)
  • The learning-rate schedule, which usually shrinks the step size as training goes on, has several reasons. One main one is that a constant step leaves SGD wobbling around the minimum (warmup and other schedules have further reasons). (P4.14: Learning-rate schedules)

Before this: Gradient descent, Expectation and variance, Law of large numbers and the Central Limit Theorem

After this lesson you can

  • Write the mini-batch update rule and say what B = 1, B between 1 and N, and B = N are called
  • Show on a small example that the average of the mini-batch gradients equals the full gradient, and say what unbiased means
  • Say how the noise of a mini-batch gradient changes with the batch size, and what it costs
  • Explain why constant-step SGD hovers near the minimum instead of settling, and two ways to shrink the hovering
  • Count steps, epochs and examples processed for a given N, B and number of epochs
  • Name the main trade-offs of small and large batches, and what is known and not known about them

To learn what a whole country thinks about a new law, you do not ask all 40 million people. You ask a random 1,000. The answer is a little off, but it costs almost nothing, and if you ask another random 1,000 tomorrow, the two errors tend to cancel out.

Training a model faces the same choice. The slope that gradient descent needs is an average over all the training examples. We can compute it exactly, or estimate it from a small random sample and take a step right away. This lesson is about the second choice: stochastic gradient descent, the version that trains nearly every neural network.

The cost of an exact step

P1.F1 said that training means minimizing the average loss over the data. With NN examples, and Li(θ)L_i(\boldsymbol{\theta}) the loss on example ii,

L(θ)=1N∑i=1NLi(θ),\mathcal{L}(\boldsymbol{\theta}) = \frac{1}{N}\sum_{i=1}^{N} L_i(\boldsymbol{\theta}), ∇L(θ)=1N∑i=1N∇Li(θ).\nabla\mathcal{L}(\boldsymbol{\theta}) = \frac{1}{N}\sum_{i=1}^{N} \nabla L_i(\boldsymbol{\theta}).

The second equation holds because the gradient of a sum is the sum of the gradients (P1.C5). So one step of full-batch gradient descent (P1.F3) needs the gradient of every example. With N=1,000,000N = 1{,}000{,}000 examples, one step means a million per-example gradients, and training takes thousands of steps. That is billions of gradient computations, to move the parameters a tiny distance each time.

The idea: estimate the average from a few examples

Pick a random batch of BB examples, average only their gradients, and step:

θ←θ−η g^,\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\,\hat{\mathbf{g}}, g^=1B∑i ∈ batch∇Li(θ).\hat{\mathbf{g}} = \frac{1}{B}\sum_{i\,\in\,\text{batch}} \nabla L_i(\boldsymbol{\theta}).

The only change from P1.F3 is that the exact gradient is replaced by an estimate g^\hat{\mathbf{g}}. The batch size gives the three names:

  • B=NB = N: full-batch gradient descent. No randomness.
  • B=1B = 1: stochastic gradient descent (SGD) in the strict sense: one random example per step.
  • 1<B<N1 < B < N: mini-batch gradient descent. Typical values are 32 to a few thousand.

In deep learning, “SGD” almost always means the mini-batch version. In PyTorch, torch.optim.SGD just applies the update rule to whatever gradient it is given. The batch size is set by the data loader, not by the optimizer.

Averaging a random sample to estimate a quantity is the Monte Carlo idea of P1.D9: the batch gradient is a Monte Carlo estimate of the full gradient.

A small example you can check by hand

Take the model y^=wx+b\hat{y} = wx + b and the three data points (1,2),(2,3),(3,7)(1, 2), (2, 3), (3, 7) from P0.2, and stand at (w,b)=(1,0)(w, b) = (1, 0). The errors wx+b−ywx + b - y are −1,−1,−4-1, -1, -4, and the loss is L=(1+1+16)/3=6\mathcal{L} = (1 + 1 + 16)/3 = 6. The gradient of one example is (2ex, 2e)(2ex,\ 2e) for error ee (P1.C4), so the three per-example gradients are:

  • example (1,2)(1,2): (−2,−2)(-2, -2)
  • example (2,3)(2,3): (−4,−2)(-4, -2)
  • example (3,7)(3,7): (−24,−8)(-24, -8)

Their average is the full gradient, (−10,−4)(-10, -4), the same numbers as in P1.C5. Now use batches of B=2B = 2. There are only three possible pairs, and each gives a different estimate:

  • examples 1 and 2: (−3,−2)(-3, -2)
  • examples 1 and 3: (−13,−5)(-13, -5)
  • examples 2 and 3: (−14,−5)(-14, -5)

No single estimate is right. But their average is (−30/3, −12/3)=(−10,−4)(-30/3,\ -12/3) = (-10, -4): exactly the full gradient. That is what it means for the estimate to be unbiased: if you could average over all the batches you might draw, you would get the true gradient. Each estimate points roughly the right way (all three have negative entries, like the true gradient), but with different lengths.

One step with η=0.1\eta = 0.1 shows the noise. The full gradient moves (1,0)(1, 0) to (2.0,0.4)(2.0, 0.4) and lowers the loss from 6 to 0.83. The pair (1, 2) moves it to (1.3,0.2)(1.3, 0.2) and the loss becomes 2.9, the pair (1, 3) gives loss 1.74, and the pair (2, 3) gives 2.20. A single example can mislead badly: example 3 alone moves to (3.4,0.8)(3.4, 0.8), where the loss is 14, higher than before. The steps are noisy, and an individual step can go uphill, but the average direction is the true one.

The code cell below reproduces all of this.

Try it: per-example gradients, pairs and their average

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

How good is the estimate?

Three facts make mini-batches work. Write σ2\sigma^2 for the variance of one example’s gradient (one coordinate of it) across the data (P1.D4).

1. Unbiased. If every example is equally likely to be in the batch, then E[g^]=∇L\mathbb{E}[\hat{\mathbf{g}}] = \nabla\mathcal{L}, by linearity of expectation (P1.D4). The example above is this fact in miniature. It needs the sampling to be uniform. If the data file is sorted (all cats, then all dogs) and you cut it into consecutive batches, the batches are not representative and the estimate is biased. That is one reason to shuffle (P1.D9, P1.D5).

2. The noise shrinks like 1/B1/\sqrt{B}. If the BB examples are drawn independently, the batch average has variance σ2/B\sigma^2/B, so its spread is σ/B\sigma/\sqrt{B} (P1.D4, P1.D8). Compared with one example:

  • B=1B = 1: noise σ\sigma, the full single-example noise
  • B=4B = 4: half of it
  • B=16B = 16: one quarter
  • B=64B = 64: one eighth
  • B=256B = 256: one sixteenth

To halve the noise you need four times the batch. The independence condition holds exactly when drawing with replacement, and approximately when NN is much larger than BB. With the three-point example and B=2B = 2, the spread of the ww-part of the estimate drops from σ=9.93\sigma = 9.93 for a single example to 7.027.02 with replacement. The three pairs above have 4.974.97 instead, because drawing without replacement is smarter: the two examples cannot repeat. The variance is multiplied by (N−B)/(N−1)(N - B)/(N - 1), which is 0.50.5 here. When BB is small next to NN, that factor is close to 1 and the simple formula is fine. At B=NB = N it is 00: no noise at all.

3. A step costs about BB gradient computations. So noise falls with B\sqrt{B} while cost grows with BB: the first few examples in a batch buy a lot of accuracy, and later ones buy less and less.

Epochs, iterations and shuffling

One iteration (or step) uses one batch. One epoch is one pass through the whole data set. With NN examples and batch size BB:

steps per epoch=NB.\text{steps per epoch} = \frac{N}{B}.

The usual recipe, used by PyTorch’s data loader when you ask it to shuffle, is to put the examples in a new random order at the start of every epoch and cut that order into consecutive batches. Every example is used exactly once per epoch. This is sampling without replacement within an epoch (P1.D9), and it is often a little better than drawing independently. If NN is not a multiple of BB, the last batch is smaller. For N=1,000,000N = 1{,}000{,}000 and B=256B = 256 there are 3,906 full batches and one batch of 64; many programs keep it, others drop it.

For the data in the widget below, N=32N = 32. With B=4B = 4 one epoch is 8 steps, and 20 epochs are 160 steps. With B=1B = 1 the same 20 epochs are 640 steps, and with B=32B = 32 they are 20.

Full-batch against SGD

The widget fits a line y^=wx+b\hat{y} = wx + b to 32 made-up points. The contour map is the average loss over the two parameters ww and bb (each oval is a set of points with the same loss, as in P1.F3). The diamond is the exact minimum. Both methods start from the same ring and are given the same number of examples to process, so the cost is equal: full-batch spends all 32 examples on each step, SGD spends BB. The comparison is fair for equal η\eta, but full-batch could use a larger one (it is stable up to about 0.1640.164). With 20 steps, η=0.1\eta = 0.1 ends 1.2681.268 from the minimum and η=0.15\eta = 0.15 ends 0.8860.886 away, still far from it. The distance is dominated by the flat valley direction, so the loss comparison below is the better yardstick.

Batch size B:
01230123wbmin
full-batch (one dot per step) SGD (one kink per step) exact minimum shared start (drag it)

Same budget, 640 examples: full-batch made 20 steps and ended 1.682 from the minimum; SGD (B = 4) made 160 steps and ended 0.14 away. SGD is closer to the minimum for this seed. In SGD's last epoch its distance stayed between 0.036 and 0.205. Once SGD has arrived, a constant η keeps it wobbling around the minimum instead of settling on it.

Show:
Loss chart against:

Excess loss 𝓛 − 𝓛min on all 32 examples, log scale (lower is better)

0.0010.010.11101000200400600examples processed

Some points are below 0.001 (the bottom of the chart), so they are drawn on the bottom line.

Full-batch gradient descent, 32 examples per step
steps = 20
examples processed = 640
final loss 𝓛 = 1.015
distance to the minimum = 1.682
SGD, B = 4 per step (shuffle every epoch, then cut into batches)
steps = 160
examples processed = 640
final loss 𝓛 = 0.628
distance to the minimum = 0.14
The exact minimum is at (w, b) = (1.614, 0.82), where 𝓛min = 0.53. The largest curvature is λmax = 12.2.
Seeds 1 to 20, same settings: SGD's final distance to the minimum has median 0.102, from 0.048 to 0.23.

The data are 32 made-up points; the model is ŷ = w·x + b with squared error. Pink SGD and blue full-batch start at the same point and are given the same number of examples to process.

Blue: full-batch gradient descent, one dot per step. Pink: mini-batch SGD with the batch size you choose, one kink per step. The chart under the map plots the loss on all 32 examples. Try B = 1, then B = 32, then the step-size decay box.

Things to try. Each of these was checked by running the widget’s own code:

  • The default. B=4B = 4, η=0.06\eta = 0.06, 20 epochs, seed 1. Full-batch has made 20 steps and is still 1.6821.682 from the minimum. SGD has made 160 steps and ended 0.1400.140 away (over seeds 1 to 20 the median is 0.1020.102). The loss chart shows why: measured in examples processed, SGD’s curve drops much faster at first. To get the loss within 0.50.5 of its minimum, full-batch needs 640 examples (20 epochs) and SGD with B=4B = 4 needs 88.
  • B=32B = 32 (all). The two paths are identical. With the whole data set in every batch, SGD is full-batch gradient descent.
  • B=1B = 1. The pink path is much more jagged. With seed 1 and η=0.06\eta = 0.06 it ends 0.4210.421 from the minimum. Move the seed slider: the final distance changes with the seed, and the readout summarizes seeds 1 to 20 (median 0.2680.268, from 0.0390.039 to 0.6030.603). A single run of a random method is one draw, so report the spread over several seeds (P1.D13).
  • A big step size. Set η=0.15\eta = 0.15. On this loss, full-batch gradient descent is stable below 2/λmax⁡=0.1642/\lambda_{\max} = 0.164, so with B=32B = 32 it converges. With B=1B = 1 every one of the 20 seeds diverges. Noise lets SGD blow up at a smaller η\eta than full-batch, here by a wide margin.
  • Decay the step size. Set B=1B = 1, η=0.06\eta = 0.06, 40 epochs. With a constant η\eta the final distance is 0.4220.422. Tick the decay box and it is 0.0140.014.
  • Draw with replacement. Each batch is now BB independent random draws. With B=32B = 32 this is no longer full-batch (some examples repeat and others are missed), so the paths differ.

Why SGD hovers instead of settling

At the exact minimum of the full loss, the full gradient is zero. But the batch gradients are not: each example’s own loss has its own slope there, and a batch sees only some of them. So SGD with a constant step size keeps being kicked, and it hovers in a noise ball around the minimum instead of settling at it. The widget shows it: after SGD arrives, the pink path keeps wandering.

Two things shrink the ball:

  • A smaller η\eta. Smaller kicks.
  • A larger BB. Less noise in each kick.

For independent draws and a small η\eta, the typical squared distance from the minimum is proportional to η/B\eta / B. On this data set with replacement, the squared distance divided by η/B\eta/B stayed between 0.840.84 and 1.281.28 across η\eta from 0.0050.005 to 0.040.04 and BB from 1 to 16 (8 seeds each), and a calculation from the gradients at the minimum predicts 0.860.86 for small η\eta. With shuffled epochs, which the widget uses by default, the ball is usually smaller still at the same η\eta and BB, so use the widget for the direction of the effect, not for this exact law. Full-batch gradient descent has no such ball, which is why it keeps improving if you run it long enough. After 200 epochs (longer than the widget allows) its loss is 0.000270.00027 above the minimum, while SGD with B=4B = 4 and η=0.06\eta = 0.06 sits about 0.060.06 above it on average (seed 1: 0.0540.054; across 20 seeds 0.0520.052 to 0.0730.073, each averaged over the last 50 of 200 epochs, though single steps are sometimes much closer and sometimes much worse).

Go deeper Where the noise-ball law comes from

Take one parameter, a bowl with curvature λ\lambda, and noisy slopes whose noise has variance σ2/B\sigma^2/B and is independent from step to step. The distance dd from the minimum then follows dt+1=(1−ηλ) dt−η ξtd_{t+1} = (1 - \eta\lambda)\,d_t - \eta\,\xi_t, where ξt\xi_t is the noise. Once the process settles, its variance VV satisfies V=(1−ηλ)2V+η2σ2/BV = (1-\eta\lambda)^2 V + \eta^2\sigma^2/B, so

V=η σ2/Bλ (2−ηλ),V = \frac{\eta\,\sigma^2/B}{\lambda\,(2 - \eta\lambda)},

which for small η\eta is about

V≈η σ22λB.V \approx \frac{\eta\,\sigma^2}{2\lambda B}.

The variance is proportional to η/B\eta/B, which is the law above. With many parameters the same happens along every direction of the bowl, with its own λ\lambda. This is for independent noise of fixed size. Real losses have noise that depends on where you are, and shuffling makes the noise within an epoch dependent, so treat η/B\eta/B as a guide.

Letting SGD settle: decaying the step size

If the ball size is proportional to η\eta, shrink η\eta as training goes on. Early on, large steps make fast progress; later, small steps shrink the wobble. That is a learning-rate schedule. The widget’s decay option (applied to both methods) uses ηt=η/(1+e/4)\eta_t = \eta/(1 + e/4), where ee is the number of epochs so far: at epoch 12 the step is η/4\eta/4.

Shrinking too fast has a cost. If the steps become tiny before SGD has arrived, it makes slow progress and may not arrive by the end of training. With B=4B = 4, η=0.06\eta = 0.06 and 40 epochs, the decayed run ends 0.5070.507 from the minimum while the constant-step run ends 0.0790.079 away. Choosing a schedule is a real design decision, treated in P4.14.

Go deeper The Robbins–Monro conditions

In 1951 Robbins and Monro studied stochastic approximation and gave conditions on the step sizes ηt\eta_t under which noisy-gradient iterations settle on the right answer:

∑t=1∞ηt=∞,∑t=1∞ηt2<∞.\sum_{t=1}^{\infty}\eta_t = \infty, \qquad \sum_{t=1}^{\infty}\eta_t^2 < \infty.

The first says the steps are big enough in total to reach any distance, so the method cannot stall too early. The second says the noise they inject adds up to a finite amount, so the wobble dies out. A step of size ηt=c/t\eta_t = c/t satisfies both. Under these conditions and further assumptions on the loss (convex, smooth, noise of bounded variance), the iterates converge to the minimum. Deep-learning practice rarely follows these conditions exactly. Schedules that decay to a small value, not to zero, are common.

The trade-offs of batch size

Small batches. Each step is cheap and noisy, and you take many steps per epoch. Memory use is low. The noise can be a nuisance (a bigger wobble, a smaller safe η\eta) and can also be useful (below).

Large batches. Each step is cleaner and costs more. You take fewer steps per epoch, and doubling BB does not double the progress per step once the noise is already small: remember the 1/B1/\sqrt{B} diminishing returns.

Wall-clock time is not the number of gradient computations. A GPU does many examples at once, so a step on 64 examples often takes about as long as a step on 8, because the hardware is not yet full. Past some size the time per step grows roughly in proportion to BB. That is why moderate batches are often the cheapest way to use the hardware, and why the best batch size depends on the machine.

Memory. Backpropagation (P4.8) stores values for every example in the batch, so memory grows with BB. A batch that does not fit simply cannot be used, and that is often what sets the upper limit.

Generalization. Some well-known experiments found that very large batches reached a worse test accuracy than small ones, and one explanation proposed was that the noise of small batches steers training to flatter minima (Keskar and others, 2016). Later work (Goyal and others, 2017) showed that, on ImageNet, much of the gap disappears when the learning rate is scaled with the batch size and increased gradually at the start. So treat “small batches generalize better” as an observation that held in some settings, not as a rule. P4.24 returns to generalization.

Escaping bad spots. The noise can kick the ball off a saddle (P1.F2) or out of a shallow valley, where exact gradient descent could sit. This tends to help. It is not guaranteed, and the noise in real mini-batches is not the same in every direction. The last code cell on this page shows the effect with noise added by hand.

Habits. Batch sizes are usually powers of two (32, 64, 128, and so on). That is a convention that fits memory and hardware, not a mathematical requirement. Batch size and step size interact: a larger batch has less noise, so it tolerates a larger η\eta before the wobble or divergence gets bad. A common heuristic, stated by Goyal and others for one family of image models, is to multiply η\eta by kk when the batch is multiplied by kk, with a gradual start (warmup). It is a rule of thumb that breaks down for very large batches, and other optimizers may need other rules. It fits with the η/B\eta/B law above: keeping η/B\eta/B fixed keeps the noise ball the same size. P4.14 and P4.23 cover choosing both in practice.

Go deeper Gradient accumulation and data parallelism

If the batch you want does not fit in memory, split it into mm smaller pieces (micro-batches), compute the gradient of each, and add them up before taking one step. Dividing each piece’s loss by mm makes the sum equal the average over the full batch. With equal pieces the result matches the big-batch gradient up to rounding; with unequal pieces you must weight by size, or the result is slightly off. Layers whose output depends on the whole batch, such as batch normalization (P4.19), see only the micro-batch, so the match is not exact for them.

for k, (xb, yb) in enumerate(loader):
    loss = loss_fn(model(xb), yb) / 4      # 4 micro-batches per step
    loss.backward()                         # gradients add up in .grad
    if (k + 1) % 4 == 0:
        opt.step()
        opt.zero_grad()

Data parallelism uses the same fact across machines. A global batch is split across devices, each computes the gradient of its share, and the shares are averaged before the update. The result is the gradient of the whole batch. Very large language models use global batches of millions of tokens; the GPT-3 paper lists 3.2 million tokens for its largest model. How the devices talk to each other is the subject of P10.B6.

Momentum (P1.F5) comes from the same noise problem: it averages recent gradients so the zig-zag cancels. Adam (P4.13) also builds on mini-batch gradients.

The recipe in one place

Intuition

You are in the fog from P1.F3 again, but now your slope meter is a bit shaky. Instead of reading the slope from a map of the whole mountain (slow), you glance at a few rocks near you (fast) and step downhill by what they say. Each glance is off a little, but the errors point in random directions, so over many steps they cancel and you still head down. Near the bottom the shaky meter keeps you stumbling around the lowest point rather than standing on it. Looking at more rocks, or taking smaller steps, steadies you.

Math

Let gi=∇Li(θ)\mathbf{g}_i = \nabla L_i(\boldsymbol{\theta}) and gˉ=1N∑igi\bar{\mathbf{g}} = \frac{1}{N}\sum_i \mathbf{g}_i. For a batch of BB indices drawn uniformly,

g^=1B∑j=1BgIj,E[g^]=gˉ.\hat{\mathbf{g}} = \frac{1}{B}\sum_{j=1}^{B}\mathbf{g}_{I_j}, \qquad \mathbb{E}[\hat{\mathbf{g}}] = \bar{\mathbf{g}}.

For independent draws, each coordinate of g^\hat{\mathbf{g}} has variance σ2/B\sigma^2/B with σ2\sigma^2 the variance of that coordinate of gi\mathbf{g}_i over the data. Without replacement the variance is multiplied by (N−B)/(N−1)(N-B)/(N-1). The update is θt+1=θt−ηtg^t\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta_t\hat{\mathbf{g}}_t. Steps per epoch are N/BN/B. With a schedule, Robbins–Monro asks for ∑tηt=∞\sum_t\eta_t = \infty and ∑tηt2<∞\sum_t\eta_t^2 < \infty.

Code

# the standard PyTorch loop (P2.7): one optimizer step per batch
loader = torch.utils.data.DataLoader(data, batch_size=64, shuffle=True)
opt = torch.optim.SGD(model.parameters(), lr=0.05)

for epoch in range(20):
    for xb, yb in loader:               # a new random order each epoch
        loss = loss_fn(model(xb), yb)   # loss on this batch
        opt.zero_grad()
        loss.backward()                 # gradient of the batch loss
        opt.step()                      # theta <- theta - lr * gradient

The batch size lives in DataLoader. opt.step() just uses whatever gradient the batch left in .grad.

Try it in code

The first cell runs full-batch gradient descent and mini-batch SGD on the same 32 points as the widget. It uses NumPy’s random numbers, so its numbers are not the widget’s, but the pattern is the same: SGD processes the same 640 examples in more, smaller steps.

Try it: full batch against mini-batches

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The second cell shows noise acting on a saddle (P1.F2). On f(x,y)=x2−y2f(x, y) = x^2 - y^2, exact gradient descent that starts at (1,0)(1, 0) stays on the line y=0y = 0 and slides into the saddle at the origin. Here we add a small random number to every gradient by hand, standing in for the noise of mini-batches.

Try it: noise pushes the ball off a saddle

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

With noise, yy grows without limit: x2−y2x^2 - y^2 has no minimum, so the ball runs away downhill and does not find a lower valley. A real loss has other terms that bend it back up, so this shows only that noise leaves the saddle.

Misconceptions

Check your understanding

  1. You raise the batch size from 64 to 256, drawing examples independently. How does the noise of the batch gradient change?

  2. What does it mean that the mini-batch gradient is unbiased?

  3. SGD with a constant step size hovers around the minimum. Which change does NOT make the hovering smaller?

  4. A data set has N = 1,000 examples. You train for 10 epochs with batch size 50. How many parameter updates happen?

  5. In the widget you pick B = 32 (all) with “Draw with replacement” unticked. How does SGD compare with full-batch gradient descent?

Exercises

  1. With the three-point example at (w,b)=(1,0)(w, b) = (1, 0), find the mini-batch gradient for the pair of examples (2,3)(2,3) and (3,7)(3,7).
    Show answerThe average of (−4,−2)(-4,-2) and (−24,−8)(-24,-8) is (−14,−5)(-14, -5).
  2. A data set has N=50,000N = 50{,}000 examples and you use B=100B = 100. How many steps are in one epoch, and how many in 30 epochs?
    Show answer50,000/100=50050{,}000/100 = 500 steps per epoch, so 30×500=15,00030 \times 500 = 15{,}000 steps.
  3. A single example’s gradient has noise (spread) 8. What is the spread of a batch average for B=16B = 16 and for B=64B = 64, with independent draws?
    Show answer8/16=28/\sqrt{16} = 2 and 8/64=18/\sqrt{64} = 1. Quadrupling the batch halved the noise.
  4. With the decay rule η/(1+e/4)\eta/(1 + e/4) and a starting η=0.06\eta = 0.06, what is the step size after 12 epochs?
    Show answer0.06/(1+3)=0.0150.06/(1 + 3) = 0.015.
  5. You want an effective batch of 256 but only 64 examples fit in memory. Describe a way to do it, and say what to divide each loss by.
    Show answerRun 4 micro-batches of 64, let their gradients add up, and take one optimizer step. Divide each micro-batch loss by 4 so the sum is the average over 256.
  6. In the widget, set B to 1, then to 32, with η=0.15\eta = 0.15. What do you see, and what does it say about step size and noise?
    Show answerWith B=32B = 32 the step is below the full-batch limit of 0.1640.164, so it converges. With B=1B = 1 the noisy steps make it diverge. Noise lowers the largest safe step size, so small batches need smaller η\eta.

Next: P1.F5 adds momentum, which averages recent gradients to smooth out noise like this, and adaptive steps. P1.F6 uses curvature to pick better steps, and P4.14 returns to learning-rate schedules and batch-size rules in practice.

Key takeaways

  • The loss is an average over N examples, so its gradient is the average of N per-example gradients. A full-batch step needs all N of them.
  • Mini-batch SGD estimates that average from B random examples: θ ← θ − η · (average gradient of the batch). B = 1 is stochastic gradient descent, B = N is full-batch, and in between is mini-batch.
  • With uniform random sampling the batch gradient is unbiased: its average over all possible batches is the full gradient. Its noise shrinks like 1/√B when the examples are drawn independently, so four times the batch halves the noise and quadruples the cost of a step.
  • An epoch is one pass through the data, N/B steps. Shuffling each epoch cuts the data into batches without replacement.
  • With a constant step size, SGD does not settle on the minimum. It hovers in a noise ball that shrinks with a smaller η or a larger B. Shrinking η over time (a schedule) lets it settle.
  • Small batches give many cheap, noisy steps; large batches give fewer, cleaner, more expensive steps. Which is faster on the clock depends on the hardware.
  • Batch size and learning rate interact: changing one usually means retuning the other. Rules such as scaling η in proportion to B are rules of thumb, not laws.
Found a mistake? Tell us