# Vanishing and Exploding Gradients

> Why the training signal shrinks or grows as it travels back through a deep network, and the fixes teams use, for your AI interview.

**In short:** When a deep network learns, the training signal sent back through its layers can shrink to almost nothing (vanishing) or grow too large (exploding). Either way, the model stops learning properly.

AI and LLM interview question Q426, Classic ML and deep-learning basics. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/vanishing-and-exploding-gradients

## Say it in 30 seconds

When a deep network learns, its correction travels backwards through every layer. If each layer shrinks it a little, it vanishes, and the early layers barely learn. If each layer grows it, it explodes, and the weights jump until training breaks. The usual fixes are ReLU activations, careful starting weights, skip paths, normalisation and gradient clipping. Before I change anything, I'd measure the gradient size in each layer.

## Say it in 2 minutes

Training a neural network means checking its answer against the right one, then sending a correction backwards through the layers. The size of that correction is the gradient. Each layer multiplies it by its own numbers as it travels back, so a deep network makes a long chain of multiplications.

If those multiplications mostly shrink the signal, the gradient vanishes. The early layers, which read the raw inputs, get almost no update and barely learn. If they mostly grow it, the gradient explodes. The weights jump so far that training diverges. Both problems get worse with depth, because a longer chain means more multiplications.

I'd show it with a small example. Take a made-up 30-layer fraud model. A factor of 0.5 per layer leaves under a billionth of the signal at the first layer. A factor of 1.5 makes it over 190,000 times bigger. Then I'd name the fixes: ReLU-style activations, careful starting weights, skip paths, batch normalisation, and gradient clipping, which caps the size of each step.

I'd also be honest that none of them is a guarantee. I'd measure the gradient in each layer, change one thing at a time, and check that the early layers move, because a fix you haven't measured is only a guess.

## What are vanishing and exploding gradients, in plain words?

A neural network learns by comparing its answer with the right one, then sending a correction backwards through its layers. That correction is the gradient. Each layer uses the part it receives to change its own weights, so the gradient decides how much every layer learns.

Vanishing gradients means the correction shrinks towards zero before it reaches the early layers, so they barely change. Exploding gradients is the opposite: the correction grows so large that the weights jump, and training falls apart.

Think of a bank's loan desk with 30 reviewers in a chain. Each one passes the feedback back up, but changes its strength by a fixed amount. If each reviewer halves it, the first reviewer hears almost nothing. If each one adds half again, the feedback turns into a shouting match. A deep fraud model faces the same chain, with 30 layers instead of 30 reviewers.

- **Gradient:** The size and direction of the correction a layer gets during training.
- **Backpropagation:** Sending the error back through the layers, one at a time, to work out each correction.
- **Layer:** One stage of a network. A deep network stacks many of them one after another.
- **Learning rate:** A small number that sets how big each update step is.

## Why do the signals shrink or grow in deep networks?

Backpropagation uses the chain rule. Each layer's share of the correction is multiplied onto the share from the layer after it. A 30-layer network therefore multiplies about 30 numbers together. If most of them are below 1, the product falls towards zero. If most are above 1, it climbs fast.

Glorot and Bengio studied this in 2010. They looked at a table of how each layer's outputs change with its inputs, called the Jacobian. Roughly, its singular values say how much each layer stretches or shrinks the signal in its main directions. They wrote:

> "training may be more difficult when the singular values of the Jacobian associated with each layer are far from 1" (Glorot and Bengio, 2010)
>
> "Layers with vanishing gradients train very slowly, or not at all." (Google's machine learning crash course)

In plain words: if each layer stretches the signal much less or much more than 1, training struggles. The chart shows the same error sent back two ways, with a made-up factor of 0.5 or 1.5 per layer.

*Diagram, One error, two ways it can go wrong: An error at the output travels back through 30 layers. If each layer halves the signal, almost nothing reaches the early layers. If each layer grows it by half again, the weights jump. Both cases are shown at once.*
1. Case one: each layer halves the signal.
2. Case two: each layer grows it by half again.
3. After 30 halvings, under a billionth is left.
4. After 30 growths, the signal passes 190,000.

## What does it look like with real numbers?

Here is a made-up 30-layer network that scores card transactions for fraud. The error at the output starts at 1.0, and each layer multiplies it by one fixed factor. The script runs three cases, and the last line applies clipping, which is explained below.

```python
# A made-up 30-layer network that scores card transactions for fraud.
# The error at the output is sent back one layer at a time, and each layer
# multiplies it by the same factor.
LAYERS = 30

def gradient_at_first_layer(factor):
    grad = 1.0
    for _ in range(LAYERS):
        grad *= factor
    return grad

def clip(grad, max_size=5.0):
    # Simplified clipping: cap one value at the limit. Real libraries such as clip_grad_norm_ cap the whole gradient norm instead.
    if abs(grad) > max_size:
        return max_size if grad > 0 else -max_size
    return grad

for factor in [0.5, 1.0, 1.5]:
    g = gradient_at_first_layer(factor)
    print(f"factor {factor}: first-layer gradient = {g:.3e}")

print(f"clipped to 5.0: {clip(gradient_at_first_layer(1.5)):.1f}")
```

Output:

```text
factor 0.5: first-layer gradient = 9.313e-10
factor 1.0: first-layer gradient = 1.000e+00
factor 1.5: first-layer gradient = 1.918e+05
clipped to 5.0: 5.0
```

- **Factor 0.5: Early layers go silent.** After 30 layers the gradient is under a billionth of the start. The first layers hardly change, so the model never learns the early patterns.
- **Factor 1.5: Weights jump.** The gradient reaches over 190,000. A step that large throws the weights far off, and the loss jumps around instead of falling.
- **Factor 1.5, clipped: Capped at 5.0.** The same huge gradient is shrunk to 5.0 before the update. The step stays within a safe size.

A factor of 1.0 keeps the signal at 1.0 through every layer. That is the balance the fixes below aim for, layer by layer.

## How do teams stop gradients vanishing or exploding?

No single fix solves it. Teams combine a few, and they check the gradient size in each layer during training. Here are the usual ones, in the order I'd try them.

1. **Use ReLU-style activations:** Google's course says the ReLU activation function can help prevent vanishing gradients. Glorot and Bengio found the sigmoid "is unsuited for deep networks with random initialization".
2. **Start the weights with care:** Glorot and Bengio proposed a new initialization scheme for faster convergence. He and colleagues derived one that considers rectifier activations such as ReLU, and said it "enables us to train extremely deep rectified models directly from scratch".
3. **Add skip paths:** A skip path lets the signal jump past a block of layers, so the gradient has a short route back. ResNet's authors wrote that they present "a residual learning framework to ease the training of networks that are substantially deeper than those used previously".
4. **Normalise the layers:** Google's course says "Batch normalization can help prevent exploding gradients, as can lowering the learning rate." Normalisation keeps each layer's values in a steady range, and a smaller learning rate makes each step smaller.
5. **Clip the gradient:** Pascanu and colleagues proposed "a gradient norm clipping strategy to deal with exploding gradients". PyTorch's clip_grad_norm_ applies it to the whole gradient: "Clip the gradient norm of an iterable of parameters." The gradients are modified in place, so the capped values are the ones the optimiser uses.

*Diagram, Fixes that act on different parts: The fixes act on different parts. Activations, starting weights and skip paths keep the signal from fading. Normalisation and clipping keep it from blowing up. Measure the gradient in each layer to check the result.*
1. The network gets fixes that keep the signal steady.
2. It also gets fixes that keep the size in range.
3. A steady signal lets the early layers learn.
4. A capped size stops the weights jumping.

> **Tip:** Asked how you'd fix it, don't say "add more layers". Name the cause, the chain of multiplications, and two fixes that act on different parts.

## Why are recurrent networks hit hardest?

A recurrent network reads a sequence one step at a time and reuses the same weights at every step. The correction must travel back through every step of the sequence. A long log file or a long transcript is therefore like a very deep network, and the same two problems appear.

> "There are two widely known issues with properly training Recurrent Neural Networks, the vanishing and the exploding gradient problems detailed in Bengio et al. (1994)." (Pascanu, Mikolov and Bengio)

Their paper also proposed a soft constraint for the vanishing side, next to the clipping for the exploding side. For an interview, say the two problems come from the same chain of multiplications. Gradient clipping carries over to recurrent networks directly. The vanishing side needs a different tool, the soft constraint above, which is not one of the ReLU or skip-path ideas.

### How would you debug a model that stops learning?

Suppose a 30-layer fraud model's loss stopped falling after a few epochs. I'd work through these checks in order, and change one thing at a time.

1. **Log the size per layer:** Print the gradient size for each layer after one batch. Near-zero numbers in the early layers point to vanishing, and huge or nan numbers point to exploding.
2. **Check the activations:** Look for units stuck at the same value, such as zero or the top of a sigmoid. A stuck unit passes on almost no gradient, so the layers before it barely learn.
3. **Lower the learning rate:** Halve it and run again. If the loss stops jumping, the steps were too big.
4. **Shorten the network:** Train a 6-layer version. If it learns and the 30-layer one doesn't, depth is the problem, and skip paths or normalisation are the next step.

> **Tip:** Check the gradient sizes again after every change. A fix that you haven't measured is only a guess.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: the training signal shrinks or grows as it passes back through layers.
- [ ] Why it happens: a long chain of multiplications, one per layer.
- [ ] Both directions, and what each does to learning.
- [ ] Fixes that act on different parts: activations, starting weights, skip paths, normalisation and clipping.
- [ ] How you'd spot it: the gradient size in each layer, in the logs.
- [ ] An honest limit: no fix is guaranteed, so measure the result.

**Common traps**

- Trap: "Just add more layers, the model will learn more." Better: More layers make the chain longer, so the problem can get worse. Fix the signal first.
- Trap: "It must be a bug, so restart training." Better: Usually it's the design: depth, activations and starting weights. Measure the gradient sizes first.
- Trap: "A lower learning rate fixes everything." Better: It helps the exploding side. It does little for a gradient that has already faded to zero.

## Can you spot the vanishing gradient?

**Spot the vanishing gradient:** Which training log shows vanishing gradients in the early layers?

A. layer_01 grad_norm=0.0000000002   layer_30 grad_norm=0.41
B. layer_01 grad_norm=12.4   layer_30 grad_norm=0.41
C. layer_01 grad_norm=0.41   layer_30 grad_norm=0.40
D. layer_01 grad_norm=nan   layer_30 grad_norm=nan

**Answer:** A. The first layer is near zero while the last layers look normal: the signal faded on its way back. The 12.4 is far above the rest, a sign of exploding gradients. nan means the numbers have already broken down, usually after an overflow.

**Quick check:** A fraud model's gradients explode after two epochs. Which first change is the lowest-risk?

A. Double the number of layers
B. Add gradient clipping and lower the learning rate
C. Remove the batch normalisation layers
D. Stop saving checkpoints

**Answer:** B. Clipping caps the size of each update, and a lower learning rate shrinks each step. Both act on the exploding side without changing the model's design.

## Can you answer these from memory?

**Flash cards**

- **What is a gradient?** The size and direction of the correction a layer gets during training.
- **What is a vanishing gradient?** The correction shrinks towards zero, so early layers barely learn.
- **What is an exploding gradient?** The correction grows too big, so the weights jump and training breaks.
- **Why does depth make it worse?** Each layer multiplies the signal again, so a long chain shrinks or grows it.
- **Two fixes that act on the signal?** ReLU-style activations and careful starting weights.
- **What does gradient clipping do?** It caps the size of the gradient before the update, so one step stays safe.

## Likely follow-up questions

- Q418 What is backpropagation? https://designervenkat.online/interview/ai/what-is-backpropagation
- Q427 What is batch normalisation? https://designervenkat.online/interview/ai/what-is-batch-normalisation
- Q438 Why does weight initialisation matter? https://designervenkat.online/interview/ai/why-does-weight-initialisation-matter
- Q053 What do residual connections do? https://designervenkat.online/interview/ai/what-do-residual-connections-do
- Q440 Why do neural nets need non-linearity? https://designervenkat.online/interview/ai/why-do-neural-nets-need-non-linearity
- Q417 What does the learning rate do? https://designervenkat.online/interview/ai/what-does-the-learning-rate-do

## Learn it in depth

- [Back propagation: who is to blame?](https://designervenkat.online/learn/machine-learning/backpropagation)
- [Activation functions: the bends](https://designervenkat.online/learn/machine-learning/activation-functions)
