↓ Skip to main content
  1. Engineering Notes & Articles/

Mathematical Optimization — From SGD and AdamW to Learning Rate Schedules

Table of Contents
Machine Learning Fundamentals - This article is part of a series.
Part 3: This Article

1. The Core Problem: Why Naive Gradient Descent Breaks at Scale
#

In Part 2, we proved that even a simple binary classifier like Logistic Regression produces a transcendental gradient equation with no closed-form algebraic solution. Finding the optimal parameters $w^*$ requires iterative numerical optimization—taking repeated steps downhill along an objective surface $J(w)$.

The simplest algorithm is Batch Gradient Descent:

$$w_{t+1} = w_t - \eta \nabla_w J(w_t), \qquad \nabla_w J(w_t) = \frac{1}{n} \sum_{i=1}^{n} \nabla_w L(h_{w_t}(x_i), y_i)$$

On clean textbook parabolas with a few hundred samples, this single equation works effortlessly. In real-world machine learning and deep learning, it breaks down along four distinct axes:

  1. Computational Bottleneck: Computing a single exact gradient requires a full pass over all $n$ training samples. When $n$ reaches millions of records or trillions of tokens, one update takes hours.
  2. Ill-Conditioned Ravines: Real objective surfaces are rarely symmetric bowls. They contain steep canyon walls paired with nearly flat valley floors. A single global learning rate $\eta$ either diverges violently off the canyon walls or crawls imperceptibly along the valley.
  3. High-Dimensional Saddle Points: In non-convex landscapes, zero-gradient plateaus are overwhelmingly saddle points—not local minima—where vanilla gradient descent stalls.
  4. Parameter Scale Mismatch: Different features and neural layers experience gradients that differ by several orders of magnitude, rendering a single uniform step size suboptimal across coordinates.

Every major optimizer developed over the past seven decades—from SGD and Momentum to Adam and AdamW—was engineered specifically to solve one or more of these failure modes.


2. Conceptual Intuition: Navigating Ravines, Noise, and Saddle Points
#

Picture standing blindfolded inside a narrow, steep-walled mountain gorge that slopes very gently toward a lake miles ahead. Your only instrument is a local altimeter that tells you the steepest downhill direction right beneath your boots.

  • Vanilla Gradient Descent steps strictly perpendicular to the contour lines. Because the gorge walls are far steeper than the valley floor, the gradient points almost entirely across the canyon rather than down it. You bounce back and forth between opposing cliffs while barely moving forward.
  • Momentum replaces your massless boots with a heavy iron ball rolling down the gorge. Left-right bounces across the steep walls cancel each other out over consecutive steps, while the tiny, consistent forward slope accumulates velocity until the ball shoots straight down the valley.
  • Adaptive Optimizers (RMSProp, Adam) adjust your stride length independently for every compass direction—taking cautious, tiny steps along violently steep axes and bold, long strides along flat, gently sloping axes.

With that physical picture anchored, let us dissect the mathematics of the loss surface and each optimizer that navigates it.


3. Mathematical Formulation: Geometry of the Loss Landscape
#

Convexity and the Condition Number
#

Near any smooth minimum $w^*$, a second-order Taylor expansion approximates the objective function locally as a quadratic bowl governed by the Hessian matrix $H = \nabla^2 J(w^*)$:

$$J(w) \approx J(w^*) + \frac{1}{2} (w - w^*)^\top H (w - w^*)$$

Because $H$ is symmetric, its eigenvalues $\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d$ describe the curvature along each orthogonal principal axis. If every eigenvalue is strictly positive ($\lambda_i \gt 0$), the surface is strictly convex.

The convergence speed of vanilla gradient descent is governed by the condition number $\kappa$:

$$\kappa = \frac{\lambda_{\max}}{\lambda_{\min}}$$

To prevent the iterates from diverging along the steepest eigenvector ($\lambda_{\max}$), the learning rate must satisfy the strict stability bound:

$$\eta \lt \frac{2}{\lambda_{\max}}$$

Under the optimal fixed step size $\eta^* = \frac{2}{\lambda_{\max} + \lambda_{\min}}$, the worst-case error shrinks at each iteration by a factor of:

$$\frac{\kappa - 1}{\kappa + 1}$$

When $\kappa = 1$ (a perfect circular bowl), gradient descent converges in a single step. When $\kappa = 1000$ (an elongated ravine), the error shrinks by only $0.998$ per iteration—requiring thousands of zig-zagging steps to make modest progress.

The High-Dimensional Saddle Point Trap
#

In non-convex problems (such as neural networks), intuition from 2D plots suggests that optimization gets trapped in poor local minima. Dauphin et al. (2014) demonstrated mathematically and empirically that this intuition fails in high dimensions.

At any critical point where $\nabla J(w) = 0$:

  • A local minimum requires all $d$ eigenvalues of the Hessian to be positive.
  • A local maximum requires all $d$ eigenvalues to be negative.
  • A saddle point occurs whenever some eigenvalues are positive and some are negative.

If the sign of each eigenvalue were treated roughly like an independent coin flip at a high-error critical point, the probability of all $d$ eigenvalues being positive scales as $2^{-d}$. In a parameter space with $d = 10^6$ weights, nearly every stationary point encountered during training is a saddle point surrounded by flat plateaus where gradients approach zero, yet downward escape directions still exist.


4. Evolution of Iterative Optimizers
#

1. Stochastic & Mini-Batch Gradient Descent (SGD)
#

Building on the Stochastic Approximation framework of Robbins & Monro (1951), Mini-Batch SGD abandons exact full-dataset gradients. At step $t$, we draw a random mini-batch $\mathcal{B}_t \subset S$ of size $B \ll n$ and compute an unbiased stochastic gradient estimate:

$$g_t = \frac{1}{B} \sum_{i \in \mathcal{B}_t} \nabla_w L(h_{w_t}(x_i), y_i), \qquad \mathbb{E}[g_t] = \nabla_w J(w_t)$$$$w_{t+1} = w_t - \eta_t g_t$$

Replacing $n$ with $B$ (typically 32 to 4,096) delivers two critical advantages:

  • Orders-of-magnitude speedup: Computation per update becomes independent of total dataset size $n$.
  • Implicit Saddle-Point Escape: Because $g_t = \nabla J(w_t) + \xi_t$ carries zero-mean sampling noise $\xi_t$, SGD naturally jitters off flat saddle points where deterministic Batch GD would freeze.

The trade-off is asymptotic variance: with a constant learning rate $\eta$, SGD never settles at exact $w^*$, instead orbiting inside a noise ball whose radius scales with $\eta$. Exact convergence requires the Robbins–Monro schedule conditions:

$$\sum_{t=1}^{\infty} \eta_t = \infty \quad \text{and} \quad \sum_{t=1}^{\infty} \eta_t^2 \lt \infty$$

In modern practice, this motivates learning rate decay schedules (such as cosine annealing).


2. Polyak Momentum (The Heavy Ball Method)
#

Introduced by Boris Polyak (1964), Momentum maintains a velocity vector $v_t$ that accumulates an exponentially decaying history of past gradients:

$$v_t = \beta v_{t-1} + g_t$$$$w_{t+1} = w_t - \eta v_t$$

Here $\beta \in [0, 1)$ is the momentum coefficient (commonly $\beta = 0.9$). Expanding the recurrence reveals why it solves the ravine problem:

$$v_t = \sum_{k=0}^{t-1} \beta^k g_{t-k}$$
  • Along consistent valley directions (where $g_t \approx g$ keeps the same sign), the geometric series sums to a terminal velocity of $\frac{1}{1-\beta} g$—amplifying effective step size by 10× when $\beta = 0.9$.
  • Along oscillating canyon walls (where $g_t$ alternates sign), positive and negative terms cancel out, damping transverse oscillations.

Mathematically, Polyak proved that optimal momentum improves the worst-case contraction rate on strongly convex quadratics from $\frac{\kappa - 1}{\kappa + 1}$ down to $\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}$—turning a condition number of $\kappa = 1000$ into an effective $\sqrt{\kappa} \approx 31.6$.


3. Adaptive Learning Rates: AdaGrad and RMSProp
#

Momentum still applies the same scalar learning rate $\eta$ to every parameter coordinate. When some parameters receive frequent large gradients and others receive sparse small gradients, coordinate-wise scaling is needed.

AdaGrad (Duchi et al., 2011) tracks the cumulative sum of squared gradients per parameter (where $\odot$ denotes element-wise multiplication):

$$G_t = G_{t-1} + g_t \odot g_t, \qquad w_{t+1} = w_t - \frac{\eta}{\sqrt{G_t} + \epsilon} \odot g_t$$

Coordinates with historically large gradients get aggressively scaled down, while rare, sparse features retain larger steps. However, because $g_t \odot g_t \ge 0$, $G_t$ grows monotonically without bound—causing the effective learning rate to shrink prematurely toward zero in deep non-convex training.

RMSProp (proposed by Geoffrey Hinton in his 2012 Coursera lecture) fixes AdaGrad’s decay flaw by replacing the infinite sum with an Exponential Moving Average (EMA) of squared gradients:

$$s_t = \beta_2 s_{t-1} + (1 - \beta_2)(g_t \odot g_t), \qquad w_{t+1} = w_t - \frac{\eta}{\sqrt{s_t} + \epsilon} \odot g_t$$

By forgetting distant gradient history at rate $\beta_2$ (typically $0.99$ or $0.999$), RMSProp estimates the local root-mean-square magnitude of recent gradients without killing the step size.


4. Adam: Adaptive Moment Estimation
#

Diederik Kingma and Jimmy Ba (2015) unified Momentum (first moment / mean) and RMSProp (second raw moment / uncentered variance) into Adam (Adaptive Moment Estimation):

$$m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t \qquad \text{(1st moment estimate)}$$$$v_t = \beta_2 v_{t-1} + (1 - \beta_2) (g_t \odot g_t) \qquad \text{(2nd raw moment estimate)}$$

Why Bias Correction Matters
#

Both $m_0$ and $v_0$ are initialized to zero vectors. Unrolling $v_t$ explicitly shows a severe early-step distortion:

$$v_t = (1 - \beta_2) \sum_{i=1}^{t} \beta_2^{t-i} g_i^2$$

Taking the expectation (assuming roughly stationary gradient second moments $\mathbb{E}[g_i^2] \approx \mathbb{E}[g_t^2]$):

$$\mathbb{E}[v_t] \approx \mathbb{E}[g_t^2] (1 - \beta_2) \sum_{i=1}^{t} \beta_2^{t-i} = \mathbb{E}[g_t^2] (1 - \beta_2^t)$$

At step $t = 1$ with standard $\beta_2 = 0.999$, $(1 - \beta_2^1) = 0.001$—meaning $v_1$ underestimates the true squared gradient scale by a factor of 1,000×. Dividing by $\sqrt{v_1}$ without correction would trigger catastrophic early-step explosions.

Adam eliminates this initialization bias cleanly via exact bias-corrected moments:

$$\hat{m}_t = \frac{m_t}{1 - \beta_1^t}, \qquad \hat{v}_t = \frac{v_t}{1 - \beta_2^t}$$$$w_{t+1} = w_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}$$

Notice the scale-invariance property of Adam: if you multiply the entire loss function by 1,000, both $\hat{m}_t$ and $\sqrt{\hat{v}_t}$ scale by 1,000 and cancel out. Each parameter update behaves approximately like a smooth, signal-to-noise-ratio-bounded step of magnitude $\pm \eta$.


5. The Subtle Flaw in Adam + $L_2$: Decoupled Weight Decay (AdamW)
#

For years, practitioners implemented regularization in Adam exactly as they did in SGD—by adding an $L_2$ penalty $\frac{\lambda}{2}\Vert{}w\Vert{}_2^2$ directly to the loss function, turning the gradient into $g_t^{\text{reg}} = g_t + \lambda w_t$.

In vanilla SGD, $L_2$ regularization and multiplicative weight decay are algebraically identical:

$$w_{t+1} = w_t - \eta (g_t + \lambda w_t) = (1 - \eta \lambda) w_t - \eta g_t$$

Ilya Loshchilov and Frank Hutter (2019) proved that this equivalence breaks completely in adaptive optimizers like Adam.

When you inject $\lambda w_t$ into $g_t$ before computing Adam’s moments, the regularization term gets absorbed into $m_t$ and $v_t$ and subsequently divided by $\sqrt{\hat{v}_t} + \epsilon$:

$$\text{Effective decay in Adam+}L_2 \propto \frac{\eta \lambda}{\sqrt{\hat{v}_t} + \epsilon} w_t$$

This creates a pathological distortion:

  • Parameters with large historical gradients ($\sqrt{\hat{v}_t}$ large) receive weak regularization.
  • Parameters with tiny historical gradients ($\sqrt{\hat{v}_t}$ small) receive disproportionately aggressive shrinkage.
  • Tuning the learning rate $\eta$ entangles gradient optimization with regularization strength.

AdamW resolves this cleanly by decoupling weight decay from the adaptive gradient step:

  1. Compute $m_t, v_t, \hat{m}_t, \hat{v}_t$ using only the pure data-loss gradient $g_t = \nabla_w J(w_t)$.
  2. Apply multiplicative weight decay directly to the weights outside the adaptive denominator:
$$w_{t+1} = (1 - \eta \lambda) w_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}$$

Every weight now decays at a clean, predictable rate independent of its gradient variance. That single algebraic correction is why AdamW replaced standard Adam as the default optimizer for virtually all modern Transformer and Large Language Model training pipelines.


5. Learning Rate Schedules: Linear Warmup, Cosine Annealing & WSD
#

Even with AdamW adapting step sizes per coordinate, keeping the global base learning rate $\eta$ constant throughout training fails at scale. Recall the Robbins–Monro conditions from Section 4.1: exact asymptotic convergence under stochastic gradients requires $\sum_{t=1}^{\infty} \eta_t = \infty$ and $\sum_{t=1}^{\infty} \eta_t^2 \lt \infty$.

In deep neural networks and Large Language Models (LLMs), a static $\eta$ faces two opposing failure modes at opposite ends of training:

  • Early training is fragile: At random initialization, loss curvature is chaotic and adaptive second-moment estimates $v_t$ are statistically noisy. Launching immediately at peak $\eta_{\max}$ can cause irreversible divergence or lock attention heads into degenerate patterns.
  • Late training is noise-limited: Near a minimum, mini-batch gradient variance prevents parameters from settling. Keeping $\eta$ large forces the weights to bounce perpetually inside a high-loss noise ball instead of descending into the bottom of the basin.

Modern LLM training resolves this tension through a learning rate schedule $\eta(t)$—historically dominated by Linear Warmup + Cosine Annealing, and increasingly evolving toward Warmup–Stable–Decay (WSD).


5.1 Phase 1: Linear Warmup
#

During the first $T_{\text{warmup}}$ steps (typically ## 5. Summary Comparison of Optimizers.1%$ to $5%$ of total training steps), the learning rate ramps linearly from zero up to its peak value $\eta_{\max}$:

$\eta_t = \eta_{\max} \cdot \frac{t}{T_{\text{warmup}}}, \qquad 1 \le t \le T_{\text{warmup}}$

Originally popularized as an engineering heuristic for stabilizing large-batch ResNet training by Goyal et al. (2017), Linear Warmup rests on two concrete mathematical mechanisms in Transformer and LLM optimization:

  1. Taming Adaptive Denominator Variance (Liu et al., 2020): Even with Adam’s bias correction $\hat{v}_t = v_t / (1 - \beta_2^t)$, early iterations ($t \ll (1 - \beta_2)^{-1}$) estimate the second moment from only a tiny handful of mini-batches. Liu et al. (2020) proved that the variance of the adaptive scaling term $1 / \sqrt{\hat{v}_t}$ is unbounded in the earliest steps, causing erratic, oversized updates before $v_t$ stabilizes. Linear warmup suppresses step magnitudes precisely while the optimizer gathers enough gradient history to make $\hat{v}_t$ statistically reliable.
  2. Surviving Sharp Initial Curvature & Transformer Gradients (Xiong et al., 2020): At initialization, weights sit in high-curvature regions where gradients fluctuate wildly across layers. Xiong et al. (2020) showed analytically that in Post-LN Transformers, expected gradient norms near the output layer are disproportionately large at step zero; without warmup, early updates shatter representation stability. Even in modern Pre-LN Transformers (which dramatically improve gradient flow), warmup remains essential at billion-parameter scales to prevent early loss spikes.

5.2 Phase 2: Cosine Annealing
#

Once warmup completes at step $T_{\text{warmup}}$, the learning rate must decay so the optimizer transitions from broad exploration to fine-grained convergence.

Introduced by Loshchilov & Hutter (2017) in SGDR (Stochastic Gradient Descent with Warm Restarts), Cosine Annealing decays the learning rate along a smooth half-cosine curve from $\eta_{\max}$ down to a floor $\eta_{\min}$ over the remaining training horizon $T_{\text{total}}$:

$\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min}) \left( 1 + \cos\left( \pi \frac{t - T_{\text{warmup}}}{T_{\text{total}} - T_{\text{warmup}}} \right) \right), \qquad T_{\text{warmup}} \lt t \le T_{\text{total}}$

In LLM pre-training, the periodic “restarts” from the original SGDR paper are almost always dropped in favor of a single cosine decay cycle, with the terminal floor typically set to $\eta_{\min} = 0.1\,\eta_{\max}$ (rather than ## 5. Summary Comparison of Optimizers$) so parameters remain responsive on the final tokens.

Why the Cosine Shape Works
#

Define normalized decay progress $u = \frac{t - T_{\text{warmup}}}{T_{\text{total}} - T_{\text{warmup}}} \in [0, 1]$. Taking the derivative with respect to progress reveals three distinct dynamical phases:

$\frac{d\eta}{du} = -\frac{\pi}{2}(\eta_{\max} - \eta_{\min}) \sin(\pi u)$

  • Prolonged High-Energy Exploration ($u \approx 0$): Because $\sin(\pi u) \approx 0$, the learning rate barely drops right after warmup, giving AdamW sustained momentum to traverse broad plateaus and escape sharp basins.
  • Rapid Transition ($u \approx 0.5$): The slope hits its steepest negative value, aggressively shrinking the stochastic noise ball as the model locks onto a promising loss valley.
  • Gentle Final Settling ($u \approx 1$): The slope flattens again as $\eta_t \to \eta_{\min}$, allowing fine-grained convergence without abruptly freezing optimization too early.

The Chinchilla Sensitivity Finding
#

In DeepMind’s Chinchilla scaling study, Hoffmann et al. (2022) revealed a strict operational requirement of Cosine Annealing: the cosine cycle length $T_{\text{total}}$ must tightly match the actual training token budget. If you configure a cosine schedule for 100B tokens but stop training at 75B tokens, the learning rate has not decayed sufficiently, leaving substantial validation loss on the table compared to a schedule properly calibrated to 75B tokens.


5.3 The Modern LLM Shift: Warmup–Stable–Decay (WSD)
#

That exact horizon sensitivity exposes the major engineering limitation of Cosine Annealing in frontier LLM pre-training: you must commit to $T_{\text{total}}$ before step 1.

If an organization trains a model on 4 trillion tokens using Cosine Annealing and later acquires 2 trillion additional high-quality tokens, continuing pre-training from the final checkpoint is awkward—the learning rate has already collapsed to $\eta_{\min}$, and re-warming it often triggers destabilizing loss spikes.

To remove this rigid horizon lock-in, recent LLM training pipelines—popularized by MiniCPM (Hu et al., 2024) and rigorously analyzed by Hägele et al. (2024)—adopt the Warmup–Stable–Decay (WSD) (or trapezoidal) schedule:

$\eta_t = \begin{cases} \eta_{\max} \cdot \dfrac{t}{T_{\text{warmup}}}, & 1 \le t \le T_{\text{warmup}} \quad \text{(Warmup)} \\ \eta_{\max}, & T_{\text{warmup}} \lt t \le T_{\text{decay}} \quad \text{(Stable Plateau)} \\ \eta_{\min} + (\eta_{\max} - \eta_{\min}) \cdot f_{\text{decay}}\!\left(\dfrac{t - T_{\text{decay}}}{T_{\text{total}} - T_{\text{decay}}}\right), & T_{\text{decay}} \lt t \le T_{\text{total}} \quad \text{(Cooldown)} \end{cases}$

where $f_{\text{decay}}(s)$ typically uses linear decay $(1 - s)$ or inverse square-root decay $(1 - \sqrt{s})$ over the final 10% to 20% of training steps.

WSD delivers two decisive advantages over Cosine Annealing:

  1. Infinite Continual Pre-Training: Because the model spends 80–90% of its life on a constant $\eta_{\max}$ plateau, researchers can keep training indefinitely on new data streams and trigger a fast cooldown branch from any intermediate checkpoint whenever they want to ship a release.
  2. Matching Performance & Annealing Synergy: Hägele et al. (2024) demonstrated across scaling-law experiments that WSD matches or outperforms fully tuned Cosine schedules without knowing $T_{\text{total}}$ in advance. In modern LLM recipes, the rapid cooldown phase is often paired with a data quality upshift (math, code, and curated reasoning corpora), yielding sharp late-stage benchmark gains.

5.4 Schedule Comparison
#

Schedule Functional Form Knows $T_{\text{total}}$ Upfront? Primary Strength Key Limitation
Constant $\eta$ $\eta_t = \eta_0$ No Simplest baseline; easy to resume Early divergence if too high; trapped in noise ball if never cooled
Step Decay Drops by factor $\gamma$ at fixed milestones Yes Clean, predictable drops (classic CNN standard) Requires manual milestone tuning; abrupt loss jolts
Warmup + Cosine Linear ramp + half-cosine to $\eta_{\min}$ Yes (strictly) Smooth exploration-to-convergence curve; battle-tested across LLMs Cannot cheaply extend training past $T_{\text{total}}$ without re-warmup
WSD (Trapezoidal) Linear ramp + constant plateau + fast cooldown No (until cooldown) Supports continual training & cheap multi-horizon scaling laws Validation loss looks artificially high until the cooldown branch runs

5.5 Minimal Implementation: Warmup + Cosine vs. WSD in NumPy
#

The snippet below implements both Linear Warmup + Cosine Annealing and WSD from scratch, then compares Constant LR, Cosine (No Warmup), Warmup + Cosine, and WSD on a noisy, ill-conditioned objective initialized with an early gradient shock (simulating early Transformer variance).

import numpy as np

def warmup_cosine_lr(
    step: int,
    total_steps: int,
    warmup_steps: int,
    lr_max: float,
    lr_min: float = 0.0,
) -> float:
    if step <= warmup_steps:
        return lr_max * (step / max(1, warmup_steps))
    progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
    progress = min(max(progress, 0.0), 1.0)
    return lr_min + 0.5 * (lr_max - lr_min) * (1.0 + np.cos(np.pi * progress))

def wsd_lr(
    step: int,
    total_steps: int,
    warmup_steps: int,
    decay_steps: int,
    lr_max: float,
    lr_min: float = 0.0,
) -> float:
    decay_start = total_steps - decay_steps
    if step <= warmup_steps:
        return lr_max * (step / max(1, warmup_steps))
    if step <= decay_start:
        return lr_max
    progress = (step - decay_start) / max(1, decay_steps)
    progress = min(max(progress, 0.0), 1.0)
    # 1 - sqrt(progress) cooldown curve (Hagele et al., 2024)
    return lr_min + (lr_max - lr_min) * (1.0 - np.sqrt(progress))

# =====================================================================
# Noisy Ill-Conditioned Quadratic + Early Gradient Shock Benchmark
# J(w) = 0.5 * (w0^2 + 50 * w1^2), observed with stochastic gradient noise
# =====================================================================
def run_schedule_experiment(schedule_name: str, lr_fn, total_steps: int = 400):
    rng = np.random.default_rng(123)
    H_diag = np.array([1.0, 50.0])
    w = np.array([8.0, 4.0])
    m, v = np.zeros(2), np.zeros(2)
    b1, b2, eps, lam = 0.9, 0.99, 1e-8, 0.01

    for t in range(1, total_steps + 1):
        # Simulate noisy early-step gradient instability + steady mini-batch noise
        noise_scale = 25.0 if t <= 15 else 2.5
        grad_noise = rng.normal(0.0, noise_scale, size=2)
        g = H_diag * w + grad_noise

        eta = lr_fn(t)

        # AdamW update with scheduled learning rate
        m = b1 * m + (1.0 - b1) * g
        v = b2 * v + (1.0 - b2) * (g ** 2)
        m_hat = m / (1.0 - b1 ** t)
        v_hat = v / (1.0 - b2 ** t)
        w = (1.0 - eta * lam) * w - eta * m_hat / (np.sqrt(v_hat) + eps)

    final_loss = float(0.5 * np.sum(H_diag * (w ** 2)))
    print(f"{schedule_name:<22} | Final Loss: {final_loss:.6f} | w = {np.round(w, 4)}")

T = 400
LR_MAX = 0.25
LR_MIN = 0.025  # 0.1 * LR_MAX

print("=== Learning Rate Schedule Comparison under AdamW (400 steps) ===")
run_schedule_experiment("Constant High LR", lambda t: LR_MAX, T)
run_schedule_experiment(
    "Cosine (No Warmup)", lambda t: warmup_cosine_lr(t, T, 0, LR_MAX, LR_MIN), T
)
run_schedule_experiment(
    "Warmup + Cosine", lambda t: warmup_cosine_lr(t, T, 40, LR_MAX, LR_MIN), T
)
run_schedule_experiment(
    "WSD (1-sqrt decay)", lambda t: wsd_lr(t, T, 40, 80, LR_MAX, LR_MIN), T
)

Interpreting the Behavior
#

Three patterns stand out immediately when running this benchmark:

  1. Constant High LR descends quickly at first, then orbits inside a noisy residual floor because its step size never shrinks below the gradient variance scale.
  2. Cosine (No Warmup) takes aggressive updates during the noisy first 15 steps while Adam’s second-moment accumulator $v_t$ is still uncalibrated, throwing weights off-trajectory before recovery begins.
  3. Warmup + Cosine and WSD both absorb the early gradient shock smoothly during the first 40 warmup steps, travel rapidly across the flat $w_0$ axis at full $\eta_{\max}$, and then cool down cleanly into the bottom of the valley—achieving dramatically lower final loss.

Optimizer trajectories on an ill-conditioned ravine and learning rate schedules

Figure 3. Left: Vanilla GD, Momentum, and Adam racing down an ill-conditioned ravine (kappa = 30). Right: constant LR vs. Linear Warmup + Cosine Annealing vs. WSD.

6. Summary Comparison of Optimizers
#

Optimizer Core Mechanism Memory Overhead (per param) Primary Strength Key Failure Mode / Limitation
Batch GD Exact full-dataset gradient $0$ Guaranteed monotonic descent on smooth convex surfaces Prohibitive $O(n)$ step cost; stalls on saddle points
Mini-Batch SGD Unbiased noisy gradient over batch $B$ $0$ Fast $O(B)$ updates; noise escapes saddle points; strong generalization Oscillates violently in high-$\kappa$ ravines; sensitive to feature scaling
SGD + Momentum EMA velocity accumulation ($\beta$) $1\times$ ($v_t$) Cancels orthogonal oscillations; accelerates flat valleys ($\kappa \to \sqrt{\kappa}$) Shared scalar $\eta$ still struggles across mismatched parameter scales
AdaGrad Cumulative squared gradient scaling $1\times$ ($G_t$) Excels on sparse tabular/NLP features Monotonic $G_t$ kills learning rate permanently in long runs
RMSProp EMA of squared gradients ($\beta_2$) $1\times$ ($s_t$) Adapts to local curvature without dying learning rate Lacks momentum smoothing and early-step bias correction
Adam 1st + 2nd EMA moments + bias correction $2\times$ ($m_t, v_t$) Fast, robust convergence across scales with minimal tuning Coupled $L_2$ regularization distorts weight shrinkage; higher memory
AdamW Adam + decoupled multiplicative weight decay $2\times$ ($m_t, v_t$) Clean, scale-invariant regularization; standard for Transformers/LLMs $2\times$ optimizer state memory (a bottleneck for multi-billion parameter models)

7. Minimal Implementation: Ravine Race & The Adam vs. AdamW Contrast
#

The NumPy script below verifies two central theoretical claims directly from scratch:

  1. Part A (Ravine Dynamics): Racing Vanilla SGD, SGD + Polyak Momentum, and Adam on an ill-conditioned 2D quadratic canyon $J(w_1, w_2) = \frac{1}{2}(w_1^2 + 100 w_2^2)$ with condition number $\kappa = 100$.
  2. Part B (Coupled $L_2$ vs. Decoupled Weight Decay): Comparing Adam + $L_2$ against AdamW on two weights subjected to zero-mean oscillating gradients whose scales differ by 1,000× ($100.0$ vs. $0.1$).
import numpy as np

# =====================================================================
# PART A: Ill-Conditioned Ravine — J(w) = 0.5 * (w0^2 + 100 * w1^2)
# Condition number kappa = 100; SGD stability limit is lr < 2/100 = 0.02
# =====================================================================
H_diag = np.array([1.0, 100.0])

def ravine_loss(w: np.ndarray) -> float:
    return float(0.5 * np.sum(H_diag * (w ** 2)))

def ravine_grad(w: np.ndarray) -> np.ndarray:
    return H_diag * w

w_init = np.array([10.0, 2.0])
n_steps = 150

# 1. Vanilla SGD (lr near stability ceiling to move as fast as safely possible)
w_sgd = w_init.copy()
for _ in range(n_steps):
    w_sgd -= 0.018 * ravine_grad(w_sgd)

# 2. SGD + Polyak Momentum (beta = 0.9)
w_mom = w_init.copy()
v_mom = np.zeros_like(w_mom)
for _ in range(n_steps):
    v_mom = 0.9 * v_mom + ravine_grad(w_mom)
    w_mom -= 0.018 * v_mom

# 3. Adam (beta1 = 0.9, beta2 = 0.999, eps = 1e-8)
w_adam = w_init.copy()
m = np.zeros_like(w_adam)
v = np.zeros_like(w_adam)
b1, b2, eps = 0.9, 0.999, 1e-8
for t in range(1, n_steps + 1):
    g = ravine_grad(w_adam)
    m = b1 * m + (1.0 - b1) * g
    v = b2 * v + (1.0 - b2) * (g ** 2)
    m_hat = m / (1.0 - b1 ** t)
    v_hat = v / (1.0 - b2 ** t)
    w_adam -= 0.25 * m_hat / (np.sqrt(v_hat) + eps)

print("=== PART A: Ill-Conditioned Ravine (kappa = 100, 150 steps) ===")
print(f"Initial Loss : {ravine_loss(w_init):.4f}  | w = {w_init}")
print(f"Vanilla SGD  : {ravine_loss(w_sgd):.6f} | w = {np.round(w_sgd, 4)}")
print(f"SGD+Momentum : {ravine_loss(w_mom):.6f} | w = {np.round(w_mom, 4)}")
print(f"Adam         : {ravine_loss(w_adam):.6f} | w = {np.round(w_adam, 4)}\n")

# =====================================================================
# PART B: Why Adam + L2 != AdamW under Mismatched Gradient Scales
# Two parameters start at w = [5.0, 5.0] under zero-mean oscillating
# gradients of amplitude [100.0, 0.1] and decay coefficient lam = 0.5
# =====================================================================
lr = 0.01
lam = 0.5
grad_scales = np.array([100.0, 0.1])

w_adam_l2 = np.array([5.0, 5.0])
m_l2, v_l2 = np.zeros(2), np.zeros(2)

w_adamw = np.array([5.0, 5.0])
m_w, v_w = np.zeros(2), np.zeros(2)

for t in range(1, 201):
    g_data = ((-1.0) ** t) * grad_scales  # Pure zero-mean oscillating gradient

    # --- Adam + Coupled L2 Regularization ---
    g_reg = g_data + lam * w_adam_l2
    m_l2 = b1 * m_l2 + (1.0 - b1) * g_reg
    v_l2 = b2 * v_l2 + (1.0 - b2) * (g_reg ** 2)
    m_l2_hat = m_l2 / (1.0 - b1 ** t)
    v_l2_hat = v_l2 / (1.0 - b2 ** t)
    w_adam_l2 -= lr * m_l2_hat / (np.sqrt(v_l2_hat) + eps)

    # --- AdamW (Decoupled Weight Decay) ---
    m_w = b1 * m_w + (1.0 - b1) * g_data
    v_w = b2 * v_w + (1.0 - b2) * (g_data ** 2)
    m_w_hat = m_w / (1.0 - b1 ** t)
    v_w_hat = v_w / (1.0 - b2 ** t)
    w_adamw = (1.0 - lr * lam) * w_adamw - lr * m_w_hat / (np.sqrt(v_w_hat) + eps)

expected_decay = 5.0 * ((1.0 - lr * lam) ** 200)
print("=== PART B: Adam + L2 vs. AdamW (200 steps, lam=0.5, lr=0.01) ===")
print(f"Theoretical uniform decay target : [{expected_decay:.3f}, {expected_decay:.3f}]")
print(f"Adam + L2 weights [big_g, small_g]: {np.round(w_adam_l2, 3)}")
print(f"AdamW     weights [big_g, small_g]: {np.round(w_adamw, 3)}")

Interpreting the Behavior
#

Running this script exposes both core mechanics cleanly:

  1. Ravine Collapse (Part A): Even with its learning rate pushed right against the stability ceiling (0.018), Vanilla SGD still ends with a noticeable residual loss along the flat axis $w_0$ because it cannot step aggressively without exploding along $w_1$. Polyak Momentum slashes the loss by several orders of magnitude using the exact same learning rate, while Adam equalizes the curvature across both coordinates and reaches the origin cleanly.
  2. Regularization Asymmetry (Part B): Because both weights start at 5.0 under pure zero-mean gradient noise, uniform weight decay should shrink both symmetrically toward ~1.835. AdamW hits [1.835, 1.835] cleanly. Adam + $L_2$, however, barely shrinks the large-gradient coordinate (remaining near 4.95) while aggressively shrinking the small-gradient coordinate (down near ~3.0)—proving numerically how coupled $L_2$ breaks down inside adaptive denominators.

8. Limitations & Bridge to Part 4
#

Optimizers like SGD, Momentum, and AdamW solve empirical risk minimization—finding parameters that drive training loss $\hat{R}_n(w)$ downward quickly and reliably.

Yet fast optimization is a double-edged sword. An aggressive optimizer paired with a flexible model can drive training loss to zero while producing catastrophic test error—or, surprisingly in modern overparameterized models, continue improving test error after training loss hits zero.

In Part 4: Generalization, Bias–Variance Tradeoff & The Double Descent Phenomenon, we will dissect the mathematical anatomy of generalization error, compare the geometry of $L_1$ vs. $L_2$ regularization, and examine how modern research reconciles classical bias–variance theory with the Double Descent regime that governs overparameterized AI systems.


References
#

  1. Robbins, H., & Monro, S. (1951). “A Stochastic Approximation Method.” The Annals of Mathematical Statistics, 22(3), 400–407. (Theoretical foundation of Stochastic Gradient Descent).
  2. Polyak, B. T. (1964). “Some Methods of Speeding Up the Convergence of Iteration Methods.” USSR Computational Mathematics and Mathematical Physics, 4(5), 1–17. (Original formulation of the Heavy Ball / Momentum method).
  3. Duchi, J., Hazan, E., & Singer, Y. (2011). “Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.” Journal of Machine Learning Research (JMLR), 12(61), 2121–2159. (AdaGrad).
  4. Dauphin, Y. N., Pascanu, R., Gulcehre, C., Cho, K., Ganguli, S., & Bengio, Y. (2014). “Identifying and Attacking the Saddle Point Problem in High-Dimensional Non-Convex Optimization.” Advances in Neural Information Processing Systems (NeurIPS 2014).
  5. Kingma, D. P., & Ba, J. (2015). “Adam: A Method for Stochastic Optimization.” International Conference on Learning Representations (ICLR 2015). arXiv:1412.6980.
  6. Loshchilov, I., & Hutter, F. (2019). “Decoupled Weight Decay Regularization.” International Conference on Learning Representations (ICLR 2019). arXiv:1711.05101. (AdamW).
  7. Goyal, P., Dollár, P., Girshick, R., Noordhuis, P., Wesolowski, L., Kyrola, A., Tulloch, A., Jia, Y., & He, K. (2017). “Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour.” arXiv:1706.02677. (Linear scaling rule and gradual warmup).
  8. Loshchilov, I., & Hutter, F. (2017). “SGDR: Stochastic Gradient Descent with Warm Restarts.” International Conference on Learning Representations (ICLR 2017). arXiv:1608.03983. (Cosine Annealing).
  9. Liu, L., Jiang, H., He, P., Chen, W., Liu, X., Gao, J., & Han, J. (2020). “On the Variance of the Adaptive Learning Rate and Beyond.” International Conference on Learning Representations (ICLR 2020). arXiv:1908.03265. (Mathematical proof of early-step adaptive variance and why warmup stabilizes Adam).
  10. Xiong, R., Yang, Y., He, D., Zheng, K., Zheng, S., Xing, C., Zhang, H., Lan, Y., Wang, L., & Liu, T.-Y. (2020). “On Layer Normalization in the Transformer Architecture.” International Conference on Machine Learning (ICML 2020). arXiv:2002.04745. (Analysis of warmup and gradient norms in Post-LN vs. Pre-LN Transformers).
  11. Hoffmann, J., Borgeaud, S., Mensch, A., et al. (2022). “Training Compute-Optimal Large Language Models.” Advances in Neural Information Processing Systems (NeurIPS 2022). arXiv:2203.15556. (Chinchilla empirical findings on matching cosine decay length to token budget).
  12. Hu, S., Tu, Y., Han, X., et al. (2024). “MiniCPM: Unveiling the Potential of Small Language Models with Scalable Training Strategies.” arXiv:2404.06395. (Warmup–Stable–Decay schedule in LLM training).
  13. Hägele, A., Bakouch, E., Kosson, A., Allal, L. B., Von Werra, L., & Jaggi, M. (2024). “Scaling Laws and Compute-Optimal Training Beyond Fixed Training Durations.” Advances in Neural Information Processing Systems (NeurIPS 2024). arXiv:2405.18392. (Systematic analysis of WSD vs. Cosine Annealing and $1 - \sqrt{s}$ cooldown).
Machine Learning Fundamentals - This article is part of a series.
Part 3: This Article