30 Mins

6. Vanishing & Exploding Gradients

The Mechanics of Gradient Instability

In deep neural networks, the gradient of the loss function is calculated via the chain rule, involving the product of many partial derivatives across layers. If these derivatives are consistently small (e.g., in sigmoid activations where the maximum gradient is 0.25), multiplying them across dozens of layers results in an exponential decay towards zero, known as the vanishing gradient problem. This effectively prevents the initial layers of the network from learning meaningful features as their weights receive updates that are negligible.

Conversely, exploding gradients occur when these derivatives are consistently greater than one. The product grows exponentially with depth, leading to massive updates to weight values. This manifests as numerical instability, where model weights become 'NaN' or oscillate wildly during training, making convergence impossible. These issues are foundational constraints in deep architecture design, necessitating specific initialization and normalization strategies.

Operator Note: Always check your gradient norms using torch.nn.utils.clip_grad_norm_ during training to prevent sudden spikes.
Python 3
import torch

# Simulating the vanishing gradient via sigmoid layers
x = torch.randn(1, 10)
for i in range(20):
    layer = torch.nn.Linear(10, 10)
    x = torch.sigmoid(layer(x))

# Backward pass on an arbitrary output node
loss = x.sum()
loss.backward()

# Observe gradients of the first layer
print(f'Gradients of first layer: {list(layer.parameters())[0].grad}')

Weight Initialization Strategies

Weight initialization is the primary defense against vanishing and exploding gradients. The goal is to keep the variance of the activation and the gradient flow consistent across layers. Xavier (Glorot) initialization was designed for symmetric activation functions like tanh, setting weight variance to $\frac{2}{\text{fan}_{in} + \text{fan}_{out}}$. It ensures that the signal variance does not shrink or explode as it passes through the layers.

For networks employing ReLU or Leaky ReLU, Xavier initialization often results in dying units. He (Kaiming) initialization addresses this by accounting for the fact that ReLU suppresses half of the input space. By setting the variance to $\frac{2}{\text{fan}_{in}}$, He initialization provides the extra scaling needed to compensate for the inactive neurons, maintaining variance stability in modern deep convolutional and residual networks.

Operator Note: Use kaiming_normal_ for ReLU-based networks and xavier_uniform_ for networks primarily using tanh or sigmoid.
Python 3
import torch.nn as nn

# Defining a layer and applying He Normal initialization
layer = nn.Linear(512, 512)
nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')

# Xavier/Glorot for a tanh network
tanh_layer = nn.Linear(512, 512)
nn.init.xavier_uniform_(tanh_layer.weight)

Mitigation via Gradient Clipping

While initialization manages the starting point, gradient clipping is the dynamic safety mechanism applied during training, particularly in Recurrent Neural Networks (RNNs) where exploding gradients are frequent due to repeated matrix multiplications. Gradient clipping involves rescaling the norm of the gradients if it exceeds a predefined threshold. This ensures that the update step remains bounded, preventing the optimizer from taking excessively large steps in the loss landscape.

By enforcing a maximum norm, we prevent the 'numerical explosion' that happens when gradients are unusually large due to erratic training batches or architectural bottlenecks. This technique is computationally inexpensive and serves as a vital safeguard, keeping the optimization trajectory within a stable region of the parameter space, even if the loss landscape is exceptionally steep.

Operator Note: Start with a threshold of 1.0 for clip_grad_norm_. If convergence is slow, increase it, but monitor for weight instability.
Python 3
import torch.nn.utils as utils

# Standard training loop step with clipping
optimizer.zero_grad()
output = model(input_data)
loss = criterion(output, target)
loss.backward()

# Clamp gradients to a maximum norm of 1.0
utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

optimizer.step()

Knowledge Check

Ready to test your understanding of 6. Vanishing & Exploding Gradients?

Back