Step 2 of 6

Backpropagation & gradient flow

How gradients flow backward through a computation graph, why vanishing and exploding gradients happen, and the practical tricks (batch norm, residual connections, careful initialization) that tame them.

18 min read

A neural network can have millions of parameters. To train it, you need the gradient of the loss with respect to every single one. Backpropagation computes all of them in a single backward pass - and understanding it means understanding why certain architectures train well and others don't.

The computational graph#

A neural network is a directed acyclic graph of operations. Each node is a simple function (multiply, add, apply activation), and data flows forward through the graph to produce a prediction and a loss:

  1. 01Forward pass: compute predictions layer by layer
  2. 02Compute loss at the output
  3. 03Backward pass: propagate gradients from loss to every parameter
  4. 04Update: adjust parameters using the gradients

The key insight: every operation in the graph has a local derivative - how its output changes with respect to its inputs. The chain rule chains these local derivatives together to get the gradient of the loss with respect to any parameter in the network.

3Blue1Brown's visual walkthrough of how backpropagation uses the chain rule to compute gradients.

The chain rule in action#

Consider a simple two-layer network: h = σ(W₁x + b₁), ŷ = W₂h + b₂, and loss L = (y − ŷ)².

To find ∂L/∂W₁ (how the loss changes with the first layer's weights), the chain rule says:

∂L∂W1=∂L∂y^⋅∂y^∂h⋅∂h∂W1\frac{\partial L}{\partial \mathbf{W}_1} = \frac{\partial L}{\partial \hat{\mathbf{y}}} \cdot \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{h}} \cdot \frac{\partial \mathbf{h}}{\partial \mathbf{W}_1}

The chain rule decomposes the gradient through each operation: loss → output → hidden → weights.

Each factor is a local derivative:

  • ∂L/∂ŷ = −2(y − ŷ) - how the loss changes with the prediction
  • ∂ŷ/∂h = W₂ - how the output changes with the hidden state
  • ∂h/∂W₁ = σ′(W₁x + b₁) · x - how the hidden state changes with the weights

Multiply them together and you have the gradient. Do this for every parameter and you have everything needed to update the network.

The calculus details: how each partial derivative is computed and chained together.

Why backpropagation is efficient#

A naive approach would compute the gradient of each parameter independently - one forward pass per parameter. For a network with N parameters, that's N forward passes. Backpropagation does it in one forward pass + one backward pass, regardless of N.

The trick: reverse-mode automatic differentiation. Instead of tracing from each parameter forward to the loss, it traces from the loss backward to all parameters simultaneously. At each node, it computes the local gradient and passes it backward to all parents.

Vanishing and exploding gradients#

As gradients flow backward through many layers, they're multiplied by each layer's Jacobian. This repeated multiplication can cause problems:

Vanishing gradients: if each layer's gradient is < 1, the product shrinks exponentially. After 50 layers, a gradient of 0.9⁵⁰ ≈ 0.005 - the early layers barely learn. This was the fundamental problem with sigmoid and tanh activations in deep networks.

Exploding gradients: if each layer's gradient is > 1, the product grows exponentially. Weights oscillate wildly and training diverges.

ProblemCauseSolutions
VanishingSigmoid/tanh saturation, deep networksReLU activation, residual connections, normalization
ExplodingLarge weight initialization, unstable dynamicsGradient clipping, careful initialization, normalization

Residual connections - the gradient highway#

Residual connections (skip connections) solve vanishing gradients by adding a shortcut:

output=x+F(x)\text{output} = \mathbf{x} + F(\mathbf{x})

Residual block: the output is the input plus the layer's transformation. The gradient flows through the shortcut undiminished.

During backpropagation, the gradient flows through two paths: through the transformation F(x) (which can vanish) and through the identity shortcut (which passes the gradient through unchanged). The shortcut ensures gradients always reach the early layers.

This is why ResNet (2015) could train 152-layer networks when previous architectures struggled beyond 20. Every modern transformer uses residual connections around both the attention and MLP blocks.

Batch normalization#

Batch normalization normalizes the activations within each mini-batch to have zero mean and unit variance, then applies a learned scale and shift:

h^=h−μbatchσbatch2+εoutput=γh^+β\hat{h} = \frac{h - \mu_{\text{batch}}}{\sqrt{\sigma^2_{\text{batch}} + \varepsilon}} \qquad \text{output} = \gamma\hat{h} + \beta

BatchNorm: normalize activations, then apply learnable scale γ and shift β.

This stabilizes training by keeping activations in a well-behaved range, reducing internal covariate shift. It also acts as a mild regularizer (the noise from batch statistics). Layer normalization (used in transformers) normalizes across features instead of across the batch, making it independent of batch size.

Weight initialization#

Bad initialization can doom training before it starts. The goal: keep activations and gradients in a reasonable range across all layers.

MethodRuleUse with
Xavier/GlorotW ~ N(0, 2/(fan_in + fan_out))Sigmoid, tanh
He/KaimingW ~ N(0, 2/fan_in)ReLU and variants

These ensure that the variance of activations stays roughly constant through the network. Modern frameworks default to one of these - you rarely need to think about it, but understanding why matters when training goes wrong.

Xavier / Glorot initialization
Sets initial weights based on fan-in and fan-out so activations neither explode nor vanish - designed for sigmoid and tanh activations.
He / Kaiming initialization
Like Xavier but accounts for ReLU zeroing out half the outputs - the standard initialization for ReLU-based networks.
Fan-in / Fan-out
Fan-in is the number of inputs to a layer, fan-out is the number of outputs - initialization methods use these to scale the initial weight variance.

Where it shows up in ML#

Autograd does backprop for you

PyTorch, JAX, and TensorFlow implement reverse-mode autodiff - you define the forward pass, the framework computes gradients automatically.

Residual connections are everywhere

ResNets, transformers, U-Nets, diffusion models - any deep architecture uses skip connections to ensure gradient flow.

Layer norm stabilizes transformers

Pre-layer-norm (normalize before attention/MLP) is now standard in LLMs - it makes training more stable than post-norm.

Gradient checkpointing saves memory

Recompute activations during the backward pass instead of storing them - trades compute for memory, essential for training large models.

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.