Skip to content
E
Educatum

Exploding Gradient

Curated by Educatum AI teamLast updated:
Neural Networks and Deep LearningNN
Direct Answer

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 ∏lW(l)⊤diag(σ′(z(l)))\prod_{l} W^{(l)\top} \text{diag}(\sigma'(z^{(l)})). Whenever the singular values of those Jacobians consistently exceed 11, 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 (∇θL\nabla_\theta \mathcal{L}): 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 11 shrink gradients exponentially toward zero in early layers.
  • Gradient Clipping: Rescaling the gradient vector gg whenever ∥g∥2>τ\|g\|_2 > \tau (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 WhhW_{hh} whose largest eigenvalue is 1.21.2. Backpropagating errors from step 100100 back to step 11 multiplies gradients repeatedly by Whh⊤W_{hh}^\top (along with tanh⁡′\tanh' factors), scaling perturbations roughly as 1.2100≈8.3×1071.2^{100} \approx 8.3 \times 10^7. A single mini-batch update throws weights far outside the smooth region of the loss surface, producing NaN losses. Adding global gradient norm clipping (τ=1.0\tau = 1.0) 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}")
  • Vanishing Gradients: Caused by saturating activations (sigmoid/tanh where σ′≤0.25\sigma' \le 0.25) or small weights; mitigated by ReLU/GELU, residual skip connections, and proper initialization.
  • Weight Initialization (Xavier & He): Scales initial weight variances by 1/nin1/n_{\text{in}} or 2/nin2/n_{\text{in}} so signal and gradient norms stay O(1)O(1) 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 11 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.