Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Residual connections

P4.2040 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A residual connection adds a layer's input to its output, so the gradient has a direct path back through the whole stack and very deep networks become trainable. The change is one addition, and it is in almost every deep network in use.

  • Residual networks put a skip connection around every pair of convolutions, which is how image models with tens or hundreds of layers are trained. (P5.9: The CNN architecture tour)
  • Every transformer block adds the output of attention and of the feed-forward part back to its input. (P7.7: The transformer block, coming soon)
  • Large language models keep one running vector that each layer reads from and adds to. (P10.A4: The residual stream view, coming soon)
  • The product of Jacobians that makes gradients fade or blow up gets an identity term when a skip is added. (P4.16: Vanishing and exploding gradients)

Before this: Vanishing and exploding gradients, Backpropagation: step by step with numbers, Normalization layers, Vector functions and the Jacobian

After this lesson you can

  • Describe the degradation problem and explain why it is not overfitting
  • Write a residual block, explain “learning the residual”, and say when a projection is needed
  • Derive the backward pass through a residual block, expand the product over blocks, and say what the identity term does and does not guarantee
  • Name the ways real networks keep the sum of paths under control (zero-initialized last layer, scaled branch, normalization) and show their effect in the widget

In 2015, He, Zhang, Ren and Sun trained two plain networks on CIFAR-10 (small colour images in ten classes): one with 20 layers and one with 56. The 56-layer network, which can represent everything the 20-layer one can, ended with a higher training error, and therefore a higher test error. A bigger model that does worse on the data it was trained on is not overfitting. Something stops the training.

Their fix was a single addition. Each block of layers gets a copy of its own input added to its output, and the deep networks then trained and got better with depth. You can see the same effect in the widget below with numbers. In a stack of 24 plain blocks at weight scale 0.80.8, the gradient at the input is 3.9×10−73.9\times10^{-7} times the gradient at the output. Add the “+x+\mathbf{x}” to every block and the ratio becomes 25. Zero-initialize the last layer of each block and it is exactly 1.

This lesson explains why the addition works, why it does not work alone, and what real networks do about that.

The degradation problem

A plain network is a stack of layers, each feeding the next. Take a shallow plain network and make it deeper by adding layers. You might expect the training error to stay the same or go down: the deeper network could copy the shallow one and make every added layer an identity (output equal to input). That network exists, so the best deep network cannot be worse on the training data than the shallow one.

Yet the experiments of He et al. showed the opposite:

  • On CIFAR-10, a 56-layer plain network had higher training error than a 20-layer one.
  • On ImageNet, a 34-layer plain network had higher training error than an 18-layer one throughout training, and training three times longer did not remove the gap.

They called this the degradation problem: as depth grows, accuracy saturates and then drops, and it drops on the training set, so the cause is not overfitting. The optimizer does not find a solution that is known to exist. He et al. suggest that stacked nonlinear layers have difficulty approximating the identity.

One more point from the same paper corrects a common guess. The authors argue that the degradation is unlikely to be caused by vanishing gradients. Their plain networks used BatchNorm (P4.19), which keeps the forward signal at a healthy size, and they checked that the backward gradients also had healthy norms. So the identity path is not only a vanishing-gradient repair. It also gives the network an easy way to carry a signal forward unchanged.

The residual block

A residual block computes

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

where FF is a few ordinary layers (the branch) and the plain addition of x\mathbf{x} is the skip connection. A tiny example: if x=(1,0)\mathbf{x}=(1,0) and the branch outputs F(x)=(0.80,1.20)F(\mathbf{x})=(0.80,1.20), the block outputs (1.80,1.20)(1.80,1.20). This is the example of the linear-algebra map (P1.B2). The addition is an element-wise sum, so x\mathbf{x} and F(x)F(\mathbf{x}) must have the same shape.

Learning the residual. Suppose the best function for this part of the network is H(x)H(\mathbf{x}). A plain block must learn HH itself. A residual block learns F=H−xF=H-\mathbf{x}, the difference from its input. If the best HH is close to the identity, then FF only has to be close to zero, and zero is easy to reach: set the weights of the last layer of the branch to zero, or let them shrink. He et al. state this as a hypothesis (it is easier to push the residual to zero than to fit an identity with a stack of nonlinear layers) and back it with experiments. The block can represent exactly the same functions as a plain block, since H=x+FH=\mathbf{x}+F. What changes is how easily the optimizer finds a good one.

When the shapes differ. If a block changes the width (or the number of channels in an image), x\mathbf{x} cannot be added to F(x)F(\mathbf{x}) directly. The standard fix is a projection shortcut: pass x\mathbf{x} through a linear layer (a 1×11\times1 convolution for images, P5.5) so that its shape matches. ResNets use identity shortcuts everywhere else, and the original paper found that projections everywhere helped only a little.

In the original ResNet block, the branch is convolution, BatchNorm, ReLU, convolution, BatchNorm, and a ReLU is applied after the addition. BatchNorm follows almost every convolution in these networks, and that is part of the recipe (P4.19).

The backward pass: an identity term

Now the part that matters for training. Write J=∂F/∂x\mathbf{J}=\partial F/\partial\mathbf{x} for the Jacobian of the branch (P1.C7), as in P4.16. The derivative of x+F(x)\mathbf{x}+F(\mathbf{x}) with respect to x\mathbf{x} is the identity matrix plus the derivative of FF:

∂y∂x=I+J.\frac{\partial\mathbf{y}}{\partial\mathbf{x}}=\mathbf{I}+\mathbf{J}.

The gradient (P4.8) therefore passes back through a block as

gℓ−1=(I+Jℓ)⊤gℓ=gℓ+Jℓ⊤gℓ.\mathbf{g}_{\ell-1}=(\mathbf{I}+\mathbf{J}_\ell)^\top\mathbf{g}_\ell=\mathbf{g}_\ell+\mathbf{J}_\ell^\top\mathbf{g}_\ell .

The incoming gradient gℓ\mathbf{g}_\ell is copied unchanged, and the part that goes through the weights is added to it. In a plain block only the second term exists.

Many blocks. The Jacobian of KK blocks in a row is a product, and for three blocks it expands exactly as in P4.16 (a recap; the numbers here differ from P4.16’s because the blocks and weights differ):

(I+J3)(I+J2)(I+J1)=I+J3+J2+J1+J3J2+J3J1+J2J1+J3J2J1.\begin{aligned} &(\mathbf{I}+\mathbf{J}_3)(\mathbf{I}+\mathbf{J}_2)(\mathbf{I}+\mathbf{J}_1)\\ &=\mathbf{I}+\mathbf{J}_3+\mathbf{J}_2+\mathbf{J}_1\\ &\quad+\mathbf{J}_3\mathbf{J}_2+\mathbf{J}_3\mathbf{J}_1+\mathbf{J}_2\mathbf{J}_1\\ &\quad+\mathbf{J}_3\mathbf{J}_2\mathbf{J}_1 . \end{aligned}

There are 23=82^3=8 terms, one for each way to send the signal through some blocks and around the others. The first term is I\mathbf{I}: the path that goes around every block. It has no factors, so the gradient that travels along it arrives at layer 1 with the same size it had at the output, however many blocks there are. A plain stack has only the last term, the one that passes through every block.

One number per block

Take the simplest case from P4.16: every block has the same Jacobian, a single number JJ, and there are 20 blocks. The gradient is multiplied by J20J^{20} in a plain stack and by (1+J)20(1+J)^{20} in a residual stack:

  • J=0.5J=0.5: plain 0.520≈9.5×10−70.5^{20}\approx9.5\times10^{-7}, residual 1.520≈33251.5^{20}\approx3325.
  • J=0.05J=0.05: plain 0.0520≈10−260.05^{20}\approx10^{-26}, residual 1.0520≈2.651.05^{20}\approx2.65.
  • J=−0.5J=-0.5: plain 9.5×10−79.5\times10^{-7}, residual (1−0.5)20=9.5×10−7(1-0.5)^{20}=9.5\times10^{-7}.

The first two lines show two things at once. The skip removes the fading: a plain stack with a factor of 0.05 per block has nothing left, a residual stack keeps a gradient of about 2.65. It also lets the gradient grow: with J=0.5J=0.5 the residual stack multiplies by 3325, and the larger the Jacobians, the faster. The third line is a warning in the other direction. The identity term is always there, but the other terms can be negative and cancel it. Here 1+J=0.51+J=0.5 and the total fades again. The identity path guarantees one term of the sum, not the sum.

So the skip is a necessary start and not a finish. Real Jacobians are matrices with both signs, and the size of the sum depends on how large J\mathbf{J} is. The rest of the lesson is about keeping it small enough.

See it: gradient flow with and without skips

The widget builds a stack of 4 to 24 blocks. Each block has two weight layers and a ReLU, F(h)=W2 relu(W1h)F(\mathbf{h})=\mathbf{W}_2\,\mathrm{relu}(\mathbf{W}_1\mathbf{h}) with 12 units, and a plain block outputs F(h)F(\mathbf{h}) while a residual block outputs h+F(h)\mathbf{h}+F(\mathbf{h}). The task is a made-up regression on 32 points. The top chart sends one backward pass from the output (right) to the input (left) at initialization, and each orange bar is the length of the gradient at that depth. The bottom chart trains the plain stack and the residual stack for 300 steps and draws both loss curves.

Zero-init and the branch scale change the residual branch only, so they do nothing while skips are off (the training run below still uses them for its residual stack).

seed 1 of 3
05101520−15−10−50510

Bar height: the length of the gradient as a power of 10 (0 means length 1). The right-hand bar is at the output of the last block, the left-hand bar is at the input of the first. The pass travels right to left. Skip off: every block multiplies the gradient by its own factor. A small triangle on a bar means the value is off the scale.

  • Gradient at the output0.628
  • Gradient at the input2.45e−7
  • Input ÷ output3.90e−7
  • Loss before training1.56

The gradient fades: the first block gets almost nothing.

Train it: plain against residual

Same depth, same starting weights, same 32 made-up points, 300 steps of plain gradient descent with learning rate:

050100150200250300−20246

Loss as a power of 10 (0 means a loss of 1; −3 means 0.001). A curve that jumps off the top blew up and stops there.

  • Plain stack (dashed, circle end)
  • Residual stack (solid, square end)
  • Plain: loss after 300 steps…
  • Residual: loss after 300 steps…

Press Train to compare them.

Show the gradient length at every position
PositionLength
input2.45e−7
after block 16.62e−7
after block 21.53e−6
after block 31.99e−6
after block 45.58e−6
after block 52.13e−5
after block 65.51e−5
after block 75.92e−5
after block 84.18e−5
after block 95.06e−5
after block 101.28e−4
after block 113.37e−4
after block 123.89e−4
after block 134.67e−4
after block 140.00126
after block 150.00159
after block 160.0061
after block 170.0115
after block 180.0185
after block 190.0126
after block 200.0229
after block 210.0907
after block 220.174
after block 230.268
after block 24 (output)0.628

Each block has two weight layers: F(h) = W2 relu(W1 h), 12 units wide. A plain block outputs F(h); a residual block outputs h + F(h). The gradient length is the length of ∂L/∂h over all 32 points. Weight scale ×1 is He's rule (P4.12). In Lite Mode, Play shows the final bars at once and training draws only the finished curves.

Gradient flow with and without skips. Top: the length of the gradient at the input and after every block, from one backward pass at initialization, on a log scale (orange bars). With skips on, the long arrow is the direct path, the small arcs are the skips around the blocks, and the dashed line is the length that the direct path alone delivers. Switch skips on, zero-init the last layer of each block, or scale the branch by one over the square root of the number of blocks. Bottom: the same stack trained by gradient descent, plain (dashed, circle) against residual (solid, square). In Lite Mode, Play shows the final bars at once and training draws only the finished curves.

What the widget shows with its default random weights (seed 1; running the same algorithm in NumPy reproduces every number):

  1. Skip off, 24 blocks, weight scale ×0.8. The gradient is 0.6280.628 at the output and 2.45×10−72.45\times10^{-7} at the input, a ratio of 3.9×10−73.9\times10^{-7}, or about ×0.54\times0.54 per block. The first blocks get almost nothing.
  2. Skip on. The ratio becomes 25: the gradient is 19.9619.96 at the output and 499499 at the input. The dashed line shows what the identity path delivers, 19.9619.96 at every depth, and the bars above it are the other terms. The fading is gone, and the gradient has grown instead.
  3. Zero-init last layer. With skips on, tick Zero-init last layer. With the last layer of every branch set to zero, F=0F=0 at the start, every block is the identity, and every bar is exactly the same height: ratio 1. The gradient then reaches every block unchanged, and training can begin from there.
  4. Branch ÷ √blocks. Each branch’s last layer is scaled by 1/241/\sqrt{24}, and the ratio is 1.321.32.
  5. Raise the scale to ×1.0 with skips on. The ratio is 1633 and the loss before training is 2.7×1062.7\times10^{6}. With skips off at ×1.0 the plain ratio is 0.01750.0175. A larger scale makes J\mathbf{J} larger, so the other terms of the sum are larger too.
  6. Training at learning rate 0.003 (24 blocks, ×0.8). The plain stack stays at a loss of 1.561.56 for all 300 steps. That is the loss of predicting 0 for every point (the mean of y2y^2): its output is almost zero and its gradients are too small to move the early layers. The residual stack with no other change blows up: the loss is 15771577 at the start and 5×10575\times10^{57} after one step. With zero-init the final loss is 0.01330.0133, and with the branch scale it is 0.008780.00878. The residual curves can jump up for a few steps and then fall again (for example near steps 130 and 240 with zero-init): at this learning rate the sum of paths briefly becomes too large. The final loss is what to compare.
  7. Shallower. At 8 blocks and ×0.8 the residual stack trains without any help (final loss 0.007310.00731), because there are fewer terms to add up, while the plain stack is still at 1.561.56.

These are one made-up task, one learning rate and one set of seeds, and nothing was tuned: a carefully tuned plain network would do better than the plain curve here. What the run shows is the pattern. A skip stops the fading, it can make the sum too large, and starting each branch small fixes that.

Keeping the sum under control

The identity term is one path out of 2K2^K. The sum of the others can be large when the branches are large, as items 2, 5 and 6 above show. Real networks therefore start each branch small, so that the sum starts close to the identity and grows only as the branches learn.

A model shows the size. Suppose the branch Jacobians are independent numbers with mean 0 and standard deviation ss (a simplification: real Jacobians are matrices and are not independent). Then the mean square of ∏(1+Jℓ)\prod(1+J_\ell) over KK blocks is (1+s2)K(1+s^2)^K, because each factor multiplies the mean square by 1+s21+s^2. With s=0.2s=0.2 and 20 blocks the root mean square is 1.481.48, while the plain product is about 10−1410^{-14}. For the sum to stay bounded as the depth grows, s2s^2 has to shrink like 1/K1/K, which means s∝1/Ks\propto1/\sqrt{K}. With s=0.5/20s=0.5/\sqrt{20} the value is 1.131.13. The same reasoning applies to the forward signal: each block adds a branch to the running vector, so its size grows with depth unless the branches are small.

The methods used in practice all make the branch small at the start:

  • Zero-initialize the last layer of each branch. The block starts as the identity. Goyal et al. (2017) did this for ResNets by setting γ=0\gamma=0 in the last BatchNorm of every residual block, so that the signal “initially propagates through the identity shortcut”, and found it eased optimization. Fixup (Zhang, Dauphin and Ma, ICLR 2019) uses the same rule and adds a scaling of the other layers.
  • Scale the branch by about 1/N1/\sqrt{N}, for NN residual layers. The GPT-2 paper states that it scales the weights of residual layers at initialization by 1/N1/\sqrt{N} (P4.12). This is the s∝1/Ks\propto1/\sqrt{K} of the model above. The widget’s “Branch ÷ √blocks” switch does exactly this.
  • Normalization inside the branch (P4.19) keeps the size of the values it normalizes standard. In a pre-norm transformer block that is the branch’s input, and the branch’s output can still be large. In a ResNet block the last BatchNorm sets the size of the branch’s output through its γ\gamma, which is why γ=0\gamma=0 there makes the block start as the identity. A normalization layer alone does not make the sum of paths small.
  • A modest learning rate and warmup (P4.14). A large step can undo a careful start.

A branch that starts at zero still learns: its last layer receives a gradient from the first step (the gradient of W2\mathbf{W}_2 is the incoming gradient times the branch’s hidden activations, neither of which is zero), and the first layers of the branch receive gradient as soon as W2\mathbf{W}_2 moves.

Where it appears

Residual networks are the family of image models built from the block above. He et al. trained residual nets with up to 152 layers on ImageNet, an ensemble of which won the 2015 ImageNet classification competition, and reported residual networks of over 1000 layers on CIFAR-10. P5.9 puts them in the tour of CNN architectures.

Pre-activation. In a follow-up (ECCV 2016) the same group moved BatchNorm and ReLU to the start of the branch so that nothing sits after the addition. Then xℓ+1=xℓ+F(xℓ)\mathbf{x}_{\ell+1}=\mathbf{x}_\ell+F(\mathbf{x}_\ell) exactly, and they showed that the signals pass directly between any two blocks, forward and backward.

Transformers. A transformer block applies the same idea twice. In the pre-norm form that GPT-2 used (P4.19),

x←x+Attention(LN(x)),x←x+MLP(LN(x)).\begin{aligned} \mathbf{x}&\leftarrow\mathbf{x}+\mathrm{Attention}\bigl(\mathrm{LN}(\mathbf{x})\bigr),\\ \mathbf{x}&\leftarrow\mathbf{x}+\mathrm{MLP}\bigl(\mathrm{LN}(\mathbf{x})\bigr). \end{aligned}

The LayerNorm is inside the branch, so the skip path carries x\mathbf{x} unnormalized from the input to the output of the stack. The original transformer was post-norm, LN(x+F(x))\mathrm{LN}(\mathbf{x}+F(\mathbf{x})), which puts a LayerNorm on the skip path itself. P7.7 builds the block and compares the two, and P10.A4 treats the running vector as a place where layers read and write.

Go deeper Pre-activation ResNets: the exact identity path

If both the skip and the function applied after the addition are identities, then xℓ+1=xℓ+F(xℓ)\mathbf{x}_{\ell+1}=\mathbf{x}_\ell+F(\mathbf{x}_\ell) for every block, and unrolling gives xK=xℓ+∑i=ℓK−1F(xi)\mathbf{x}_K=\mathbf{x}_\ell+\sum_{i=\ell}^{K-1}F(\mathbf{x}_i) for any earlier block ℓ\ell. The chain rule then gives

∂E∂xℓ=∂E∂xK(1+∂∂xℓ∑i=ℓK−1F(xi)),\frac{\partial\mathcal{E}}{\partial\mathbf{x}_\ell}=\frac{\partial\mathcal{E}}{\partial\mathbf{x}_K}\left(1+\frac{\partial}{\partial\mathbf{x}_\ell}\sum_{i=\ell}^{K-1}F(\mathbf{x}_i)\right),

where E\mathcal{E} is the loss (the paper’s symbol). The first term, ∂E/∂xK\partial\mathcal{E}/\partial\mathbf{x}_K, reaches every block directly. In the original block, the ReLU after the addition sits on the skip path, so the gradient meets a ReLU slope (0 or 1) at every block along the way. The authors report that the pre-activation form trained a 1001-layer network on CIFAR-10 and gave better results than the original.

Go deeper Residual networks as a crowd of short paths

Expanding the product gives 2K2^K paths, each passing through some blocks and around the others. Veit, Wilber and Belongie (NeurIPS 2016) used this view to explain several observations. Deleting a single block from a trained ResNet at test time cost only a little accuracy, whereas deleting any single layer from a 15-layer VGG network (a plain stack) dropped it to chance level. And in a 110-layer ResNet, most of the gradient came from paths only 10 to 34 layers deep (the network has 54 two-layer blocks): the long paths exist but carry almost none of it. They concluded that residual networks do not so much learn one very deep function as a collection of paths of many lengths that behave a little like an ensemble. This is a way to look at the network, and not a complete account of why it trains.

Go deeper Highway networks, DenseNet and other ways to connect layers

Highway networks (Srivastava, Greff and Schmidhuber, 2015) came first and use a learned gate to decide how much of the input to carry and how much to transform. They trained hundreds of layers with plain gradient descent. A residual block is the ungated case: the carry is always the full input, which is simpler and has no extra parameters. The same carry idea appears in gated recurrent cells (P6.7). DenseNet (Huang et al., CVPR 2017) connects each layer to all earlier layers by concatenating their feature maps instead of adding them. U-Net skips, which join an early feature map to a later one in image segmentation, are covered in P5.13.

Depth: three ways to see it

Intuition

A residual stack is a motorway beside a winding road. The winding road (the branch FF) can change the traffic on the way: it picks things up and puts new things down. The motorway carries the traffic straight through, and at every junction the two flows are added. A message from the last block to the first can go along the motorway without passing a single junction, which is why it arrives at full size.

The picture breaks in two places. The flows are added, not chosen between, so a big winding-road flow shows up in the total, which is why a skip alone can make the gradient too large. And the motorway only helps while it is clear: in a post-norm transformer, the skip path passes through a LayerNorm at every block, and the clean road is gone.

Math

Unrolling hℓ=hℓ−1+Fℓ(hℓ−1)\mathbf{h}_\ell=\mathbf{h}_{\ell-1}+F_\ell(\mathbf{h}_{\ell-1}) over KK blocks gives the forward sum

hK=h0+∑ℓ=1KFℓ(hℓ−1).\mathbf{h}_K=\mathbf{h}_0+\sum_{\ell=1}^{K}F_\ell(\mathbf{h}_{\ell-1}).

Writing Jℓ=∂Fℓ/∂hℓ−1\mathbf{J}_\ell=\partial F_\ell/\partial\mathbf{h}_{\ell-1}, the Jacobian of the whole stack is ∂hK/∂h0=(I+JK)⋯(I+J1)\partial\mathbf{h}_K/\partial\mathbf{h}_0=(\mathbf{I}+\mathbf{J}_K)\cdots(\mathbf{I}+\mathbf{J}_1), which expands into the sum over all 2K2^K subsets of blocks of the ordered product of their J\mathbf{J}, starting with I\mathbf{I}. The gradient is its transpose times gK\mathbf{g}_K:

g0=gK+∑ℓJℓ⊤gK+⋯ .\mathbf{g}_0=\mathbf{g}_K+\sum_\ell\mathbf{J}_\ell^\top\mathbf{g}_K+\cdots .

In the widget a block is F(h)=W2DW1hF(\mathbf{h})=\mathbf{W}_2\mathbf{D}\mathbf{W}_1\mathbf{h} locally, with D=diag(ϕ′(W1h))\mathbf{D}=\mathrm{diag}(\phi'(\mathbf{W}_1\mathbf{h})) the ReLU slopes (0 or 1), so J=W2DW1\mathbf{J}=\mathbf{W}_2\mathbf{D}\mathbf{W}_1. If the branch outputs have independent zero-mean contributions, their variances add: with branch variance cc times the input’s, Var(hK)≈(1+c)KVar(h0)\mathrm{Var}(\mathbf{h}_K)\approx(1+c)^K\mathrm{Var}(\mathbf{h}_0), and c=1/Kc=1/K gives (1+1/K)K→e(1+1/K)^K\to e. This is the reason for the 1/K1/\sqrt{K} scale on the branch weights, since a branch output that is linear in its weights has variance scaling as the weights squared.

Code

A pre-norm residual block in PyTorch. The last layer of the branch starts at zero, so the block starts as the identity.

import torch
import torch.nn as nn

class ResBlock(nn.Module):
    """Pre-norm residual block: y = x + F(LayerNorm(x))."""
    def __init__(self, d, zero_init=True):
        super().__init__()
        self.norm = nn.LayerNorm(d)
        self.fc1 = nn.Linear(d, 4 * d)
        self.fc2 = nn.Linear(4 * d, d)
        if zero_init:                    # the branch starts as F = 0
            nn.init.zeros_(self.fc2.weight)
            nn.init.zeros_(self.fc2.bias)

    def forward(self, x):
        return x + self.fc2(torch.relu(self.fc1(self.norm(x))))

torch.manual_seed(0)
d = 4
block = ResBlock(d)
x = torch.randn(3, d)
print("shapes:", tuple(x.shape), "->", tuple(block(x).shape))
print("parameters:", sum(p.numel() for p in block.parameters()))
print("zero-init: block(x) == x ?", torch.equal(block(x), x))

J = torch.autograd.functional.jacobian(block, x[0])
print("dy/dx at init is the identity ?", torch.allclose(J, torch.eye(d)))

nn.init.normal_(block.fc2.weight, std=0.5)   # a branch with weights
J = torch.autograd.functional.jacobian(block, x[0])
print("dy/dx row 0, branch on:", J[0].detach().numpy().round(2))

deep = nn.Sequential(*[ResBlock(d) for _ in range(50)])   # 50 blocks
x = torch.randn(1, d, requires_grad=True)
deep(x).sum().backward()
print("50 blocks, zero-init, grad of sum:", x.grad[0].numpy())

Output from a local run with PyTorch 2.9.1:

shapes: (3, 4) -> (3, 4)
parameters: 156
zero-init: block(x) == x ? True
dy/dx at init is the identity ? True
dy/dx row 0, branch on: [ 2.25  1.07 -0.8  -1.52]
50 blocks, zero-init, grad of sum: [1. 1. 1. 1.]

The 156 parameters are the LayerNorm’s γ\gamma and β\beta (88), the first linear layer (4⋅16+16=804\cdot16+16=80) and the second (16⋅4+4=6816\cdot4+4=68). After 50 zero-initialized blocks the gradient of the output sum at the input is still exactly (1,1,1,1)(1,1,1,1). A block is an ordinary module: the only unusual line is x + ....

Try it in Python

The first cell is the scalar picture: one Jacobian number per block, then random Jacobians with standard deviation ss to check the (1+s2)K(1+s^2)^K rule. The second trains a 24-block plain stack and a residual stack on the same made-up task as the widget, with its own NumPy random numbers, so the figures differ from the widget’s.

One number per block, and random Jacobians

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives, for J=0.5J=0.5, −0.5-0.5 and 0.050.05: J20=9.54×10−7J^{20}=9.54\times10^{-7}, 9.54×10−79.54\times10^{-7} and 9.5×10−279.5\times10^{-27} in the plain stack, and (1+J)20=3325(1+J)^{20}=3325, 9.5×10−79.5\times10^{-7} and 2.6532.653 in the residual stack. For random Jacobians with s=0.2s=0.2 the root mean square of the residual product is 1.4771.477 (theory 1.4801.480) against about 10−1410^{-14} for the plain one. With s=0.5/20s=0.5/\sqrt{20} it is 1.1311.131 (theory 1.1321.132).

Plain, residual and zero-init: gradients and training

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives: predicting 0 for every point has loss 0.4490.449. The gradient length at depths 0, 8, 16 and 24 is 8.3×10−88.3\times10^{-8}, 1.5×10−51.5\times10^{-5}, 0.0050.005 and 0.230.23 for the plain stack, 200200, 6666, 1919 and 4.64.6 for the residual stack, and 0.440.44 at every depth for the zero-initialized one. In training, the plain stack stays at 0.4490.449 (it predicts about 0 and the early layers do not move), the residual stack starts at 639639 and blows up at step 1, and the zero-initialized one goes from 0.5770.577 to 0.160.16 at step 100 and 0.07950.0795 at step 300.

Common mistakes

Quiz

Check your understanding

  1. A 56-layer plain network has a higher training error than a 20-layer one. Why does this rule out overfitting as the explanation?

  2. A stack of 4 residual blocks has F(x)=0.5xF(x)=0.5x in every block (single numbers). By what factor is the gradient multiplied between the output and the input?

  3. The last layer of the branch in every residual block is initialized to zero. What does the network compute at the start of training?

  4. In the widget, 24 blocks with skip connections at weight scale ×1.0 give a gradient at the input that is about 1633 times the gradient at the output. Which statement is correct?

  5. In a pre-norm transformer block, x←x+Attention(LN(x))\mathbf{x}\leftarrow\mathbf{x}+\mathrm{Attention}(\mathrm{LN}(\mathbf{x})). Where does the LayerNorm sit with respect to the skip path?

Exercises

  1. Ten blocks each have the Jacobian J=0.3J=0.3 (a single number). What is the gradient factor of a plain stack and of a residual stack?
    Show answerPlain: 0.310=5.9×10−60.3^{10}=5.9\times10^{-6}. Residual: 1.310≈13.81.3^{10}\approx13.8. The skip changes a fading gradient into a mildly growing one.
  2. A residual block has the Jacobian J=diag(0.5,−1)\mathbf{J}=\mathrm{diag}(0.5,-1). The incoming gradient is g=(1,1)\mathbf{g}=(1,1). What is the gradient passed back? Which part of it is lost, and why?
    Show answer(I+J)⊤g=diag(1.5,0) (1,1)=(1.5,0)(\mathbf{I}+\mathbf{J})^\top\mathbf{g}=\mathrm{diag}(1.5,0)\,(1,1)=(1.5,0). The second component is lost: 1+(−1)=01+(-1)=0, so the branch exactly cancels the skip in that direction. The identity path is present but not guaranteed to survive the other terms.
  3. A block takes a vector of 64 numbers, and its branch outputs 128 numbers. What goes wrong with x+F(x)\mathbf{x}+F(\mathbf{x}), and what is the usual fix? What does the fix do to the identity path?
    Show answerThe vectors have different lengths, so they cannot be added. A projection shortcut uses a 128×64128\times64 matrix Ws\mathbf{W}_s (a linear layer, or a 1×11\times1 convolution for images) and computes Wsx+F(x)\mathbf{W}_s\mathbf{x}+F(\mathbf{x}). The skip path then multiplies the gradient by Ws⊤\mathbf{W}_s^\top and is no longer an exact identity, which is why ResNets use projections only where the shape changes.
  4. Each block adds a branch whose output has a variance cc times the variance of its input, so the variance of the running vector is multiplied by 1+c1+c per block. What is the total factor after 24 blocks with c=1c=1 and with c=1/24c=1/24?
    Show answer224≈1.7×1072^{24}\approx1.7\times10^{7} with c=1c=1, and (1+1/24)24≈2.66(1+1/24)^{24}\approx2.66 with c=1/24c=1/24. Scaling the branch so that its variance is about 1/K1/K of the input’s keeps the total near a constant, which is the 1/K1/\sqrt{K} scale on the branch’s weights.
  5. A zero-initialized last layer makes the whole branch output zero at the start. Why does the branch still learn?
    Show answerThe gradient of the last layer’s weights is the incoming gradient times the hidden activations of the branch, and neither is zero, so those weights move on the first step. Once they are not zero, the first layers of the branch receive gradient too. The zero only removes the branch’s contribution to the output, not its gradient.

Next: P4.21 turns to embedding layers, which look up a learned vector for each token or category. P7.7 puts residual connections, LayerNorm and attention together in one transformer block, P5.9 meets ResNet in the tour of CNN architectures, and P10.A4 views the running vector as a residual stream.

Key takeaways

  • Deeper plain networks can have higher training error than shallower ones, so the problem is optimization and not overfitting. He et al. (2016) fixed it with blocks that compute y=x+F(x)\mathbf{y}=\mathbf{x}+F(\mathbf{x}): the block only has to learn the residual FF, and F=0F=0 gives the identity.
  • The backward step through a block is gℓ−1=gℓ+Jℓ⊤gℓ\mathbf{g}_{\ell-1}=\mathbf{g}_\ell+\mathbf{J}_\ell^\top\mathbf{g}_\ell, because ∂y/∂x=I+J\partial\mathbf{y}/\partial\mathbf{x}=\mathbf{I}+\mathbf{J}. The product over blocks contains a term I\mathbf{I} with no factors at all, so the gradient has a direct path to every block, whatever the depth.
  • One number per block: with J=0.5J=0.5 and 20 blocks, a plain stack multiplies the gradient by 0.520≈9.5×10−70.5^{20}\approx9.5\times10^{-7} and a residual stack by 1.520≈33251.5^{20}\approx3325. The skip removes the fading and lets growth appear. A skip also does not forbid cancellation: with J=−0.5J=-0.5 the residual stack gives 9.5×10−79.5\times10^{-7} again.
  • Real networks keep the sum under control by starting each branch small: a zero-initialized last layer in every branch (zero γ\gamma of the last BatchNorm, Fixup), a branch scaled by about 1/N1/\sqrt{N} (GPT-2), normalization inside the branch (P4.19), and a modest learning rate with warmup.
  • Transformers use the same idea in pre-norm form, x←x+F(LN(x))\mathbf{x}\leftarrow\mathbf{x}+F(\mathrm{LN}(\mathbf{x})), so the skip path carries x\mathbf{x} unnormalized. The shapes of x\mathbf{x} and F(x)F(\mathbf{x}) must match, or a projection adjusts x\mathbf{x}.
Found a mistake? Tell us