NeuroGenesys.
Optimization & GeneralizationAcademy • Foundations • Lesson 3 of 4

Stochastic optimization: SGD, momentum and Adam

7 min read • By Will Schulz • NeuroGenesys AI Academy

No one computes the exact gradient of a language model's loss over its full training set: one gradient step would require a pass over trillions of tokens. Training instead uses cheap, noisy gradient estimates and adds two refinements, momentum and per-parameter step sizes. This lesson explains each piece, why it works, and the optimizer settings large models actually use.

Noisy gradients are enough

The training loss is an average over examples, L(θ)=1N∑iℓi(θ)L(\theta) = \frac1N\sum_i \ell_i(\theta). Pick a random minibatch BB of bb examples and use

gB=1b∑i∈B∇ℓi(θ)g_B = \frac1b\sum_{i\in B}\nabla \ell_i(\theta)

in place of ∇L\nabla L. This estimate is unbiased: its expectation is the true gradient. Its variance falls as 1/b1/b, so its standard deviation falls as 1/b1/\sqrt b. Quadrupling the batch only halves the noise, while it quadruples the compute per step.

That the method converges at all goes back to Robbins and Monro (1951). They studied finding the root of a function that can only be observed through noisy measurements. They showed that iterating with step sizes ηk\eta_k satisfying

∑kηk=∞,∑kηk2<∞\sum_k \eta_k = \infty, \qquad \sum_k \eta_k^2 < \infty

converges, for example with ηk∝1/k\eta_k \propto 1/k.[1] The first condition lets the iterates travel arbitrarily far; the second makes the accumulated noise finite. Stochastic gradient descent (SGD) is this scheme applied to ∇L=0\nabla L = 0. In practice, deep-learning schedules do not follow 1/k1/k. They use a roughly constant rate followed by a decay, but the logic is the same: large steps to make progress, small steps to average out the noise.

The noise is not only a cost. Keskar et al. found that very large batches tended to converge to sharper minima and to generalize worse than small batches, and attributed the difference to the noise in small-batch gradients.[2] The interpretation is debated (see Generalization). Practitioners have also found ways to use large batches without that loss. Goyal et al. trained ResNet-50 on ImageNet with batches of 8,192 images without losing accuracy. They scaled the learning rate linearly with batch size and added a warmup phase.[3]

Momentum: averaging out the zig-zag

Gradient descent in a long, narrow valley zig-zags across the steep walls and creeps along the floor. Polyak's heavy-ball method (1964) adds a velocity term:[4]

vk+1=βvk+∇L(θk),θk+1=θk−η vk+1.v_{k+1} = \beta v_k + \nabla L(\theta_k), \qquad \theta_{k+1} = \theta_k - \eta\, v_{k+1}.

The velocity is an exponentially weighted sum of past gradients. Components that keep the same sign, along the valley floor, add up, so with a constant gradient the effective step approaches η/(1−β)\eta/(1-\beta). That is 10 times larger for the common choice β=0.9\beta=0.9. Components that flip sign, across the walls, largely cancel.

Worked example: the same valley, with momentum

Return to L=12(x2+100y2)L = \tfrac12(x^2 + 100y^2), with condition number κ=100\kappa=100. Plain gradient descent with its best step contracts the error by (κ−1)/(κ+1)=0.980(\kappa-1)/(\kappa+1) = 0.980 per step, so a 100-fold reduction takes about 230 steps. On quadratics, heavy-ball momentum with tuned η\eta and β\beta achieves the rate (κ−1)/(κ+1)=9/11≈0.818(\sqrt\kappa-1)/(\sqrt\kappa+1) = 9/11 \approx 0.818, a standard result for quadratics. The same 100-fold reduction then takes

ln⁡100−ln⁡0.818≈4.610.201≈23 steps,\frac{\ln 100}{-\ln 0.818} \approx \frac{4.61}{0.201} \approx 23 \text{ steps},

a tenfold speed-up. The dependence on conditioning has gone from κ\kappa to κ\sqrt\kappa. With stochastic gradients the gain is smaller, because momentum also averages noise, but the qualitative benefit remains.

Check your understanding

With momentum β=0.99\beta = 0.99 and learning rate η\eta, roughly what effective step size does a parameter receive if its gradient has been constant for a long time? What risk does this create?

Show answer +

η/(1−β)=100η\eta/(1-\beta) = 100\eta. The risk is overshoot: the velocity takes about 1/(1−β)≈1001/(1-\beta)\approx100 steps to respond to a change, so when the gradient changes direction the parameter keeps moving the old way for many steps. High-momentum settings usually need a smaller η\eta.

Adam: a step size per parameter

Parameters in a deep network see gradients on very different scales. Embedding rows for rare tokens are updated seldom, and some layers have far larger gradients than others. A single learning rate suits none of them well. Adam (Kingma and Ba, 2014) keeps two running averages per parameter, the mean and the uncentred variance of its gradient:[5]

mk=β1mk−1+(1−β1)gk,sk=β2sk−1+(1−β2)gk2,m_k = \beta_1 m_{k-1} + (1-\beta_1)g_k, \qquad s_k = \beta_2 s_{k-1} + (1-\beta_2)g_k^2,

corrects them for their zero initialisation,

m^k=mk1−β1k,s^k=sk1−β2k,\hat m_k = \frac{m_k}{1-\beta_1^k}, \qquad \hat s_k = \frac{s_k}{1-\beta_2^k},

and updates

θk=θk−1−η m^ks^k+ϵ.\theta_{k} = \theta_{k-1} - \eta\,\frac{\hat m_k}{\sqrt{\hat s_k}+\epsilon}.

The paper's suggested defaults are β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999 and ϵ=10−8\epsilon=10^{-8}.[5]

Why bias correction? At the first step, m1=(1−β1)g1=0.1 g1m_1 = (1-\beta_1)g_1 = 0.1\,g_1, which is far too small. Dividing by 1−β11=0.11-\beta_1^1 = 0.1 restores m^1=g1\hat m_1 = g_1. Likewise s^1=g12\hat s_1 = g_1^2, so the first update is η g1/∣g1∣=±η\eta\, g_1/|g_1| = \pm\eta per coordinate.

That last observation is the key property. The ratio m^/s^\hat m/\sqrt{\hat s} is roughly unit-scale whatever the raw size of the gradient, so each parameter moves by about η\eta per step, scaled down when its gradient is noisy (large s^\hat s relative to m^2\hat m^2). Rescaling the loss by 1,000 leaves Adam's updates almost unchanged. Adam behaves like momentum combined with a per-coordinate correction for conditioning.

Check your understanding

Parameter A has gradients that are always +0.001+0.001. Parameter B has gradients that alternate between +1+1 and −1-1. After many steps of Adam, which moves faster, and why?

Show answer +

A. Its m^≈0.001\hat m \approx 0.001 and s^≈0.001\sqrt{\hat s}\approx 0.001, so it moves by about η\eta per step. For B, m^≈0\hat m \approx 0 (the signs cancel) while s^≈1\sqrt{\hat s}\approx 1, so it barely moves. Adam's step size depends on the gradient's consistency, not its magnitude.

AdamW: decoupling weight decay

Weight decay shrinks parameters toward zero every step. For plain SGD this is the same as adding an L2 penalty λ2∥θ∥2\tfrac\lambda2\|\theta\|^2 to the loss. Loshchilov and Hutter pointed out that for Adam the two are not equivalent.[6] If the penalty's gradient λθ\lambda\theta is added to gg, it gets divided by s^\sqrt{\hat s} along with everything else. Parameters with large gradient variance are then barely regularised. AdamW applies the decay directly to the weights, outside the adaptive scaling:

θk=θk−1−η(m^ks^k+ϵ+λ θk−1).\theta_k = \theta_{k-1} - \eta\left(\frac{\hat m_k}{\sqrt{\hat s_k}+\epsilon} + \lambda\,\theta_{k-1}\right).

They reported that decoupling made the best decay value largely independent of the learning rate. It also substantially improved Adam's generalization, enough to match SGD with momentum on image-classification benchmarks where Adam had lagged.[6]

AdamW is widely used to train large transformers. In one documented example, Llama 2 was pretrained with AdamW using β1=0.9\beta_1=0.9, β2=0.95\beta_2=0.95, ϵ=10−5\epsilon=10^{-5}, weight decay 0.1, gradient clipping at 1.0, 2,000 warmup steps and cosine decay to 10% of the peak learning rate.[7] The lower β2\beta_2 shortens the memory of the variance estimate from about 1,000 steps to about 20, so it responds faster to changes in gradient scale.

Weight decay matters beyond final accuracy. In this lab's small-network continual-learning experiments, loss of plasticity over long training streams behaved like an Adam-related weight-norm pathology. Plain weight decay fixed it better than several specialised methods at that scale. The authors note that other work finds L2 insufficient for deeper networks and longer streams.[8] The full results are in Escaping the saturated game.

Key takeaways

  • Minibatch gradients are unbiased and have noise that falls as 1/b1/\sqrt{b}. Robbins–Monro step-size conditions explain why noisy steps still converge.
  • Momentum accumulates consistent gradient directions and cancels oscillating ones. On quadratics it improves the dependence on conditioning from κ\kappa to κ\sqrt\kappa, from about 230 to about 23 steps in the worked example.
  • Adam normalises each parameter's step by a running estimate of its gradient scale, so updates are roughly η\eta in size and insensitive to gradient magnitude. Bias correction fixes the early steps.
  • With Adam, L2 regularisation and weight decay differ. AdamW decouples them and is the standard optimizer for large transformers.

Sources

  1. H. Robbins and S. Monro (1951). "A Stochastic Approximation Method." The Annals of Mathematical Statistics 22(3), 400–407. https://doi.org/10.1214/aoms/1177729586 ↩

  2. N. S. Keskar, D. Mudigere, J. Nocedal, M. Smelyanskiy and P. T. P. Tang (2016). "On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima." ICLR 2017. arXiv:1609.04836. https://arxiv.org/abs/1609.04836 ↩

  3. P. Goyal, P. Dollár, R. Girshick et al. (2017). "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour." arXiv:1706.02677. https://arxiv.org/abs/1706.02677 ↩

  4. B. T. Polyak (1964). "Some methods of speeding up the convergence of iteration methods." USSR Computational Mathematics and Mathematical Physics 4(5), 1–17. https://doi.org/10.1016/0041-5553(64)90137-5 ↩

  5. D. P. Kingma and J. Ba (2014). "Adam: A Method for Stochastic Optimization." ICLR 2015. arXiv:1412.6980. https://arxiv.org/abs/1412.6980 ↩ ↩2

  6. I. Loshchilov and F. Hutter (2017). "Decoupled Weight Decay Regularization." ICLR 2019. arXiv:1711.05101. https://arxiv.org/abs/1711.05101 ↩ ↩2

  7. H. Touvron et al. (2023). "Llama 2: Open Foundation and Fine-Tuned Chat Models." arXiv:2307.09288. https://arxiv.org/abs/2307.09288 ↩

  8. NeuroGenesys (2026). "Escaping the saturated game: plasticity, harder benchmarks, and retrieval in continual learning." /research/three-frontiers-continual-learning ↩

Leadership

A word from the founder — on why the brain is the blueprint, and why the next decade of intelligence will be built here.

"The brain is the universe's only proof that general intelligence is possible. We treat it as the blueprint."

From cortical interfaces to photonic silicon, every program at NeuroGenesys exists to answer one question: how does intelligence arise — and how do we build it safely.

Will Schulz

Will Schulz

Founder, NeuroGenesys • AW3 Technology