Lesson 6 of 187 min
Vanishing gradients and residual connections
On the way back, every layer multiplies the slope again, so a deep network loses it; a skip connection gives the slope a path back that never shrinks.
After this lesson you can explain why deep networks were hard to train, how the starting weights matter, and why skip connections fixed it.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Check the early layers
Take one backward pass before training and check the first and last hidden weights. A tiny early gradient can be hard to spot from the loss alone. This starts with the same handwritten digits and held-out split as the video. Run the cells in order.
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.set_num_threads(4)
digits = load_digits()
x, _, y, _ = train_test_split(digits.data / 16, digits.target,
test_size=0.2, stratify=digits.target, random_state=0)
x, y = torch.tensor(x, dtype=torch.float32), torch.tensor(y, dtype=torch.long)def stack(depth=20, activation=nn.ReLU, seed=0):
torch.manual_seed(seed)
layers = [nn.Linear(64, 32)] + [nn.Linear(32, 32) for _ in range(depth - 1)]
return nn.Sequential(*(part for layer in layers for part in (layer, activation())),
nn.Linear(32, 10))
plain = stack()
nn.functional.cross_entropy(plain(x), y).backward()
print(*(f"{layer.weight.grad.abs().mean():.2e}" for layer in (plain[0], plain[-3])))8.85e-11 3.75e-05
Give ReLU a wider start
The hidden layers have ReLU after them, so use Kaiming normal with nonlinearity="relu". Leave the final scores layer at its original start. Rerun the same backward pass and read the same two gradients. PyTorch initialization
wide = stack()
for layer in wide[:-1:2]:
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
nn.init.zeros_(layer.bias)
nn.functional.cross_entropy(wide(x), y).backward()
print(*(f"{layer.weight.grad.abs().mean():.2e}" for layer in (wide[0], wide[-3])))3.48e-04 1.43e-04
See what fades on the way up
A deep stack can make different pictures look almost identical by the time they reach the last layer. In the plain stack, compare the spread across pictures just after the first and last ReLUs. The last number explains why the scores have so little to work with.
with torch.no_grad():
first = plain[:2](x)
last = plain[:-1](x)
print(f"{first.std(dim=0).mean():.2e}", f"{last.std(dim=0).mean():.2e}")8.79e-02 5.44e-09
Read tiny updates and large ones
Adam adds a small number to its denominator. When the gradient is much smaller, Adam's first update is small too. The plain 20-layer run at seeds 1 and 2 stayed near 10% after 30 epochs. Rates above one can build up the other way. Adam in PyTorch
for slope in (1e-12, 1e-5):
weight = nn.Parameter(torch.zeros(()))
weight.grad = torch.tensor(slope)
torch.optim.Adam([weight], lr=1e-3).step()
print(f"{weight.abs():.2e}")
print(f"{1.2 ** 19:.1f}")1.00e-07 9.99e-04 31.9
Try a start for an S-curve
PyTorch calls this S-curve Sigmoid. Xavier initialization is one starting point. Check the same early and late weights after swapping it in. The S-curve can still shrink the gradient even when you change the start. Xavier uniform in PyTorch
curved = stack(activation=nn.Sigmoid)
for layer in curved[:-1:2]:
nn.init.xavier_uniform_(layer.weight)
nn.init.zeros_(layer.bias)
nn.functional.cross_entropy(curved(x), y).backward()
print(*(f"{layer.weight.grad.abs().mean():.2e}" for layer in (curved[0], curved[-3])))6.12e-16 9.20e-04
Follow a skip into a transformer
Qwen3 saves its input before attention and adds it back afterward. Its feed-forward part repeats the pattern. Research on hyper-connections and mHC carries several streams and mixes them around each layer. Qwen3 source, Hyper-Connections, mHC
h = torch.tensor([0.5, 1.5])
for delta in (torch.tensor([-0.2, 0.3]), torch.tensor([0.1, -0.4])):
saved = h
h = saved + delta
print(h.round(decimals=1))tensor([0.4000, 1.4000])
Run on Python 3.13.3, PyTorch 2.15.0 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Backpropagation
A box works out guess = h * w2 + 4.2. The forward pass kept h = 3, and w2 is 0.5. On the way back, a slope of 2 reaches the guess. What slope does w2 get?
2 of 3
Twenty layers of ReLU neurons, with PyTorch's own starting weights, barely learn: the first layer gets almost no slope. But ReLU's own rate is 1 or 0. So why does the slope still shrink at every layer?
3 of 3
A block works out h + torch.relu(self.layer(h)). On the way back, a slope of 2 reaches the block's output. The path through the layer passes back 0.5 of it. What slope reaches h?
The ideas in this lesson
- Vanishing gradients
- On the way back, each layer multiplies the slope by its rate; under 1, layer after layer, it shrinks to almost nothing.
- Starting weights
- How big the weights start sets each layer's rate; Kaiming's start keeps a ReLU layer's size, so the slope gets through.
- Skip (residual) connection
- A block's input is added to its output; on the way back, the add passes the slope through whole, to every layer.
It leans on
- Reading a PyTorch class
Transcript
What the video says, part by part. Press a time to watch from there.
Why deep networks stop learning
Here's a mystery. This network reads numbers written by hand. It gets nearly every one right. It has one layer in between. Now give it many more layers, and train it the same way.
It does far worse. So why does a deeper network stop learning?
Twenty layers
Here's the digits network. With one hidden layer, it gets about ninety-five percent right, on the pictures set aside. Now give it twenty hidden layers of thirty-two ReLU neurons, and train it with the same loop, for thirty epochs. How many will it get right? Hold on to your guess.
Deeper is worse
For seventeen epochs, it gets one picture in ten right. That's no better than picking a digit at random. Its loss stays at two point three, where a network that hasn't learned anything starts.
Then it learns, very slowly.
After thirty epochs, about half.
Five layers get about ninety-two percent. Ten get about sixty-two. The more layers it has, the worse it does.
The slope shrinks layer by layer
So why does a deep network barely learn?
At the start of training, look at the slope that backpropagation brings back to each layer. The last layer's is the biggest. Each layer below gets less. And by the first layer... less than a ten-millionth of it is left. With a slope that small, those weights barely move.
The vanishing gradient
Why less at every layer?
On the way back, backpropagation multiplies the slope by each layer's rate: how much of the slope that layer passes back.
Here, every rate is about zero point four, a little under half.
Halve a number ten times. What's left?
About a thousandth. Halve it twenty times, and about a millionth is left.
Our nineteen rates of zero point four leave even less. All the slopes together are the gradient. So this is called... the vanishing gradient.
ReLU is not the fix
You might read that the S-curve causes this, because its own rate is never more than a quarter. And that ReLU fixes it, because its rate is one or zero. But look. This network already uses ReLU, and its slope still shrinks. So what else sets the rate?
The weights set the rate
On the way back, every layer multiplies the slope by its rate. In a deep network, a rate under one makes the slope vanish. So where does a layer's rate come from? From its weights, too.
ReLU turns about half of what comes in to zero. PyTorch starts the weights too small to make up for that. So what happens? Each layer passes on only about zero point four of what it gets. On the way back, that shrinks the slope. On the way up, it shrinks the picture too, so the last layers can hardly tell one digit from another. Kaiming's starting weights, named after the researcher who found them, are about two and a half times bigger. That's just enough so each layer keeps the size of what passes through it.
How the weights start matters
Now the first layer gets about a third of the last layer's slope, not a ten-millionth. Trained the same way, it gets about eighty-nine percent. So the starting weights really matter.
A path that never shrinks
The slope shrinks as it passes back through many layers. A good start helps. But with Kaiming's start, twenty layers still do worse than five: eighty-nine percent compared to ninety-five. Very deep networks train because of one simple fix.
Take what goes into a layer, and add it to what comes out.
That extra path is a skip.
A layer with its skip is called a block.
On the way back, what does that plus do to the slope?
It passes the slope to both of its sides, unchanged: back through the layer, and straight down the skip.
So along the skips, the slope never shrinks, all the way to the first layer. That's a skip connection.
Depth stops hurting
The same twenty layers, with PyTorch's own start, now get almost ninety-six percent. Below each block, the slope from the skip and the slope from the layer are added together. So the first layer even gets more than the last.
And five, ten or twenty layers all get about ninety-six. Now more layers don't hurt.
Each block learns a change
Now each block only learns a change to add to what it got. That change is called the residual. So a skip connection is also called a residual connection. In twenty fifteen, ResNet trained a hundred and fifty-two layers with them, and won that year's ImageNet contest.
The digits only need one layer. Harder tasks need depth, and skips are what let it train.
In code
In code, a block is a small class. Its forward method runs what comes in through its layer and ReLU... then adds what came in, unchanged. Put nineteen of these after the first layer, and train them with the same loop. It scores almost ninety-six percent. And a transformer block, the kind inside chatbots, has the same plus twice: once after each of its two parts.
Here's the code of a real chatbot model. It saves what came in, then adds it back. In this code, that saved input is named residual.
Shrinks, or gets through
So, on the way back, every layer multiplies the slope. With rates under one, layer after layer, the slope vanishes. Starting weights that keep each layer's size help.
And a skip gives the slope a path that never shrinks.
A path back
Skips let every layer learn, even in a very deep network. Now try it on this lesson's page, and take the quiz. Find out how deep the S-curve can go and still learn.
You use this lesson in Lab 3: A deep digit reader that doesn't memorize, after Dropout, weight decay and early stopping.
Facts last checked on .
