Exploding Gradient
Exploding gradients arise during backpropagation when repeated multiplication of layer weight matrices and activation derivatives causes error gradients to grow exponentially across deep layers or long sequences. This produces huge parameter updates, loss oscillations, or NaN overflow, and is mitigated using gradient norm clipping, proper initialization (Xavier/He), normalization layers, residual connections, and gated RNNs.
Study Card: Exploding Gradient
Direct Answer
Exploding gradients occur when gradients backpropagated through a deep neural network or an unrolled Recurrent Neural Network (RNN) grow exponentially across layers or time steps. By the chain rule, the gradient at an earlier layer involves a product of Jacobians . Whenever the singular values of those Jacobians consistently exceed , the product scales exponentially with depth or sequence length, resulting in massive parameter steps, oscillating loss, and eventual NaN numerical overflow. Standard remedies include gradient clipping (capping the global gradient norm), Xavier/He initialization, residual connections, Batch/Layer Normalization, and gated recurrent cells (LSTM/GRU).
Key Terms
- Gradient (): The vector of partial derivatives of the loss with respect to weights, pointing in the direction of steepest ascent.
- Backpropagation: Applying the chain rule backward from the output loss to compute gradients layer by layer.
- Vanishing Gradient Problem: The dual failure mode where Jacobian singular values below shrink gradients exponentially toward zero in early layers.
- Gradient Clipping: Rescaling the gradient vector whenever (
clipnorm/clip_by_global_norm) or clamping elements (clipvalue) to keep updates bounded without changing the gradient direction (for norm clipping). - Normalization (BatchNorm / LayerNorm): Stabilizes forward activation scales and backpropagated Jacobian norms across deep networks.
Example
Imagine training a vanilla RNN across 100 time steps with recurrent weight matrix whose largest eigenvalue is . Backpropagating errors from step back to step multiplies gradients repeatedly by (along with factors), scaling perturbations roughly as . A single mini-batch update throws weights far outside the smooth region of the loss surface, producing NaN losses. Adding global gradient norm clipping () bounds step size while preserving update direction.
Code Implementation
import numpy as np
import tensorflow as tf
from tensorflow import keras
# Generate synthetic binary classification data
np.random.seed(42)
X = np.random.rand(1000, 100).astype(np.float32)
y = np.random.randint(0, 2, size=(1000, 1)).astype(np.float32)
# Define a deep MLP model
model = keras.Sequential([
keras.Input(shape=(100,)),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(1, activation='sigmoid'),
])
# 1. Built-in gradient clipping via optimizer clipnorm (or clipvalue)
optimizer = keras.optimizers.Adam(learning_rate=1e-3, clipnorm=1.0)
model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X, y, epochs=5, batch_size=32, verbose=0)
# 2. Equivalent explicit custom training step with tf.clip_by_global_norm
loss_fn = keras.losses.BinaryCrossentropy()
@tf.function
def train_step(x_batch, y_batch):
with tf.GradientTape() as tape:
preds = model(x_batch, training=True)
loss_value = loss_fn(y_batch, preds)
grads = tape.gradient(loss_value, model.trainable_variables)
clipped_grads, global_norm = tf.clip_by_global_norm(grads, clip_norm=1.0)
optimizer.apply_gradients(zip(clipped_grads, model.trainable_variables))
return loss_value, global_norm
loss_val, grad_norm = train_step(X[:32], y[:32])
print(f"Step loss: {float(loss_val):.4f}, Pre-clip global norm: {float(grad_norm):.4f}")
Related Concepts
- Vanishing Gradients: Caused by saturating activations (sigmoid/tanh where ) or small weights; mitigated by ReLU/GELU, residual skip connections, and proper initialization.
- Weight Initialization (Xavier & He): Scales initial weight variances by or so signal and gradient norms stay across depth at initialization.
- Recurrent Neural Networks (LSTMs & GRUs): Additive cell-state highways (“constant error carousel”) prevent exponential blowup or decay across long sequence horizons.
- Activation Functions: ReLU mitigates vanishing gradients via derivative on positive inputs, whereas its unbounded positive output can still allow exploding activations/gradients unless paired with He initialization, residual scaling, or LayerNorm/BatchNorm.
- Weight Regularization Limits: While L2 weight decay discourages excessively large weights over time, it does not prevent sudden Jacobian-product explosion in a single unstable batch—gradient clipping and normalization provide immediate protection.