Backpropagation Calculus and Modern Deep Learning Optimizers

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.

The Computational Graph & Forward Pass

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} ).

The Calculus of Backpropagation: Reverse-Mode Autodiff

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:

( rac{partial mathcal{L}}{partial mathbf{W}^{(l)}} = rac{partial mathcal{L}}{partial mathbf{z}^{(l)}} imes rac{partial mathbf{z}^{(l)}}{partial mathbf{W}^{(l)}} = oldsymbol{delta}^{(l)} (mathbf{a}^{(l-1)})^T )

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!

Evolution of Deep Learning Optimizers

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.

Learning Rate Scheduling

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:

  • Warmup: Starting with a tiny learning rate for the first 1,000 steps and ramping up linearly to prevent early parameter destruction.
  • Cosine Annealing: Decaying the learning rate following a cosine curve: ( eta_t = eta_{min} + rac{1}{2}(eta_{max} - eta_{min})(1 + cos(pi t / T)) ).

PyTorch Implementation: Using AdamW with Cosine Annealing

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}")

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is AdamW preferred over original Adam in Transformer training?

In original Adam, L2 regularization was added directly to the gradient. Because Adam divides gradients by the square root of the second moment (RMSprop), weights with large historical gradients received less weight decay than weights with small gradients. AdamW decouples weight decay directly from gradient updates, restoring true exponential weight decay and dramatically improving generalization in LLMs.

Q2. What is Gradient Clipping and why is it used?

Gradient Clipping caps the maximum norm of gradients (e.g., torch.nn.utils.clip_grad_norm_(parameters, max_norm=1.0)) during backpropagation. It prevents the 'Exploding Gradient' problem in deep recurrent networks and transformers, where a sudden massive gradient spike causes weights to update wildly into NaN values.

Q3. Why do we call optimizer.zero_grad() in PyTorch before loss.backward()?

In PyTorch, gradients are accumulated by default (added to existing tensors: param.grad += new_grad) to allow computing gradients across multiple mini-batches before stepping. Calling optimizer.zero_grad() resets existing gradients to zero, preventing gradients from past batches from contaminating the current step.

Q4. What is the role of the learning rate warmup phase?

At the start of training, model weights are random, producing chaotic and unreliable initial gradients. Jumping straight to a high learning rate can knock the model into a bad local minimum from which it cannot recover. Warmup starts with a near-zero learning rate for the first few thousand steps, giving the optimizer time to stabilize its momentum buffers.

Explore Related Artificial Intelligence Tutorials & Next Steps

Broaden your foundational and advanced AI knowledge across our curriculum:

Neural Networks & Perceptrons

Forward activations, loss functions, and weight matrices.

Convolutional Networks (CNN)

Backpropagating through convolutional filters and pooling layers.

Debugging & Troubleshooting AI

Fixing vanishing and exploding gradients, dead ReLUs, and learning rate spikes.

120+ AI Technical Interview Q&A

Math derivation of backpropagation and momentum in Adam optimizer.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!