Level 3 In-Depth AI · Deep Learning
Residual Connections
Add a layer's input back to its output, so each block only learns a correction. This one-line trick lets networks go hundreds of layers deep and runs through every modern Transformer.
- Level
- ●●●●● Intermediate
- Reading
- 11 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 18 concepts →
- Quiz
- 5 questions ↓
Read first
Vanishing and Exploding GradientsThe full path from zero — 18 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Residual Connections
Read them roughly in this order. See it on the concept map →
Why it matters
Until 2015, deeper was not simply better. Stacking more layers should, in principle, give a network more power: a 56-layer network can always copy a 20-layer one and set its extra layers to "do nothing". In practice the 56-layer network trained worse. Its error on the training data itself was higher. That rules out Overfitting and the Bias–Variance Tradeoff as the cause. The extra depth was making the optimisation harder.
The fix, published by Kaiming He and colleagues at Microsoft Research in December 2015, was almost embarrassingly simple: add each block's input to its output. Their ResNet ("residual network") won the 2015 ImageNet competition with 152 layers, about seven times deeper than GoogLeNet, the 22-layer winner of the year before. They also trained a version with more than 1,000 layers on a small dataset.
Since then the idea has spread everywhere. Every The Transformer, from BERT to the GPT models, wraps each of its sub-layers in a residual connection. GPT-3 has 96 Transformer layers, which would be very hard to train without them. If you look at any modern architecture diagram, you will see the little "+" that this chapter is about.
The intuition
Imagine editing a document passed down a line of 50 editors. In version A, each editor must retype the whole document from memory with their improvements. After 50 retypings, almost nothing of the original survives, and if the first editor made a good change, nobody downstream can tell who to thank. In version B, each editor gets the document and writes suggested changes in the margin, which are then applied. An editor with nothing to add writes nothing, and the document passes through intact. Feedback about the final version also travels straight back to everyone.
Version B is a residual network. Each block receives and computes a correction , the residual, and the block outputs . The path that carries around the block unchanged is the skip connection (also called a shortcut or identity connection). Adding it is a residual connection.
Two good things follow:
- Doing nothing is easy. For an ordinary layer, learning the identity ("output = input") requires finding exactly the right weights. For a residual block it only requires , which is close to where small random weights start anyway. So adding blocks can't easily make the network worse.
- Gradients have a highway. During Backpropagation, the error signal can travel back along the skip connections without being multiplied by any weights. Early layers keep receiving a useful gradient, however deep the network is.
Key idea A residual block computes instead of . The layers only learn the change to make, and the plain "+ x" gives gradients a direct path back to the earliest layers.
How it works
The degradation problem
The puzzle the ResNet paper set out to solve is called the degradation problem. On the CIFAR-10 image dataset, a plain 56-layer network had higher training error than a plain 20-layer one. That isn't overfitting, which would show up as low training error and high test error. The deeper network simply could not be optimised as well, even though a solution at least as good as the 20-layer one existed. The Vanishing and Exploding Gradients chapter explains part of the reason: the gradient reaching early layers is a product of many factors, one per layer, and products of many numbers tend to shrink towards zero or blow up.
The equation
An ordinary layer or block computes . A residual block computes
where is the block's input vector, is a small stack of layers (in the original ResNet, two layers with a ReLU between them), and is the output. The addition is element by element, so must have the same shape as .
Why gradients survive
Backpropagation needs the derivative of the output with respect to the input. For one number flowing through a block, , the derivative is
That "1" comes from the skip connection, and it changes everything. A plain stack of layers passes a gradient back multiplied by . A residual stack multiplies by .
A worked example. Take 20 layers where each one's derivative is about 0.5:
- Plain: . The first layer receives a millionth of the signal. In effect it never learns.
- Residual, with each branch's derivative small, say in ten blocks and in the other ten: . Almost all of the signal arrives.
Multiply out two blocks and you see why: . The term "1" is the path that skips both blocks, and are paths through one block each, and goes through both. A residual network with blocks contains such paths of different lengths. Veit and colleagues showed in 2016 that trained ResNets behave a bit like an ensemble of many shallower networks, with most of the gradient coming from the shorter paths.
The same holds for the whole network at once. Unrolling from block to the last block gives
The final output is the early representation plus a sum of corrections. The gradient of the loss with respect to therefore always contains the gradient with respect to itself, passed back unchanged.
Seeing it happen
The experiment in the code section below builds two 50-block networks that differ only in the "+ x". Here is how large the gradient is in each block just before the first training step:
The plain network's early layers get gradients around , too small to change anything. After 300 steps the plain network is still guessing at chance, while the residual one has fitted the data perfectly.
When shapes don't match
The addition needs and to be the same shape. In a convolutional network, some blocks halve the image size and double the number of channels. There the shortcut becomes a cheap projection, usually a 1×1 convolution with stride 2, which reshapes to fit: . Only a handful of blocks need this. All the rest use the plain identity.
Bottleneck blocks
Deeper ResNets (50, 101 and 152 layers) use a bottleneck block to save computation. A 1×1 convolution first shrinks the channels (say 256 → 64), then a 3×3 convolution works on the thin version, then another 1×1 convolution expands back to 256 before the addition. ResNet-50 has about 25.6 million parameters and is still one of the most common image backbones. Classic CNN Architectures: LeNet to ResNet covers the family.
Where the normalisation goes
The original block applies batch normalisation and ReLU inside , plus one more ReLU after the addition. A 2016 follow-up by the same authors, Identity Mappings in Deep Residual Networks, moved the normalisation and activation to the start of the branch ("pre-activation"). This keeps the skip path a pure identity from end to end and trains better at very large depths.
Transformers made the same choice, for the same reason. A modern pre-LN Transformer layer is
where LN is layer normalisation. The original 2017 Transformer put the normalisation after the addition ("post-LN"), which needs a careful learning-rate warmup to train stably.
The residual stream
Because every sub-layer only adds to , it is useful to picture a Transformer as one long vector, the residual stream, flowing from the input embedding to the output. Each attention and MLP layer reads from the stream and writes a correction back into it. The final prediction is made from the sum of everything written. The term comes from interpretability research at Anthropic (Elhage and colleagues, 2021), and it is a central idea in Mechanistic Interpretability: you can ask what each layer adds to the stream and study the layers somewhat independently.
In code
A small experiment in PyTorch. The two networks are identical except for the x + in forward:
import torch
import torch.nn as nn
class Block(nn.Module):
def __init__(self, width, residual):
super().__init__()
self.f = nn.Sequential(nn.Linear(width, width), nn.Tanh())
self.residual = residual
def forward(self, x):
return x + self.f(x) if self.residual else self.f(x)
def deep_net(depth, residual, width=32):
return nn.Sequential(nn.Linear(2, width),
*[Block(width, residual) for _ in range(depth)],
nn.Linear(width, 1))
torch.manual_seed(0)
x = torch.randn(512, 2)
y = (x[:, 0] * x[:, 1] > 0).float().unsqueeze(1) # XOR-like pattern
for residual in (False, True):
torch.manual_seed(1)
net = deep_net(depth=50, residual=residual)
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
loss_fn = nn.BCEWithLogitsLoss()
for step in range(301):
loss = loss_fn(net(x), y)
opt.zero_grad(); loss.backward()
if step == 0: # how much gradient reaches the first layer?
g = net[0].weight.grad.norm().item()
opt.step()
acc = ((net(x) > 0).float() == y).float().mean().item()
print(f"residual={residual!s:5} first-layer grad {g:.2e} loss {loss.item():.3f} acc {acc:.2f}")
# residual=False first-layer grad 1.68e-15 loss 0.693 acc 0.51
# residual=True first-layer grad 9.13e-01 loss 0.000 acc 1.00
A loss of 0.693 is : the plain network is still guessing. The real ResNet "basic block" for images looks like this, with convolutions and batch normalisation inside the branch:
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, channels):
super().__init__()
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(channels)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
return F.relu(x + out) # add the shortcut, then ReLU
block = BasicBlock(64)
print(block(torch.randn(8, 64, 32, 32)).shape) # torch.Size([8, 64, 32, 32])
torchvision.models.resnet50(weights="DEFAULT") gives you the full pretrained network (Transfer Learning).
Common pitfalls
- Shape mismatches.
x + F(x)fails, or worse, silently broadcasts, if the shapes differ. Whenever a block changes the size or number of channels, it needs a projection shortcut. - Activations growing with depth. Each block adds to the stream, so its size can grow with the number of blocks. Normalisation inside the branches helps. So does starting each branch near zero: zero-initialise the last normalisation scale in each block, or, as GPT-2 did, scale the initial weights of residual layers down by for residual layers.
- Putting things on the skip path. A ReLU, dropout or normalisation directly on the shortcut breaks the clean identity. Keep the skip path as plain as possible, and put the extra operations inside .
- Assuming residuals fix everything. They make depth trainable. They do not choose the learning rate for you or stop overfitting. The training recipe still applies.
Watch out "Skip connection" also names a different idea: in U-Net and similar encoder–decoder networks (Image Segmentation), skip connections usually concatenate early feature maps onto later ones rather than adding them. Both carry information past intermediate layers, but they are different operations with different shapes.
Variations
- Highway networks (Srivastava, Greff and Schmidhuber, 2015) came a few months before ResNets and used a learned gate to mix and . ResNet's ungated version turned out simpler and at least as good. The idea of an additive path for gradients goes back further, to the cell state of the LSTM in 1997.
- DenseNet (2016) connects every layer to every later layer in a block by concatenation.
- Pre-activation ResNets and pre-LN Transformers keep the identity path clean, as described above.
- Residual streams in Transformers are the default today. See The Transformer, Vision Transformers and Diffusion Transformers.
A bit of history
Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun posted Deep Residual Learning for Image Recognition in December 2015. Their 152-layer ResNet won the ImageNet classification challenge that year, and an ensemble of ResNets reached 3.57% top-5 error. The paper won the best paper award at CVPR 2016 and has since become one of the most cited papers in all of science. The idea combined two earlier lines of work: gated shortcuts (highway networks, 2015, from Jürgen Schmidhuber's lab) and the additive memory of LSTMs. Two years later, the Transformer adopted residual connections around every sub-layer. Today the residual stream is how people describe what happens inside large language models.
Try it
- In the experiment, change
nn.Tanh()tonn.ReLU()and the depth to 20, 50 and 100. At what depth does the plain network stop learning? Does the residual one?- Print the size (norm) of the activations after every block of the residual network. Does it grow with depth? Try multiplying
self.f(x)by0.1.- By hand: with each branch derivative equal to in all 20 blocks, what is the product ? What does that tell you about whether residuals alone guarantee healthy gradients?
Hint for 3: is the same tiny number as the plain network. Residuals help because branches start out small, which is why careful initialisation and normalisation still matter.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Deep Residual Learning for Image Recognition
ResNet: skip connections made networks with 100+ layers trainable.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Identity Mappings in Deep Residual Networks
The follow-up to ResNet: keeping the shortcut a pure identity (pre-activation blocks) makes networks of 1,000+ layers train well.
Highway Networks
Gated shortcut connections that let information and gradients bypass layers, published months before ResNet.
Residual Networks Behave Like Ensembles of Relatively Shallow Networks
Shows a ResNet as a collection of many paths of different lengths, with most gradient flowing through the short ones.
Transformer Circuits Thread
Research reverse-engineering Transformers: circuits, superposition, features and model biology.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/residual-connections.md