

The main chapter explained how to update parameters and why minimizing training loss is not the whole task. We now ask a more detailed question: what determines how quickly an optimizer approaches a solution, and which solution do we keep? A learning rate can be stable but painfully slow. A stochastic gradient can be correct on average but still introduce substantial noise. A penalty can make a numerical problem easier while changing the model we fit.
This page is optional reading for students who want to follow those connections mathematically. Each section develops an idea, then offers an exercise with a worked solution. You can solve the exercises on paper; the Python figures provide additional checks. No neural-network knowledge is required.
For a focused second pass after the main chapter, follow the Taylor and momentum argument, the Adam counterexamples, and the batch-size/MSE experiment. For a 30-minute discussion, choose one proof, one Adam example, and the batch-size experiment; the full optional page contains more than fits into one session. The scalar proofs require Taylor’s theorem with Lagrange remainder; the final matrix extension additionally uses covariance and the trace of a matrix.
We build on the least-squares derivation in chapter 1 and the curvature discussion in chapter 2. Recall that the gradient contains first partial derivatives, while the Hessian contains second partial derivatives. For a positive-definite quadratic, the Hessian’s largest-to-smallest eigenvalue ratio is its condition number. The examples below begin with diagonal matrices, so the diagonal entries already give those eigenvalues; you need not calculate eigenvectors to follow them.
Our squared-loss convention is half mean squared error. An L2 penalty is \(\lambda\|w\|^2\), so its gradient is \(2\lambda w\). We keep that factor of two throughout. The last two sections use centered data with no intercept among the penalized parameters; we explain how this relates to fitting an unpenalized intercept.
Knowing that a method converges does not tell us whether it will make useful progress within our budget. Consider
\[L(u,v)=\frac12(au^2+bv^2),\qquad 0<a\leq b.\]
The minimum is at the origin. Its gradient is \((au,bv)\), so gradient descent separates into two scalar updates:
\[u_{t+1}=(1-\eta a)u_t,\qquad v_{t+1}=(1-\eta b)v_t.\]
Each step multiplies a coordinate by the same factor. Applying the update repeatedly therefore gives
\[u_t=(1-\eta a)^t u_0,\qquad v_t=(1-\eta b)^t v_0.\]
This is more informative than saying that a narrow valley slows learning: it tells us exactly how much error remains after any number of updates. Both coordinates converge from arbitrary starting points when both multipliers have magnitude below one. Since \(b\) is the larger curvature, the shared condition is \(0<\eta<2/b\).
Take \(a=1\), \(b=20\), and \(\eta=0.05\). Then \(u_t=0.95^t u_0\), whereas the first update sets \(v\) to zero because \(1-0.05(20)=0\). The steep direction is solved immediately, but the shallow one retains 95% of its error on each step. To reduce that remaining error to at most one tenth of its initial magnitude, we need
\[0.95^t\leq0.1 \quad\Longrightarrow\quad t\log(0.95)\leq\log(0.1) \quad\Longrightarrow\quad t\geq\frac{\log(0.1)}{\log(0.95)}\approx44.89.\]
Dividing reverses the inequality because \(\log(0.95)<0\). Thus 45 updates are needed. Notice that this is a statement about parameter error. Once only \(u\) remains, loss is proportional to \(u^2\), so a tenfold error reduction gives a hundredfold loss reduction.
Define \(\rho=\max(|1-\eta a|,|1-\eta b|)\). Then the Euclidean error satisfies \(\|(u_t,v_t)\|\leq\rho^t\|(u_0,v_0)\|\). Among constant scalar learning rates, the best worst-case factor is obtained by balancing the two extreme factors with opposite signs:
\[1-\eta a=-(1-\eta b) \quad\Longrightarrow\quad \eta^*=\frac{2}{a+b}.\]
The resulting factor is
\[\rho^*=\frac{b-a}{b+a}=\frac{\kappa-1}{\kappa+1},\qquad \kappa=b/a.\]
As the condition number grows, this factor approaches one: each step removes less of the worst-case error. This result concerns a fixed positive-definite quadratic and a constant scalar step. It is not a universal best learning rate for arbitrary models or a particular starting point. It gives a precise version of the conditioning argument from chapter 2 (Boyd and Vandenberghe 2004).


1.1 \(\eta^*=2/(1+9)=0.2\). The factors are \(1-0.2=0.8\) and \(1-0.2(9)=-0.8\), so \(\rho^*=0.8\). Thus \((u_1,v_1)=(0.8,-0.8)\) and \((u_2,v_2)=(0.64,0.64)\).
1.2 We need \(0.8^t\leq0.1\), giving \(t\geq10.32\). Since updates are integers, 11 suffice. Here both coordinates have the same absolute multiplier, so the bound is attained for every nonzero starting point.
1.3 Each squared coordinate is multiplied by \(0.8^{2t}\), so \(L_t/L_0=0.64^t\). A 90% loss reduction needs \(t\geq\log(0.1)/\log(0.64)\approx5.16\), hence 6 updates. Parameter error and loss have different reduction factors.
Read further: Boyd and Vandenberghe, Convex Optimization, §9.3, for gradient descent and its convergence analysis. The book is freely available from the authors.
Ordinary gradient descent uses only the current parameter value to determine the next one. Momentum carries an additional state. We can see what that memory does without introducing a new model: take \(L(w)=cw^2/2\), with \(c>0\), and use the main chapter’s recurrence
\[v_{t+1}=\beta v_t+cw_t,\qquad w_{t+1}=w_t-\eta v_{t+1}.\]
For \(t\geq1\), the previous update implies \(\eta v_t=w_{t-1}-w_t\). Substitute this into the new update:
\[\begin{aligned} w_{t+1}&=w_t-\eta\beta v_t-\eta cw_t\\ &=w_t-\beta(w_{t-1}-w_t)-\eta cw_t\\ &=(1+\beta-\eta c)w_t-\beta w_{t-1}. \end{aligned}\]
The next parameter depends on the previous two values. With \(v_0=0\), the first step remains \(w_1=(1-\eta c)w_0\); the two-step recurrence then continues the sequence. This makes the difference from plain descent explicit (Zhang et al. 2023).
To investigate possible patterns, try a solution proportional to \(r^t\). Substitution gives the characteristic equation
\[r^2-(1+\beta-\eta c)r+\beta=0.\]
Its roots describe the recurrence’s modes. If both roots have magnitude below one, the sequence converges to zero for arbitrary initial conditions. Negative or complex roots can produce oscillation. Repeated roots introduce an additional factor proportional to \(t\), but still decay if their magnitude is below one. You do not need this root analysis to implement momentum; it explains why adding history can change both speed and stability.
Set \(c=1\), \(\eta=0.5\), \(\beta=0.5\), \(w_0=1\), and \(v_0=0\).
2.1 \(w_1=(1-0.5)1=0.5\). Subsequently \(w_{t+1}=w_t-0.5w_{t-1}\), so \(w_2=0.5-0.5(1)=0\) and \(w_3=0-0.5(0.5)=-0.25\). The stored velocity is still nonzero at the minimum; unlike plain descent, momentum can move away from it on the next step.
2.2 The equation is \(r^2-r+0.5=0\). The quadratic formula gives \(r=(1\pm\sqrt{-1})/2=(1\pm i)/2\). Each magnitude is \(\sqrt{1/4+1/4}=1/\sqrt2\approx0.707<1\), so the recurrence converges with an oscillatory envelope.
2.3 No. The envelope factor 0.707 is larger than 0.5 and therefore decays more slowly. Some individual momentum iterates can nevertheless be closer, including the exact zero at update 2. One lucky iterate is not a general convergence-rate advantage.
Read further: D2L §12.6, Momentum. Compare its update convention with ours before transferring numerical settings.
The quadratic calculation above is exact. What survives when curvature changes as we move? Let \(f:\mathbb R\to\mathbb R\) be twice continuously differentiable, bounded below by \(f_{\inf}\), and satisfy \(|f''(x)|\leq L\) everywhere, with \(L>0\). Here \(L\) is a curvature bound, not the loss function. Taylor’s theorem with Lagrange remainder gives, for some \(\xi\) between \(x\) and \(x+d\),
\[f(x+d)=f(x)+f'(x)d+\frac12f''(\xi)d^2 \leq f(x)+f'(x)d+\frac L2d^2.\]
The first-order term predicts improvement; the second-order term limits how far we can trust that prediction. The bound must hold along the entire step, not just at its starting point. In several dimensions, apply the same argument to \(h(s)=f(w+sd)\); a Hessian bound \(\|\nabla^2 f\|_{\mathrm{op}}\leq L\) gives \(f(w+d)\leq f(w)+\nabla f(w)^\top d+L\|d\|^2/2\).
For gradient descent, \(d=-\eta f'(x)\), hence
\[f(x_{t+1})\leq f(x_t) -\eta\left(1-\frac{L\eta}{2}\right)|f'(x_t)|^2.\]
Thus \(0<\eta<2/L\) guarantees strict decrease whenever the gradient is nonzero. At \(\eta=1/L\), sum this inequality from \(t=0\) to \(T-1\). The function values telescope:
\[\sum_{t=0}^{T-1}|f'(x_t)|^2\leq2L[f(x_0)-f_{\inf}],\qquad \min_{0\leq t<T}|f'(x_t)|^2\leq\frac{2L[f(x_0)-f_{\inf}]}{T}.\]
The infinite sum is finite, so \(f'(x_t)\to0\). The displayed rate concerns the smallest squared gradient seen so far, not the distance of the last iterate to a minimizer. Without additional assumptions, it establishes neither convergence of the parameters nor a global minimum. For example, descent initialized at the local maximum \(x=0\) of \(f(x)=\cos x\) stays there, despite bounded curvature and a lower-bounded objective. Compare the stronger quadratic result in Section 13.2.
Use the book’s unnormalized momentum and write the displacement as \(d_t=x_t-x_{t-1}=-\eta v_t\). For constant \(\eta>0\) and \(0\leq\beta<1\),
\[d_{t+1}=\beta d_t-\eta f'(x_t).\]
Substitute \(f'(x_t)=(\beta d_t-d_{t+1})/\eta\) into the Taylor bound:
\[f(x_{t+1})\leq f(x_t)+\frac\beta\eta d_t d_{t+1} -\left(\frac1\eta-\frac L2\right)d_{t+1}^2.\]
The elementary inequality \(2ab\leq a^2+b^2\) suggests defining
\[E_t=f(x_t)+\frac\beta{2\eta}d_t^2.\]
Applying that inequality and collecting terms gives
\[E_{t+1}\leq E_t- \left(\frac{1-\beta}{\eta}-\frac L2\right)d_{t+1}^2.\]
If \(0<\eta<2(1-\beta)/L\), this energy decreases and is bounded below by \(f_{\inf}\). Telescoping shows \(\sum_t d_{t+1}^2<\infty\), so \(d_t\to0\) and \(f'(x_t)=(\beta d_t-d_{t+1})/\eta\to0\). The loss itself can temporarily rise while the energy falls. This is a sufficient stationarity argument, not an acceleration theorem. More detailed heavy-ball analyses use related energy functions (Sun et al. 2019).
The condition is conservative: for the scalar quadratic \(cw^2/2\), the roots in Section 13.3 are inside the unit circle exactly when \(0<\eta c<2(1+\beta)\), for \(0\leq\beta<1\). This larger quadratic stability region does not prove the same guarantee for every smooth nonquadratic loss.
beta, eta = 0.5, 0.5 # L = 1; satisfies the sufficient energy condition.
x, displacement = 1.0, 0.0
momentum_x, momentum_energy = [x], [0.5 * x**2]
for _ in range(16):
displacement = beta * displacement - eta * x
x += displacement
momentum_x.append(x)
momentum_energy.append(0.5 * x**2 + beta * displacement**2 / (2 * eta))
assert np.any(np.diff(0.5 * np.array(momentum_x)**2) > 0)
assert np.all(np.diff(momentum_energy) <= 1e-14)fig, ax = plt.subplots(figsize=(7, 3.6))
ax.plot(0.5 * np.array(momentum_x)**2, "o-", label="Loss")
ax.plot(momentum_energy, "s--", label="Loss + memory energy")
ax.set(xlabel="Update", ylabel="Value", xlim=(0, 8))
ax.legend(frameon=False)
ax.grid(alpha=0.15)
fig.tight_layout()
show_plot(fig)

Suppose the gradient has been \(+1\) long enough that the accumulator is at \(v=1/(1-\beta)=10\) for \(\beta=0.9\). Now the gradient becomes \(-1\) on every subsequent update. How many updates pass before the parameter moves in the new descent direction?
After \(k\) new gradients, \(v_k=-10+20(0.9)^k\). It first becomes negative when \(0.9^k<1/2\), at \(k=7\). For the first six updates, \(-\eta v_k\) still points in the old direction. This is a prescribed-gradient thought experiment, not a claim that a particular fixed objective generates those gradients.
With constant gradients, the steady update is \(-\eta g/(1-\beta)\). Therefore holding the numerical learning rate fixed while adding momentum changes both memory and steady update magnitude. A convention using \(v_{t+1}=\beta v_t+(1-\beta)g_t\) needs a correspondingly rescaled learning rate for a fair comparison.
Recall the Adam equations, using \(s\) for the second moment to distinguish it from momentum’s velocity:
\[\begin{aligned} m_{t+1}&=\beta_1m_t+(1-\beta_1)g_t, & s_{t+1}&=\beta_2s_t+(1-\beta_2)g_t^2,\\ \hat m_{t+1}&=m_{t+1}/(1-\beta_1^{t+1}), & \hat s_{t+1}&=s_{t+1}/(1-\beta_2^{t+1}). \end{aligned}\]
Squares, square roots, and divisions are coordinatewise. From zero moment states, the first bias-corrected moments are \(g_0\) and \(g_0^2\). Thus a gradient \((1,100)\) produces a first update close to \(-\eta(1,1)\) when epsilon is small. The denominator measures past squared gradients, not second derivatives; Adam is not Newton’s method (Kingma and Ba 2015).
Multiplying every loss by a positive constant \(a\) scales gradient descent’s step by \(a\) at a fixed parameter value. With Adam, scaling the entire gradient history from the start gives \(\hat m\mapsto a\hat m\) and \(\hat s\mapsto a^2\hat s\). Their ratio is unchanged if epsilon is zero and the denominator is nonzero. With epsilon, the scaled ratio is \(\hat m/(\sqrt{\hat s}+\epsilon/a)\), so the invariance is approximate. Changing scale midway through a run does not rescale the already stored history.
In one dimension let \(D_t=\sqrt{\hat s_{t+1}}+\epsilon>0\). With the exact current gradient \(f'(x_t)\), Taylor’s bound gives
\[f(x_{t+1})\leq f(x_t) -\eta\frac{f'(x_t)\hat m_{t+1}}{D_t} +\frac{L\eta^2}{2}\frac{\hat m_{t+1}^2}{D_t^2}.\]
Two obstacles are visible: the stored first moment can disagree in sign with the current gradient, and a gradient-based denominator does not enforce the curvature-dependent step bound. Bias correction removes the initial shrinking of the moments; it does not settle either obstacle.
An exact counterexample needs only a special case of Adam. Set \(f(x)=x^2/2\), \(\beta_1=\beta_2=0\), \(\eta=0.1\), and \(\epsilon=0.01\). Then \(x_{t+1}=x_t-0.1x_t/(|x_t|+0.01)\), and
\[0.04\longmapsto-0.04\longmapsto0.04.\]
The loss remains \(0.0008\). At the positive point, \(d=-0.08\): the first-order change \(f'(x)d=-0.0032\) is exactly canceled by the second-order term \(d^2/2=0.0032\). This deterministic two-cycle is not a statement about the usual default beta values; it disproves an unconditional claim that Adam must converge even on every smooth convex quadratic at every constant step size.
x, cycle = 0.04, [0.04]
for _ in range(8):
x -= 0.1 * x / (abs(x) + 0.01)
cycle.append(x)
np.testing.assert_allclose(cycle, 0.04 * (-1.0)**np.arange(9), atol=1e-14)There are deeper failure examples for Adam and convergence analyses of modified methods (Reddi et al. 2018). Positive Adam results also exist under explicit assumptions and parameter schedules: for example, a smooth bounded-gradient analysis with horizon-dependent learning rate and \(\beta_2\) (Défossez et al. 2022). Neither a small teaching counterexample nor a theorem with special assumptions settles the performance of default Adam on all neural networks.
For a single training example, consider \(f(w)=\tfrac12(w_1+2w_2-1)^2\) and initialize at \((0,0)\). Every gradient is a multiple of \((1,2)\). Gradient descent and scalar momentum with zero initial velocity therefore stay on \(w_2=2w_1\). If they converge to zero loss, their limit is \((1/5,2/5)\), the minimum Euclidean-norm solution.
In idealized Adam with \(\epsilon=0\), zero initial moments, and shared beta values, \(\hat m_2=2\hat m_1\) and \(\hat s_2=4\hat s_1\). Whenever the denominator is nonzero, both coordinates receive equal updates. Thus \(w_1=w_2\), and if zero loss is reached, the solution is \((1/3,1/3)\). This is a statement about the invariant path, not an additional convergence proof. Positive epsilon perturbs the exact equality. A new input \((1,0)\) receives predictions \(1/5\) and \(1/3\) from these two solutions. Equal training loss need not imply equal predictions elsewhere, and the example does not establish which is better. This connects optimization to implicit preferences among solutions (Wilson et al. 2017).
Finally, the weights alone are not the complete training state. At the same weights, different momentum or Adam moments can produce different next steps. To resume the same run, save optimizer state and step count, learning-rate scheduler state, and the random/data-order state as well as the parameters.
Chapter 1 established that uniform sampling gives an unbiased gradient estimate at fixed parameters. We now quantify the variability around that mean. To keep the notation manageable, consider one scalar gradient component. Let the per-example values be \(g_1,\ldots,g_n\), with
\[\mu=\frac1n\sum_i g_i,\qquad \sigma^2=\frac1n\sum_i(g_i-\mu)^2.\]
This variance describes a uniform draw from a fixed finite dataset, so its denominator is \(n\). It is not the sample-variance estimator with denominator \(n-1\).
Draw \(B\) indices independently and uniformly, allowing repeated examples. The batch estimate is \(\bar g_B=B^{-1}\sum_{j=1}^B g_{I_j}\). Averaging preserves the mean. Independence makes the cross-covariances vanish, so
\[\mathbb E[\bar g_B]=\mu,\qquad \operatorname{Var}(\bar g_B)=\frac1{B^2}\sum_{j=1}^B\operatorname{Var}(g_{I_j}) =\frac{\sigma^2}{B}.\]
Variance falls as \(1/B\), but standard deviation falls only as \(1/\sqrt B\). Halving the standard deviation therefore requires four times as many independent samples. This helps explain why increasing batch size has diminishing statistical returns; it does not by itself determine elapsed time or the best training configuration (Zhang et al. 2023).
A uniformly chosen batch of \(B\) distinct examples has dependent draws: selecting one example changes which ones remain. For \(n>1\), two distinct draws have covariance \(-\sigma^2/(n-1)\). To see why, write \(d_i=g_i-\mu\), so \(\sum_i d_i=0\). Then
\[\sum_{i\ne j}d_id_j=(\sum_i d_i)^2-\sum_i d_i^2=-n\sigma^2.\]
Dividing by the \(n(n-1)\) ordered distinct pairs gives the covariance. Including these cross-terms yields
\[\operatorname{Var}(\bar g_B)=\frac1{B^2} \left[B\sigma^2-B(B-1)\frac{\sigma^2}{n-1}\right] =\frac{\sigma^2}{B}\frac{n-B}{n-1}.\]
At \(B=n\) this variance is zero: every example is included. With replacement, even \(B=n\) can contain duplicates and omit examples, so the variance need not vanish. These formulas hold at fixed parameters. During shuffled training, parameters change between batches and the remaining data depend on earlier draws; this is not the same experiment as repeatedly sampling fresh independent batches at a fixed point.
At a fixed parameter value, four example gradients are \((-2,0,2,4)\).
3.1 \(\mu=(-2+0+2+4)/4=1\). Squared deviations are \(9,1,1,9\), giving \(\sigma^2=20/4=5\).
3.2 With replacement, variance is \(5/2=2.5\). Without replacement it is \((5/2)(4-2)/(4-1)=5/3\).
3.3 The pairs \((-2,0),(-2,2),(-2,4),(0,2),(0,4),(2,4)\) have means \(-1,0,1,1,2,3\). Their mean is 1 and their variance is \((4+1+0+0+1+4)/6=5/3\). This concerns gradient estimation on training data, not prediction quality on validation data.
Read further: D2L §12.5, Mini-batch Stochastic Gradient Descent, for the connection between averaging, computational efficiency, and training.
An unbiased gradient does not imply an unbiased loss after the update: loss is a nonlinear function of the parameters. We can quantify that difference with an intercept-only regression model, \(\hat y=w\). For fixed training labels let
\[\mu_y=\frac1n\sum_i y_i,\qquad \sigma_y^2=\frac1n\sum_i(y_i-\mu_y)^2,\qquad e=w-\mu_y.\]
The full training MSE and the optimized half MSE are
\[M(w)=\frac1n\sum_i(w-y_i)^2=\sigma_y^2+e^2,\qquad F(w)=M(w)/2.\]
Thus \(e^2\) is excess training MSE above this model’s fitted minimum. The residual \(\sigma_y^2\) is not necessarily irreducible prediction noise; a richer model with input features could explain some of it.
Sample \(B\) labels independently with replacement. The gradient of the batch half MSE is \(w-\bar y_B\). Write \(\zeta=\bar y_B-\mu_y\), so \(\mathbb E[\zeta]=0\) and \(\mathbb E[\zeta^2]=\sigma_y^2/B\). The new error is
\[e^+=(1-\eta)e+\eta\zeta.\]
Squaring and taking expectation at the current \(w\) removes the cross-term:
\[\boxed{\mathbb E[M(w^+)\mid w] =\sigma_y^2+(1-\eta)^2e^2+\frac{\eta^2\sigma_y^2}{B}.}\]
Consequently, the expected reduction is
\[\boxed{\Delta_B(w)=M(w)-\mathbb E[M(w^+)\mid w] =\eta(2-\eta)e^2-\frac{\eta^2\sigma_y^2}{B}.}\]
The deterministic part improves the fit; gradient noise adds squared error. At the same \(w\) and \(\eta\), increasing \(B\) reduces that penalty as \(1/B\). The expected parameter update is identical for every \(B\), but its expected loss is not. At \(e=0\), a noisy update increases expected MSE whenever \(\eta>0\) and \(\sigma_y^2>0\).
For \(\eta=0.2\), \(\sigma_y^2=1\), and \(e=0.1\), the current MSE is \(1.01\):
| Batch size | Expected next MSE | Expected reduction |
|---|---|---|
| 1 | 1.046400 | -0.036400 |
| 4 | 1.016400 | -0.006400 |
| 16 | 1.008900 | 0.001100 |
| 64 | 1.007025 | 0.002975 |
In this example, the larger batch changes the sign of expected progress. A single stochastic realization may still go in either direction.
Use a balanced dataset containing labels 1 and 3. Its mean is 2 and variance is 1. The number of threes in a size-\(B\) batch is binomial, which lets us sample the exact batch-mean distribution without allocating a large sample matrix. Each trial below starts at the same parameter value; this is not yet a training trajectory. Points show Monte Carlo means with two standard errors.
batch_sizes = np.array([1, 4, 16, 64, 256, 1024])
rng = np.random.default_rng(20261030)
eta, repetitions = 0.2, 50_000
batch_mc = {}
for error in [1.0, 0.1]:
estimates, standard_errors = [], []
for batch in batch_sizes:
noise = 2 * rng.binomial(batch, 0.5, repetitions) / batch - 1
new_error = (1 - eta) * error + eta * noise
reductions = error**2 - new_error**2
estimates.append(reductions.mean())
standard_errors.append(reductions.std(ddof=1) / np.sqrt(repetitions))
theory = eta * (2 - eta) * error**2 - eta**2 / batch_sizes
batch_mc[error] = (theory, np.array(estimates), np.array(standard_errors))
assert np.all(np.abs(estimates - theory) < 6 * np.array(standard_errors) + 1e-12)fig, axes = plt.subplots(1, 2, figsize=(9, 3.6))
for ax, (error, (theory, estimate, se)) in zip(axes, batch_mc.items()):
ax.plot(batch_sizes, theory, label="Exact expectation")
ax.errorbar(batch_sizes, estimate, yerr=2 * se, fmt="o", label="Simulation ±2 SE")
ax.axhline(0, color="0.5", linewidth=0.8)
ax.set(xscale="log", xlabel="Batch size", title=f"Current error = {error}")
ax.grid(alpha=0.15)
axes[0].set_ylabel("Reduction in full training MSE")
axes[0].legend(frameon=False, fontsize=8)
fig.tight_layout()
show_plot(fig)

With fresh independent batches, let \(u_t=\mathbb E[(w_t-\mu_y)^2]\). For constant \(0<\eta<2\),
\[u_{t+1}=(1-\eta)^2u_t+\frac{\eta^2\sigma_y^2}{B},\]
\[u_t=(1-\eta)^{2t}u_0+ \frac{\eta\sigma_y^2}{B(2-\eta)}\left[1-(1-\eta)^{2t}\right].\]
The limiting excess MSE is \(\eta\sigma_y^2/[B(2-\eta)]\). Reducing the learning rate or enlarging the batch lowers this floor. Reducing the rate also slows the initial contraction. This floor relies on persistent gradient noise: if every example gradient vanishes at an interpolating solution, this particular obstruction disappears. It is not a universal nonzero floor for all SGD.
| Budget held fixed | Number of updates | Question answered |
|---|---|---|
| Updates \(T\) | \(T\) | How useful is each gradient estimate? |
| Examples processed \(C\) | \(\lfloor C/B\rfloor\) | How much progress per example evaluation? |
| Training time \(\tau\) | Approximately \(\lfloor\tau/t_{\mathrm{step}}(B)\rfloor\) | How much progress on this implementation and hardware? |
Examples processed counts repeats. For shuffled data it is closely related to epochs, but it is not a count of distinct examples under replacement sampling. At fixed \(\eta\), large batches take fewer updates under an example budget, so their lower noise can lose to slower early progress.
The next figure uses the exact recurrence and an illustrative cost model \(t_{\mathrm{step}}(B)=a+cB\), with \(a=1\) and \(c=0.02\) in arbitrary time units. Its time axis is modeled, not measured. Overhead favors batching; per-example cost eventually limits the benefit. A real device can have a quite different cost curve because of vectorization, memory limits, and parallel execution.
fig, axes = plt.subplots(1, 3, figsize=(10, 3.6))
steps = np.arange(301)
for batch in [1, 4, 16, 64]:
eta = 0.2
decay = (1 - eta)**(2 * steps)
expected_excess = decay + eta / (batch * (2 - eta)) * (1 - decay)
budgets = [steps, steps * batch, steps * (1 + 0.02 * batch)]
for ax, budget in zip(axes, budgets):
ax.semilogy(budget, expected_excess, label=f"B = {batch}")
for ax, label, limit in zip(axes, ["Updates", "Examples processed", "Modeled time"],
[40, 300, 80]):
ax.set(xlabel=label, xlim=(0, limit), ylim=(0.001, 1.1))
ax.grid(alpha=0.15)
axes[0].set_ylabel("Expected excess training MSE")
axes[0].legend(frameon=False, fontsize=8)
fig.tight_layout()
show_plot(fig)

For fixed \(w\) with \(e\ne0\), maximize the one-step reduction over \(\eta\). The derivative gives
\[\eta_B^*=\frac{e^2}{e^2+\sigma_y^2/B},\qquad \Delta_B^*=\frac{e^2}{1+B_{\mathrm{noise}}/B},\qquad B_{\mathrm{noise}}=\frac{\sigma_y^2}{e^2}.\]
For \(B\ll B_{\mathrm{noise}}\), both the locally optimal rate and progress increase approximately linearly with \(B\). For \(B\gg B_{\mathrm{noise}}\), improvement per update saturates. The crossover grows as the fit approaches the mean. This simple calculation connects to the empirical gradient-noise-scale idea (McCandlish et al. 2018); it does not prove an unrestricted linear scaling rule for neural networks.
Under the cost model above, progress per unit time is proportional to \(B/[(B+B_{\mathrm{noise}})(a+cB)]\). Its derivative has the sign of \(aB_{\mathrm{noise}}-cB^2\), so the positive continuous optimum is \(B^*=\sqrt{aB_{\mathrm{noise}}/c}\) when \(a,c,B_{\mathrm{noise}}>0\). A usable batch is an integer within memory limits. This is a one-step, locally tuned model; it is not the globally best batch for an entire training run.
For an empirical follow-up, use noisy linear regression with many features. The repository includes tools/benchmark_batch_size.py, which prints a table and saves JSON with the configuration, candidate learning rates, individual trials, success counts, and timings. Run from the repository root:
uv run --locked python tools/benchmark_batch_size.py --mode smoke --output /tmp/batch-smoke.json
uv run --locked python tools/benchmark_batch_size.py --mode full --output /tmp/batch-full.jsonThe full experiment generates 16,384 examples with 64 Gaussian features and additive label noise of variance 1, using seed 20261030 and float64 NumPy on CPU. It compares \(B\in\{1,4,16,64,256,1024,4096\}\) from the same zero weights. The script requests one BLAS thread before importing NumPy and records the environment; timings are specific to that machine and implementation.
The core update, with independent uniform indices and half-MSE normalization, is exactly:
indices = rng.integers(0, len(y), size=batch)
xb = X[indices]
gradient = xb.T @ (xb @ w - y[indices]) / batch
w -= learning_rate * gradientUse the least-squares solution \(w_{\mathrm{LS}}\) to measure excess full training MSE without subtracting two nearly equal losses:
\[M(w)-M(w_{\mathrm{LS}})=(w-w_{\mathrm{LS}})^\top H(w-w_{\mathrm{LS}}),\qquad H=X^\top X/n.\]
The target is excess training MSE at most 0.1 for three consecutive updates; this is an operational stopping rule, not a convergence certificate. For each batch, try the same learning-rate grid on pilot seeds 200–202. Select the rate with the smallest median update count among candidates that succeed on all pilot seeds, breaking ties toward the smaller rate. Freeze that rate and report ten fresh seeds 1000–1009. This selects for update efficiency; it need not identify the exact fastest learning rate in seconds. Keep pilot tuning time separate from the reported training time.
Warm up each shape and randomize batch order across reporting trials. Time random index generation, data gathering, gradient computation, and updating; exclude data generation, least-squares fitting, full-loss evaluation, plotting, and tuning. The full mode caps each trial at 6,000 updates or 0.12 accumulated training seconds, whichever is reached first. Increase that time cap with --max-seconds on slower machines. Report failures as budget-limited or unstable, and retain them in the success count. Conditional timing summaries of successful trials are not enough if success rates differ. The timer also adds overhead to very short updates; repeat measurements before interpreting small differences. GPU versions would need device synchronization.
A motivating reference CPU run, with NumPy 2.3.5 and one OpenBLAS 0.3.30 thread, reached the target on all ten reporting seeds for every batch. The following are rounded measurements from that run, not expected values or promises for another machine:
| Batch | Selected rate | Median updates | Median examples | Median training time (ms) |
|---|---|---|---|---|
| 1 | 0.0025 | 835.5 | 835.5 | 7.60 |
| 4 | 0.01 | 211 | 844 | 1.85 |
| 16 | 0.04 | 56.5 | 904 | 0.55 |
| 64 | 0.08 | 19.5 | 1,248 | 0.25 |
| 256 | 0.32 | 6 | 1,536 | 0.16 |
| 1,024 | 0.64 | 4 | 4,096 | 0.35 |
| 4,096 | 0.64 | 4 | 16,384 | 2.21 |
The instructive pattern is that updates plateau before computation does: the largest two batches both need four median updates, but the larger one costs more. Batch 256 was fastest in this run; batch 1 used fewer examples. The script also records fixed-rate runs at \(\eta=0.01\) for 600 updates, so students can distinguish the effect of averaging from the effect of retuning. The smoke mode uses a smaller configuration for a quick functional check and is not expected to reproduce the full table. No validation or test performance is assessed here. The accompanying raw measurement file is experiments/week03/batch-size-reference.json; rerun the script to obtain measurements on your own hardware.
import json
from pathlib import Path
reference = json.loads(Path("experiments/week03/batch-size-reference.json").read_text())
rows = reference["summary"]
batches = np.array([row["batch"] for row in rows])
fig, axes = plt.subplots(1, 3, figsize=(10, 3.6))
for ax, key, label in zip(axes, ["median_steps", "median_examples", "median_ms"],
["Updates to target", "Examples to target", "Training time (ms)"]):
values = np.array([row[key] for row in rows])
ax.plot(batches, values, "o-")
if key == "median_ms":
lo = np.array([row["q25_ms"] for row in rows])
hi = np.array([row["q75_ms"] for row in rows])
ax.errorbar(batches, values, yerr=[values - lo, hi - values], fmt="none", capsize=3)
ax.set(xscale="log", yscale="log", xlabel="Batch size", ylabel=label)
ax.grid(alpha=0.15)
fig.tight_layout()
show_plot(fig)

For \(F(w)=\|Xw-y\|^2/(2n)\), let \(g=\nabla F(w)\), \(H=X^\top X/n\), and let \(\Sigma\) be the covariance of a uniformly drawn per-example gradient at the current fixed \(w\). Independent with-replacement sampling gives \(\operatorname{Cov}(\hat g_B)=\Sigma/B\). Taylor is exact for this quadratic:
\[\mathbb E[F(w-\eta\hat g_B)\mid w]=F(w)-\eta\|g\|^2 +\frac{\eta^2}{2}\left(g^\top Hg+\frac{\operatorname{tr}(H\Sigma)}{B}\right).\]
The trace term measures noise weighted by curvature. It follows by writing \(\hat g_B=g+\xi\), taking expectations, and using \(\mathbb E[\xi^\top H\xi]=\operatorname{tr}(H\Sigma)/B\). For an \(L\)-smooth nonquadratic loss with an unbiased finite-variance batch gradient, the corresponding upper bound is
\[\mathbb E[F(w-\eta\hat g_B)\mid w]\leq F(w) -\eta(1-L\eta/2)\|g\|^2+\frac{L\eta^2}{2B}\operatorname{tr}\Sigma.\]
These formulas explain why noise matters more when the gradient signal is small, without asserting a universal runtime-optimal batch. For a detailed least-squares treatment of batching, averaging, and parallelization, see Jain et al. (2018).
For a uniformly drawn batch without replacement, multiply the variance term by \((n-B)/(n-1)\), as in Section 13.6. A full distinct batch has no sampling variance; a size-\(n\) batch drawn with replacement still does. Random reshuffling during training needs more care because current parameters depend on previously selected examples.
The one-step formulas above describe plain SGD. Momentum adds history; Adam adds history and a random denominator, so we cannot substitute its update into the SGD formula and keep the same noise term. At a fixed parameter with independent stationary gradient noise of variance \(\sigma_g^2/B\), a normalized exponential average \(m_t=\beta m_{t-1}+(1-\beta)g_t\) has stationary variance \((1-\beta)\sigma_g^2/[(1+\beta)B]\): sum the squared geometric weights. During training the gradients and parameters change, so this averaging calculation alone is not an optimizer convergence guarantee.
Memory is measured in updates. A moving average’s characteristic horizon is approximately \(1/(1-\beta)\) updates, or \(B/(1-\beta)\) sampled examples. Changing \(B\) at fixed beta changes its memory in data units. To preserve exponential decay per processed example, a formal rescaling is \(\beta_{\mathrm{new}}=\beta_{\mathrm{old}}^{B_{\mathrm{new}}/B_{\mathrm{old}}}\); this does not make the resulting optimizer trajectories equivalent. Compare SGD, momentum, and Adam with an explicit budget and comparable tuning effort.
Ordinary least squares chooses coefficients that minimize prediction error. Ridge regression adds a preference for smaller coefficients. Starting from chapter 1’s normal equations makes the change especially clear.
Let \(X\) and \(y\) be centered training features and targets, and write
\[J(w)=\frac1{2n}\|Xw-y\|^2+\lambda\|w\|^2.\]
All entries of \(w\) are penalized. Centering lets us leave the intercept out of this system; in the original coordinates its fitted value is \(b=\bar y-\bar x^\top w\). Use these training means when predicting new examples. No validation or test observations are used to fit the centering.
Differentiating and setting the gradient to zero gives
\[\frac1nX^\top(Xw-y)+2\lambda w=0,\]
\[\left(\frac1nX^\top X+2\lambda I\right)w=\frac1nX^\top y.\]
Define \(H=X^\top X/n\) and \(q=X^\top y/n\). The solution is \(w_\lambda=(H+2\lambda I)^{-1}q\). As in ordinary least squares, this inverse is a mathematical expression; implement a linear solve rather than explicitly forming an inverse. For \(\lambda>0\), adding \(2\lambda I\) makes the system positive definite even when feature columns are redundant (Goodfellow et al. 2016).
Choose orthonormal coordinates aligned with \(H\)’s eigenvectors. In those coordinates, let the curvature in direction \(j\) be \(h_j\geq0\) and the corresponding component of \(q\) be \(q_j\). Then
\[w_{\lambda,j}=\frac{q_j}{h_j+2\lambda}.\]
If \(h_j>0\), the unregularized solution is \(w_j^*=q_j/h_j\), giving
\[w_{\lambda,j}=\frac{h_j}{h_j+2\lambda}w_j^*.\]
Ridge shrinks low-curvature directions more strongly in relative terms. If \(h_j=0\), least squares also has \(q_j=0\) in that direction: the training predictions cannot identify that coefficient, while ridge chooses zero. For positive-definite \(H\), the penalized condition number is
\[\kappa_\lambda=\frac{h_{\max}+2\lambda}{h_{\min}+2\lambda}.\]
It approaches one as lambda grows. But better conditioning does not prove better generalization: a very large penalty may make the fit almost constant. Nor does it guarantee faster progress at an unchanged learning rate, because the largest curvature has increased. We changed both the solution and the geometry.
For a centered two-feature problem, suppose
\[H=\begin{pmatrix}1&1\\1&1\end{pmatrix},\qquad q=\begin{pmatrix}2\\2\end{pmatrix}.\]
4.1 Both rows give \(w_1+w_2=2\). Every pair \((a,2-a)\) solves the system, so coefficients are not unique.
4.2 Since \(2\lambda=1\), the equations are \(2w_1+w_2=2\) and \(w_1+2w_2=2\). Subtracting gives \(w_1=w_2\), hence \(3w_1=2\) and \(w_1=w_2=2/3\). Their sum is \(4/3\), not 2: ridge changes the fitted solution rather than merely choosing a different algorithm for the same unpenalized optimum.
4.3 Adding the identity shifts both eigenvalues by 1, giving 1 and 3. The condition number is 3. The penalized problem has a unique solution and a nonsingular Hessian. Nothing here measures unseen-data performance, so better generalization is not established.
Read further: Goodfellow, Bengio, and Courville, Deep Learning, §7.1.1, on L2 parameter regularization (Goodfellow et al. 2016). The online book is free to read.
Ridge changes the objective explicitly. Early stopping keeps the objective but limits how far we follow its optimization trajectory. Why can these different operations have a similar effect?
Use the same centered least-squares problem and initialize \(w_0=0\). In an eigenvector direction with \(h_j>0\), gradient descent gives
\[w_{t+1,j}=(1-\eta h_j)w_{t,j}+\eta q_j.\]
Subtract the unregularized solution \(w_j^*=q_j/h_j\). Since \(q_j=h_jw_j^*\),
\[w_{t+1,j}-w_j^*=(1-\eta h_j)(w_{t,j}-w_j^*).\]
Starting from zero, repeated substitution gives
\[w_{t,j}=\left[1-(1-\eta h_j)^t\right]w_j^*.\]
For \(0<\eta\leq1/h_{\max}\) and integer \(t\geq1\), the bracket lies between zero and one. We have reached only a fraction of the least-squares coefficient. High-curvature directions approach their fitted values more quickly; low-curvature directions remain more strongly suppressed. In a zero-curvature direction, \(q_j=0\) and zero initialization leaves the coefficient zero. The shrinkage interpretation depends on initialization and step size: larger stable rates can overshoot, and nonzero initialization changes the expression.
Compare the two factors multiplying \(w_j^*\):
\[\text{Early stopping: }1-(1-\eta h_j)^t, \qquad \text{Ridge: }\frac{h_j}{h_j+2\lambda}.\]
Both can suppress poorly determined, low-curvature directions. Their functional forms differ, however. Matching them for one direction generally produces a lambda that will not match another. Thus early stopping is not simply ridge regression with one universally equivalent penalty strength. This least-squares analysis explains a regularizing mechanism; it does not prove that every early checkpoint generalizes better (Goodfellow et al. 2016).


Let \(H=\operatorname{diag}(1,4)\) and \(w^*=(2,1)\). Start from zero and use \(\eta=0.2\) for two updates.
5.1 The factors are \(1-(1-0.2)^2=0.36\) and \(1-(1-0.8)^2=0.96\). Thus \(w_2=(0.36\cdot2,0.96\cdot1)=(0.72,0.96)\).
5.2 Matching the first factor requires \(1/(1+2\lambda)=0.36\). Therefore \(2\lambda=1/0.36-1=16/9\), so \(\lambda=8/9\). The second ridge factor is then \(4/(4+16/9)=9/13\approx0.6923\), not 0.96. Conversely, matching the second would require \(4/(4+2\lambda)=0.96\), giving \(\lambda=1/12\), which does not match the first. No single lambda matches both coefficients in this example.
5.3 Compare prediction loss on validation data using a declared selection procedure. After selecting settings, assess the frozen procedure on untouched test data. The formulas describe fitting to the training objective, not which suppressed directions contain noise rather than useful signal.
Read further: Goodfellow, Bengio, and Courville, §7.8, on early stopping and its relation to regularization. Compare the book’s normalization conventions with ours when following its equations (Goodfellow et al. 2016).
These examples expose different decisions within training. A learning rate and momentum coefficient change how we approach an objective. Batch size changes the gradient estimate’s variability and computation. Ridge changes the objective itself, while early stopping selects an intermediate point on the original trajectory. Their effects can interact, but they are not interchangeable controls.
For further practice, choose one derivation and change its assumptions: initialize away from zero, leave an intercept unpenalized, or sample a batch without replacement. State which equation must change before running any code. Being able to identify where an argument stops applying is as useful as reproducing the argument itself.