A neural network with millions or billions of parameters begins with randomly initialized weights. How does it learn the exact values that transform raw image pixels into category labels or generate coherent human prose? The answer is Backpropagation (the backward propagation of errors via the multivariable calculus chain rule) combined with modern Optimization Algorithms.
Modern deep learning frameworks (PyTorch, TensorFlow) represent mathematical computations as a directed Computation Graph. During the Forward Pass, operations are evaluated from left to right, saving intermediate activation tensors in GPU memory to calculate the final scalar Loss ( mathcal{L} ).
Backpropagation uses reverse-mode automatic differentiation. To compute how much a specific weight matrix ( mathbf{W}^{(l)} ) at layer ( l ) contributed to the final loss ( mathcal{L} ), we apply the Multivariable Calculus Chain Rule backward from output to input:
Where the error term ( oldsymbol{delta}^{(l)} = rac{partial mathcal{L}}{partial mathbf{z}^{(l)}} = left( (mathbf{W}^{(l+1)})^T oldsymbol{delta}^{(l+1)} ight) odot sigma'(mathbf{z}^{(l)}) ).
Because the error signal ( oldsymbol{delta}^{(l+1)} ) is computed once at layer ( l+1 ) and reused for all neurons at layer ( l ), backpropagation achieves a stunning computational efficiency: computing gradients for all parameters in a network takes the exact same asymptotic time complexity ( O(W) ) as a single forward evaluation!
| Optimizer | Key Mathematical Formula | Mechanism & Tradeoffs |
|---|---|---|
| Standard SGD | ( heta_{t+1} = heta_t - eta abla mathcal{L}( heta_t) ) | Steps blindly along the negative gradient. Struggles in ravines with high curvature; oscillates wildly across steep ravines while making minimal progress along gentle slopes. |
| SGD with Momentum | ( v_t = gamma v_{t-1} + eta
abla mathcal{L}( heta_t) ) ( heta_{t+1} = heta_t - v_t ) |
Simulates physical momentum (heavy ball rolling downhill). Averages past velocity ( v_t ) to dampen perpendicular oscillations and accelerate along consistent directional gradients. |
| RMSprop (Hinton, 2012) | ( s_t = eta s_{t-1} + (1 - eta) g_t^2 ) ( heta_{t+1} = heta_t - rac{eta}{sqrt{s_t} + epsilon} g_t ) |
Maintains an exponential moving average of squared gradients ( s_t ). Adapts the learning rate individually per parameter: divides by ( sqrt{s_t} ), slowing down steep directions and speeding up flat ones. |
| Adam (Kingma & Ba, 2014) | Combines First Moment (Momentum: ( m_t )) and Second Moment (RMSprop: ( v_t )) with bias-correction factors: ( hat{m}_t = rac{m_t}{1 - eta_1^t} ), ( hat{v}_t = rac{v_t}{1 - eta_2^t} ) | The Industry Standard for General Deep Learning. Default parameters ( eta_1 = 0.9, eta_2 = 0.999, epsilon = 10^{-8} ). Fast convergence, highly robust to sparse gradients. |
| AdamW (Loshchilov & Hutter, 2017) | Decoupled Weight Decay: ( heta_{t+1} = heta_t - eta rac{hat{m}_t}{sqrt{hat{v}_t} + epsilon} - eta lambda heta_t ) | The Standard Optimizer for Transformers & Modern LLMs. Fixes a mathematical flaw in original Adam where L2 regularization was scaled by ( 1/sqrt{v_t} ), restoring proper weight decay generalization. |
Keeping the learning rate ( eta ) constant throughout training leads to suboptimal results: large early on leads to fast progress, but later prevents fine convergence into narrow loss minima. Modern training utilizes:
The following snippet demonstrates configuring AdamW with decoupled weight decay and a warmup cosine scheduler in PyTorch:
import torch
import torch.nn as nn
from torch.optim import AdamW
from torch.optim.lr_scheduler import CosineAnnealingLR
# Simple model
model = nn.Sequential(
nn.Linear(128, 64),
nn.GELU(),
nn.Linear(64, 10)
)
# 1. Configure AdamW with decoupled weight decay
optimizer = AdamW(
model.parameters(),
lr=5e-4, # Peak learning rate
betas=(0.9, 0.999), # First and second moment decays
weight_decay=0.01, # True decoupled weight decay
eps=1e-8
)
# 2. Configure Cosine Annealing Learning Rate Scheduler
epochs = 50
scheduler = CosineAnnealingLR(optimizer, T_max=epochs, eta_min=1e-6)
print(f"Initial Learning Rate: {optimizer.param_groups[0]['lr']}")
for epoch in range(1, 6):
# Simulated training step
optimizer.step()
scheduler.step()
print(f"Epoch {epoch:2d} -> Updated Learning Rate: {optimizer.param_groups[0]['lr']:.6f}")
Broaden your foundational and advanced AI knowledge across our curriculum:
Forward activations, loss functions, and weight matrices.
Backpropagating through convolutional filters and pooling layers.
Fixing vanishing and exploding gradients, dead ReLUs, and learning rate spikes.
Math derivation of backpropagation and momentum in Adam optimizer.