◆ AI All-in-One

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
↗ Plan a path here

Read first

Vanishing and Exploding Gradients

This leads to

The TransformerClassic CNN Architectures: LeNet to ResNet
The full path from zero — 18 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Backpropagation
  17. Activation Functions
  18. Vanishing and Exploding Gradients
  19. 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 x\mathbf{x} and computes a correction F(x)F(\mathbf{x}), the residual, and the block outputs x+F(x)\mathbf{x} + F(\mathbf{x}). The path that carries x\mathbf{x} around the block unchanged is the skip connection (also called a shortcut or identity connection). Adding it is a residual connection.

x layer weights W₁ ReLU layer weights W₂ output x + F(x) skip connection: copy x unchanged no weights, nothing to learn, gradient passes straight through residual branch F(x) learns only the change to make to x add if F(x) = 0 the block passes x through untouched, so a newly added block starts out harmless
Fig. 1 A residual block. The input x takes two routes: through the layers, which compute a correction F(x), and around them on the skip connection. The two are added. If the layers output zero, the block simply passes x on.

Two good things follow:

  1. 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 F(x)=0F(\mathbf{x}) = 0, which is close to where small random weights start anyway. So adding blocks can't easily make the network worse.
  2. 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 x+F(x)\mathbf{x} + F(\mathbf{x}) instead of F(x)F(\mathbf{x}). 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 y=F(x)\mathbf{y} = F(\mathbf{x}). A residual block computes

y=x+F(x)\mathbf{y} = \mathbf{x} + F(\mathbf{x})

where x\mathbf{x} is the block's input vector, FF is a small stack of layers (in the original ResNet, two layers with a ReLU between them), and y\mathbf{y} is the output. The addition is element by element, so F(x)F(\mathbf{x}) must have the same shape as x\mathbf{x}.

Why gradients survive

Backpropagation needs the derivative of the output with respect to the input. For one number flowing through a block, y=x+F(x)y = x + F(x), the derivative is

dydx=1+F′(x)\frac{dy}{dx} = 1 + F'(x)

That "1" comes from the skip connection, and it changes everything. A plain stack of nn layers passes a gradient back multiplied by F1′⋅F2′⋯Fn′F_1' \cdot F_2' \cdots F_n'. A residual stack multiplies by (1+F1′)(1+F2′)⋯(1+Fn′)(1 + F_1')(1 + F_2') \cdots (1 + F_n').

A worked example. Take 20 layers where each one's derivative is about 0.5:

  • Plain: 0.520≈0.000000950.5^{20} \approx 0.00000095. The first layer receives a millionth of the signal. In effect it never learns.
  • Residual, with each branch's derivative small, say +0.1+0.1 in ten blocks and −0.1-0.1 in the other ten: 1.110×0.910=2.594×0.349≈0.901.1^{10} \times 0.9^{10} = 2.594 \times 0.349 \approx 0.90. Almost all of the signal arrives.

Multiply out two blocks and you see why: (1+a)(1+b)=1+a+b+ab(1 + a)(1 + b) = 1 + a + b + ab. The term "1" is the path that skips both blocks, aa and bb are paths through one block each, and abab goes through both. A residual network with nn blocks contains 2n2^n 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 xl+1=xl+Fl(xl)\mathbf{x}_{l+1} = \mathbf{x}_l + F_l(\mathbf{x}_l) from block ll to the last block LL gives

xL=xl+∑i=lL−1Fi(xi)\mathbf{x}_L = \mathbf{x}_l + \sum_{i=l}^{L-1} F_i(\mathbf{x}_i)

The final output is the early representation plus a sum of corrections. The gradient of the loss with respect to xl\mathbf{x}_l therefore always contains the gradient with respect to xL\mathbf{x}_L 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:

1 10⁻⁴ 10⁻⁸ 10⁻¹² 10⁻¹⁶ 1 10 20 30 40 50 block number (1 = nearest the input, 50 = nearest the output) gradient size (log scale) with residual connections every block gets a gradient of about 1 plain network shrinks about 10× every 4–5 blocks on the way back first block: ~10⁻¹⁴, so it never learns
Fig. 2 Gradient size reaching each of 50 blocks, measured before training (log scale). In the plain network it shrinks by about ten times every four or five blocks on the way back, so the first block gets around 10⁻¹⁴. With residual connections, every block gets a gradient of about 1.

The plain network's early layers get gradients around 10−1410^{-14}, 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 x\mathbf{x} and F(x)F(\mathbf{x}) 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 x\mathbf{x} to fit: y=Wsx+F(x)\mathbf{y} = \mathbf{W}_s\mathbf{x} + F(\mathbf{x}). 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 FF, 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

x←x+Attention(LN(x)),x←x+MLP(LN(x))\mathbf{x} \leftarrow \mathbf{x} + \text{Attention}(\text{LN}(\mathbf{x})), \qquad \mathbf{x} \leftarrow \mathbf{x} + \text{MLP}(\text{LN}(\mathbf{x}))

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 x\mathbf{x}, 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 ln⁡2\ln 2: 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 1/N1/\sqrt{N} for NN 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 FF.
  • 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 x\mathbf{x} and F(x)F(\mathbf{x}). 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

  1. In the experiment, change nn.Tanh() to nn.ReLU() and the depth to 20, 50 and 100. At what depth does the plain network stop learning? Does the residual one?
  2. Print the size (norm) of the activations after every block of the residual network. Does it grow with depth? Try multiplying self.f(x) by 0.1.
  3. By hand: with each branch derivative equal to −0.5-0.5 in all 20 blocks, what is the product (1+F′)20(1 + F')^{20}? What does that tell you about whether residuals alone guarantee healthy gradients?

Hint for 3: 0.5200.5^{20} 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A plain 56-layer network has higher TRAINING error than a plain 20-layer one. What does this tell you?

  2. Twenty layers each have derivative about 0.5. Roughly how much of the gradient reaches the first layer in a plain stack?

  3. Why is it easy for a residual block to 'do nothing' when that is best?

  4. A ResNet block halves the image size and doubles the channels. What has to change in its shortcut?

  5. In a Transformer, what does the 'residual stream' view describe?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Paper

Identity Mappings in Deep Residual Networks

He, Zhang, Ren & Sun · 2016 · Advanced · Free

The follow-up to ResNet: keeping the shortcut a pure identity (pre-activation blocks) makes networks of 1,000+ layers train well.

Paper

Highway Networks

Srivastava, Greff & Schmidhuber · 2015 · Advanced · Free

Gated shortcut connections that let information and gradients bypass layers, published months before ResNet.

Article

Transformer Circuits Thread

Anthropic interpretability team · Advanced · Free

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