Simple Algorithm
Deep Learning · Representation · 22 min

Residual Connections

Skip connections, gradient highways and networks hundreds of layers deep.

In 2015, adding layers to a well-trained network made it worse, and worse on its own training data. The cure was a single addition: let every block add its output to its input. That identity path carries the gradient past every weight matrix, took networks from twenty layers to a thousand, and is the backbone of every transformer. It also creates a problem you will derive here: at initialization, variances pile up along the path.

What you’ll learn

  • Explain the degradation problem and why the evidence points to an optimization failure rather than overfitting, vanishing gradients or missing capacity.
  • Derive the forward and backward pass through a stack of residual blocks, show that the gradient at every block contains the top gradient unchanged, and explain why pre-activation blocks keep that identity exact.
  • Show that variances add along the residual path at initialization, derive how fast the signal grows with and without normalization inside the branches, and compare the remedies.
  • Build residual blocks in PyTorch, with projection shortcuts and zero-initialized branches, and connect them to the residual stream of a transformer.

When deeper was worse

By 2015, careful initialization and batch normalization had made plain networks of a few dozen layers trainable from scratch. Going further exposed something stranger than vanishing gradients. He, Zhang, Ren and Sun (2016) trained plain convolutional networks of 18 and 34 layers on ImageNet: the 34-layer network had the higher training error throughout training, and the worse validation error at the end (28.54% against 27.94% top-1). On CIFAR-10, plain networks of 20, 32, 44 and 56 layers ranked the same way: the deeper, the higher the training error. They called it the degradation problem.

Every obvious explanation fails:

  • Not overfitting. Overfitting leaves training error low and raises test error. Here the training error itself got worse.
  • Not missing capacity. Take the trained 18-layer network and insert 16 layers that compute the identity: you get a 34-layer network with exactly the same training error. The deeper network's solutions include the shallower one's.
  • Not vanishing signals. Batch normalization kept every layer's forward signal at a non-zero variance, and He et al. checked that the backpropagated gradients had healthy norms. Training three times longer did not close the gap.

What remains is optimization: gradient descent does not find the good solutions the deeper network contains. He et al. conjectured that deep plain networks converge exponentially slowly.

Think first F=H−xF = H - \mathbf x and HH describe the same function. Why should one be easier to learn than the other?

Because of where training starts and what is cheap to represent. For a block that should do almost nothing, a plain stack of convolutions, normalizations and ReLUs must tune all its weights so that the composition reproduces its input, and nothing in a random initialization favors that. A residual branch only has to output almost zero, which small weights (and weight decay) already push it toward. He et al. found exactly this in trained networks: residual layers responded more weakly than plain layers, and the deeper the ResNet, the less each layer changed the signal.

The reformulation reversed the result. With identity shortcuts and no extra parameters, the 34-layer ResNet beat the 18-layer one (25.03% against 27.88% top-1, 10-crop testing) and trained to a lower error than its plain twin. Networks of 152 layers followed, and an ensemble of ResNets won the ILSVRC 2015 classification task. On CIFAR-10, a 1,202-layer ResNet trained to under 0.1% training error with no optimization difficulty, though its test error (7.93%) was worse than a 110-layer network's (6.43%), which He et al. attributed to overfitting 19.4 million parameters to a small dataset.

Check your understanding

A 40-layer plain network reaches a higher training loss than a 20-layer version of the same design. Its gradient norms look normal at every layer, and training twice as long changes nothing. Which change addresses the cause most directly?

  1. Add dropout and stronger weight decay
  2. Double the width of every layer
  3. Wrap every pair of layers in an identity shortcut, so each block learns a residual
  4. Switch from He to Xavier initialization
Show the answer

C. Wrap every pair of layers in an identity shortcut, so each block learns a residual

Higher training loss with healthy gradients is the signature of degradation: the deeper network contains good solutions that the optimizer does not find. Shortcuts make the identity the default, so extra blocks start out harmless and only have to learn corrections.

The identity path, forward and backward

Write the network as residual blocks acting on a stream x0,x1,…,xL\mathbf x_0,\mathbf x_1,\dots,\mathbf x_L, in the form where nothing but an addition sits on the shortcut: xℓ+1=xℓ+Fℓ(xℓ)\mathbf x_{\ell+1} = \mathbf x_\ell + F_\ell(\mathbf x_\ell). Two lines of calculus show what the shortcut buys.

DerivationThrough a stack of residual blocks
  1. xL=xℓ+∑i=ℓL−1Fi(xi),in particularxL=x0+∑i=0L−1Fi(xi)\mathbf x_L = \mathbf x_\ell + \sum_{i=\ell}^{L-1}F_i(\mathbf x_i),\qquad\text{in particular}\quad\mathbf x_L = \mathbf x_0 + \sum_{i=0}^{L-1}F_i(\mathbf x_i)

    Unroll the recursion from any block ℓ\ell to the top. The output is the input plus a sum of branch outputs, and no matrix ever multiplies xℓ\mathbf x_\ell itself:

  2. ∂xL∂xℓ=(I+JL−1)⋯(I+Jℓ)=I+∑iJi+∑i<jJjJi+⋯+JL−1⋯Jℓ\frac{\partial\mathbf x_L}{\partial\mathbf x_\ell} = (I + J_{L-1})\cdots(I + J_\ell) = I + \sum_iJ_i + \sum_{i<j}J_jJ_i + \cdots + J_{L-1}\cdots J_\ell

    Differentiate. With Ji=∂Fi/∂xiJ_i = \partial F_i/\partial\mathbf x_i, one block's Jacobian is I+JiI + J_i, and the chain rule multiplies them. Expanding the product gives 2L−ℓ2^{L-\ell} terms, one for each subset of branches a signal can pass through:

  3. ∂ℓ∂xℓ=∂ℓ∂xL+∂ℓ∂xL ∂∂xℓ∑i=ℓL−1Fi(xi)\frac{\partial\ell}{\partial\mathbf x_\ell} = \frac{\partial\ell}{\partial\mathbf x_L} + \frac{\partial\ell}{\partial\mathbf x_L}\,\frac{\partial}{\partial\mathbf x_\ell}\sum_{i=\ell}^{L-1}F_i(\mathbf x_i)

    A plain network keeps only the last term, a product of L−ℓL - \ell Jacobians, which is what vanishes or explodes. Backward, as a row vector, the gradient at block ℓ\ell is the gradient at the top plus whatever flows through the branches:

  4. The first term reaches every block unchanged, whatever the weights. For the gradient at xℓ\mathbf x_\ell to vanish, the second term would have to cancel it exactly, for every example of a batch, which essentially never happens. As He et al. put it, a layer's gradient does not vanish even when the weights are arbitrarily small.

Check your understanding

In a residual network the gradient at block ℓ\ell is ∂ℓ∂xL(I+∂∂xℓ∑iFi)\frac{\partial\ell}{\partial\mathbf x_L}\big(I + \frac{\partial}{\partial\mathbf x_\ell}\sum_iF_i\big). What would it take for it to vanish?

  1. Every branch Jacobian JiJ_i would have to be zero
  2. The weights would have to be very small
  3. The branch term would have to equal −I-I along the incoming gradient, cancelling the identity, for essentially every example
  4. The network would have to be deeper than it is wide
Show the answer

C. The branch term would have to equal −I-I along the incoming gradient, cancelling the identity, for essentially every example

The identity term delivers ∂ℓ/∂xL\partial\ell/\partial\mathbf x_L untouched, so only an exact cancellation by the branch term could remove it. Zero branch Jacobians or tiny weights do the opposite: they leave the gradient equal to the top gradient.

The argument needs the shortcut to be exactly the identity. The original ResNet block was not: it applied a ReLU after the addition, xℓ+1=ReLU⁡(xℓ+F(xℓ))\mathbf x_{\ell+1} = \operatorname{ReLU}(\mathbf x_\ell + F(\mathbf x_\ell)), so the main path passed through a nonlinearity at every block that clips negative values. The follow-up paper (He, Zhang, Ren & Sun, 2016, "Identity mappings in deep residual networks") moved batch normalization and ReLU into the branch, before each convolution: the pre-activation block computes x+conv(ReLU(BN(conv(ReLU(BN(x))))))\mathbf x + \text{conv}(\text{ReLU}(\text{BN}(\text{conv}(\text{ReLU}(\text{BN}(\mathbf x)))))) and leaves the shortcut untouched. The benefit grew with depth: on CIFAR-10 the test error of a 110-layer network went from 6.61% to 6.37%, and of a 1,001-layer network from 7.61% to 4.92%; on CIFAR-100 the 1,001-layer network improved from 27.82% to 22.71%.

Transformers relearned the rule. The original transformer normalized after each addition, LN⁡(x+F(x))\operatorname{LN}(\mathbf x + F(\mathbf x)) (post-LN), which puts a normalization on the main path; the pre-LN block x+F(LN⁡(x))\mathbf x + F(\operatorname{LN}(\mathbf x)) keeps it clean. GPT-2 moved layer normalization to the input of each sub-block, in the authors' words "similar to a pre-activation residual network" (Radford et al., 2019). Normalization & Stability in Transformers follows what this choice does at scale.

Variances add up

The identity path fixes the backward pass but creates a forward problem. At initialization a branch computes a fresh random function of its input: if the last layer of the branch has zero-mean weights, F(x)F(\mathbf x) has mean zero and is uncorrelated with x\mathbf x. Cross terms vanish in expectation, so mean squares simply add, and the shortcut never removes anything.

DerivationHow the stream grows at initialization
  1. qℓ+1=qℓ+vℓq_{\ell+1} = q_\ell + v_\ell

    Write qℓ=E∥xℓ∥2/nq_\ell = \E\norm{\mathbf x_\ell}^2/n for the stream's mean square (width nn) and vℓ=E∥Fℓ(xℓ)∥2/nv_\ell = \E\norm{F_\ell(\mathbf x_\ell)}^2/n for the branch's. Because E[xℓ⊤Fℓ(xℓ)]=0\E[\mathbf x_\ell^\top F_\ell(\mathbf x_\ell)] = 0:

  2. qL=(1+c)L q0q_L = (1 + c)^L\,q_0

    No normalization. A branch initialized to preserve its input's scale (He or LeCun initialization inside it) outputs vℓ=c qℓv_\ell = c\,q_\ell with cc of order one, so every block multiplies the mean square by 1+c1 + c. Growth is exponential in depth, 2L2^L for c=1c = 1:

  3. qL=q0+L v,vqℓ≈1ℓq_L = q_0 + L\,v,\qquad\frac{v}{q_\ell}\approx\frac1\ell

    Normalization at the branch input (pre-activation batch normalization, or a pre-LN block). The branch now sees a normalized copy of the stream, so vℓ=vv_\ell = v no longer depends on qℓq_\ell, and the mean square grows only linearly. Block ℓ\ell adds a fraction v/qℓ≈1/ℓv/q_\ell\approx1/\ell of what is already there: deep blocks start close to the identity, and the network behaves like a shallower one at initialization (De & Smith, 2020, showed this for batch normalization):

  4. qL=(1+α2c)L q0,(1+cL)L≤ecq_L = (1 + \alpha^2c)^L\,q_0,\qquad\Big(1 + \frac cL\Big)^L\le e^c

    Scaled or zero-initialized branches. Multiply each branch by a constant α\alpha and the factor becomes 1+α2c1 + \alpha^2c. A branch whose last layer starts at zero, or that is multiplied by a learnable gate starting at zero, gives α=0\alpha = 0: an exact identity at initialization. And α=1/L\alpha = 1/\sqrt L keeps the growth bounded at any depth:

Predict before you look

In a pre-LN residual network the input has mean square 11, and each branch adds a mean square of 11 whatever the size of the stream. After 48 blocks, by what factor has the stream's RMS grown?

Show the answer

7 ×

q48=1+48×1=49q_{48} = 1 + 48\times1 = 49, so the RMS is 49=7\sqrt{49} = 7 times the input's. Without the normalization, with branches that preserve their input's scale (c=1c = 1), the same 48 blocks would multiply the mean square by 2482^{48} and the RMS by 224≈1.7×1072^{24}\approx1.7\times10^7.

Residual networks in practice

Changing shape. Inside a stage of a ResNet the shapes match and the shortcut is the identity. Where a stage halves the resolution and widens the channels, the shortcut must change shape too. He et al. compared three options on ImageNet: pad the new channels with zeros (A), project with a strided 1×11\times1 convolution only where the dimensions change (B), or project everywhere (C). ResNet-34 reached 25.03%, 24.52% and 24.19% top-1 error: all far below the plain network's 28.54% and close to one another, so projections are not what cures degradation, and B became the standard. Deeper ResNets use a bottleneck branch (1×11\times1 to reduce the channels, 3×33\times3, 1×11\times1 to restore them) to keep 50 to 152 layers affordable; CNN Architectures: LeNet to ConvNeXt counts the cost.

Transformers. A transformer is a residual network whose branches alternate between attention and a feed-forward layer. Each reads a normalized copy of the residual stream and adds its output back, so by the unrolled formula a token's final state is its embedding plus everything every sublayer wrote (The Transformer Block). Nothing is overwritten; a later layer can only add.

Starting at the identity. Zero-initialized branches are a one-line recipe. Goyal et al. (2017) set the scale γ\gamma of the last batch normalization in each residual block to 00, so that signals initially travel only through the shortcuts, which they found eased optimization early in training; torchvision's ResNets offer it as zero_init_residual=True. GPT-2 scaled the weights of its residual layers at initialization by 1/N1/\sqrt N, with NN the number of residual layers, to account for the accumulation along the residual path (Radford et al., 2019). Fixup and SkipInit go further and train deep ResNets with no normalization layers at all (Training Without Normalization), and ReZero multiplies every branch by a learnable scalar that starts at zero (Scaling Residual Branches with Depth).

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class ResidualBlock(nn.Module):
    """Pre-norm residual block h + W2·GELU(W1·LN(h)); the shortcut is an exact identity."""
    def __init__(self, d: int, zero_init: bool = True):
        super().__init__()
        self.norm = nn.LayerNorm(d)
        self.fc1, self.fc2 = nn.Linear(d, 4 * d), nn.Linear(4 * d, d)
        if zero_init:                       # the branch outputs 0: the block starts as the identity
            nn.init.zeros_(self.fc2.weight)
            nn.init.zeros_(self.fc2.bias)

    def forward(self, h):
        return h + self.fc2(F.gelu(self.fc1(self.norm(h))))

net = nn.Sequential(*[ResidualBlock(256) for _ in range(100)])
x = torch.randn(32, 256)
print(torch.equal(net(x), x))               # True: 100 blocks that start as the identity
net(x).pow(2).sum().backward()
print(net[0].fc1.weight.grad.abs().max())   # tensor(0.): fc2 = 0 blocks fc1's gradient at first
print(net[0].fc2.weight.grad.abs().max())   # positive: fc2 learns first, then fc1 follows

A zero last layer makes the block an identity without making it dead. The gradient reaches fc2 at once, because it multiplies the nonzero hidden activations; after one step fc2 is nonzero and passes gradient on to fc1. Since fc1 is random, the hidden units differ, so this is not the symmetry trap of all-zero initialization (Initialization & Vanishing Gradients).

Dropping branches. One regularizer depends on the shortcut directly: stochastic depth skips whole residual branches at random during training, which is harmless only because the shortcut keeps the network connected without them (Beyond Plain Residuals).

Why it works, and what is still open

No single explanation covers everything residual connections do. Four complementary ones each have evidence behind them:

  • Smoother loss surfaces. Li, Xu, Taylor, Studer and Goldstein (2018) plotted the loss landscape of CIFAR-10 networks along filter-normalized random directions. Without shortcuts the surface changed from nearly convex at 20 layers to chaotic at 56 and 110, and test error rose (13.31% and 16.44% without shortcuts, against 5.89% and 5.79% with them). With shortcuts, the 20- and 110-layer surfaces looked almost the same.
  • Short paths. The expansion of ∏(I+Ji)\prod(I + J_i) gives the gradient many short routes, and in trained ResNets most of it travels along them.
  • Gradients that keep their structure. In deep plain networks the gradients at two nearby inputs decorrelate exponentially with depth, until they look like white noise; with skip connections they decorrelate only sublinearly (Balduzzi et al., 2017).
  • Iterative refinement. Each block makes a small correction to a shared representation, and later blocks mostly polish it, which is why one can read a prediction off the middle of a network (Reading the Residual Stream).

A fifth view links depth to time. A block x+εf(x)\mathbf x + \varepsilon f(\mathbf x) is one forward-Euler step of size ε\varepsilon of the differential equation x˙=f(x,t)\dot{\mathbf x} = f(\mathbf x, t), and taking the limit literally gives neural ODEs (Chen, Rubanova, Bettencourt & Duvenaud, 2018). Whether a trained ResNet actually approximates such a limit depends on how its branches are scaled as depth grows, the question the first Emergence lesson below takes up.

Key takeaways

  • Deeper plain networks can reach higher training error than shallower ones (degradation): an optimization failure, not overfitting, missing capacity or vanishing signals.
  • A residual block computes x+F(x)\mathbf x + F(\mathbf x). Unrolled, xL=xℓ+∑iFi(xi)\mathbf x_L = \mathbf x_\ell + \sum_iF_i(\mathbf x_i), and the gradient at every block contains the top gradient unchanged, so it vanishes only if the branches cancel it exactly.
  • The shortcut must stay a pure identity: pre-activation ResNets and pre-LN transformers keep nonlinearities and normalization off the main path.
  • At initialization variances add along the stream: unnormalized branches multiply the mean square by 1+c1 + c per block, branches with normalized inputs add a constant (linear growth, each block about 1/ℓ1/\ell of the stream), and scaled or zero-initialized branches start near the identity.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

For blocks xi+1=xi+Fi(xi)\mathbf x_{i+1} = \mathbf x_i + F_i(\mathbf x_i) with Ji=∂Fi/∂xiJ_i = \partial F_i/\partial\mathbf x_i, what is ∂xL/∂xℓ\partial\mathbf x_L/\partial\mathbf x_\ell?

  1. JL−1JL−2⋯JℓJ_{L-1}J_{L-2}\cdots J_\ell
  2. I+JL−1JL−2⋯JℓI + J_{L-1}J_{L-2}\cdots J_\ell
  3. I+∑i=ℓL−1JiI + \sum_{i=\ell}^{L-1}J_i
  4. (I+JL−1)(I+JL−2)⋯(I+Jℓ)(I + J_{L-1})(I + J_{L-2})\cdots(I + J_\ell)
Show the answer

D. (I+JL−1)(I+JL−2)⋯(I+Jℓ)(I + J_{L-1})(I + J_{L-2})\cdots(I + J_\ell)

Each block's Jacobian is I+JiI + J_i and the chain rule multiplies them. Expanded, the product contains the identity, every single JiJ_i, every product of two, and so on: 2L−ℓ2^{L-\ell} terms, one per subset of branches.

Question 2

The original ResNet block computes ReLU⁡(x+F(x))\operatorname{ReLU}(\mathbf x + F(\mathbf x)); the pre-activation block computes x+F(x)\mathbf x + F(\mathbf x), with batch normalization and ReLU moved inside FF. Why did the change matter most for a 1,001-layer network?

  1. The pre-activation block has fewer parameters, so the deep network overfits less
  2. With a ReLU after every addition, the main path of the 1,001-layer network passes through 333 nonlinearities (one per residual unit) that clip negative values, so the identity term in the gradient is only approximate; moving them into the branch makes the path an exact identity
  3. Batch normalization is cheaper to compute before a convolution than after it
  4. ReLU after the addition caused the activations to explode with depth
Show the answer

B. With a ReLU after every addition, the main path of the 1,001-layer network passes through 333 nonlinearities (one per residual unit) that clip negative values, so the identity term in the gradient is only approximate; moving them into the branch makes the path an exact identity

The gradient formula ∂ℓ/∂xℓ=∂ℓ/∂xL(I+… )\partial\ell/\partial\mathbf x_\ell = \partial\ell/\partial\mathbf x_L(I + \dots) holds exactly only if the main path is a pure sum. Each post-addition ReLU zeroes the gradient wherever its input is negative, and over hundreds of blocks those losses add up. On CIFAR-10 the 1,001-layer network improved from 7.61% to 4.92% test error.

Question 3

At initialization, a residual network's branches each output a mean square equal to their input's (c=1c = 1). How does the stream's mean square change over 30 blocks, without normalization, and with LayerNorm at each branch input (each branch then adds 11, starting from 11)?

  1. By about 3030 in both cases
  2. By 230≈1092^{30}\approx10^9 without normalization, and to 3131 with it
  3. By 2302^{30} in both cases: normalization inside the branch does not touch the shortcut
  4. It stays constant without normalization and grows to 3131 with it
Show the answer

B. By 230≈1092^{30}\approx10^9 without normalization, and to 3131 with it

Mean squares add because a branch's output is uncorrelated with its input at initialization. Unnormalized, each block adds as much as is already there, doubling the total; with a normalized input, each block adds a fixed amount, so growth is linear.

Question 4

The last linear layer of every residual branch is initialized to zero, while the branch's first layer is random. What happens at the first gradient step?

  1. Nothing in the branch can learn, because the branch outputs zero
  2. All units of the branch receive identical gradients forever, as with all-zero initialization
  3. The gradient bypasses the block through the shortcut, so the branch's weights never train
  4. The zero last layer gets a nonzero gradient and moves; the earlier layers get zero gradient at this step and start learning once the last layer is nonzero
Show the answer

D. The zero last layer gets a nonzero gradient and moves; the earlier layers get zero gradient at this step and start learning once the last layer is nonzero

The last layer's gradient is the incoming gradient times the branch's hidden activations, which are nonzero because the first layer is random. The earlier layers' gradient passes through the last layer's weights, which are still zero, so it starts one step later. Meanwhile the block is an exact identity, so the network starts shallow.

Go deeper

Further reading

  • K. He, X. Zhang, S. Ren & J. Sun, "Deep residual learning for image recognition," CVPR (2016).
  • K. He, X. Zhang, S. Ren & J. Sun, "Identity mappings in deep residual networks," ECCV (2016).
  • S. J. D. Prince, Understanding Deep Learning, ch. 11 "Residual networks" (MIT Press, 2023), free at udlbook.github.io/udlbook.