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 , the gradient at the input is times the gradient at the output. Add the “” 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
where is a few ordinary layers (the branch) and the plain addition of is the skip connection. A tiny example: if and the branch outputs , the block outputs . This is the example of the linear-algebra map (P1.B2). The addition is an element-wise sum, so and must have the same shape.
Learning the residual. Suppose the best function for this part of the network is . A plain block must learn itself. A residual block learns , the difference from its input. If the best is close to the identity, then 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 . 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), cannot be added to directly. The standard fix is a projection shortcut: pass through a linear layer (a 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 for the Jacobian of the branch (P1.C7), as in P4.16. The derivative of with respect to is the identity matrix plus the derivative of :
The gradient (P4.8) therefore passes back through a block as
The incoming gradient 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 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):
There are terms, one for each way to send the signal through some blocks and around the others. The first term is : 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 , and there are 20 blocks. The gradient is multiplied by in a plain stack and by in a residual stack:
- : plain , residual .
- : plain , residual .
- : plain , residual .
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 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 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 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, with 12 units, and a plain block outputs while a residual block outputs . 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.
What the widget shows with its default random weights (seed 1; running the same algorithm in NumPy reproduces every number):
- Skip off, 24 blocks, weight scale ×0.8. The gradient is at the output and at the input, a ratio of , or about per block. The first blocks get almost nothing.
- Skip on. The ratio becomes 25: the gradient is at the output and at the input. The dashed line shows what the identity path delivers, at every depth, and the bars above it are the other terms. The fading is gone, and the gradient has grown instead.
- Zero-init last layer. With skips on, tick Zero-init last layer. With the last layer of every branch set to zero, 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.
- Branch ÷ √blocks. Each branch’s last layer is scaled by , and the ratio is .
- Raise the scale to ×1.0 with skips on. The ratio is 1633 and the loss before training is . With skips off at ×1.0 the plain ratio is . A larger scale makes larger, so the other terms of the sum are larger too.
- Training at learning rate 0.003 (24 blocks, ×0.8). The plain stack stays at a loss of for all 300 steps. That is the loss of predicting 0 for every point (the mean of ): 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 at the start and after one step. With zero-init the final loss is , and with the branch scale it is . 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.
- Shallower. At 8 blocks and ×0.8 the residual stack trains without any help (final loss ), because there are fewer terms to add up, while the plain stack is still at .
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 . 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 (a simplification: real Jacobians are matrices and are not independent). Then the mean square of over blocks is , because each factor multiplies the mean square by . With and 20 blocks the root mean square is , while the plain product is about . For the sum to stay bounded as the depth grows, has to shrink like , which means . With the value is . 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 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 , for residual layers. The GPT-2 paper states that it scales the weights of residual layers at initialization by (P4.12). This is the 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 , which is why 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 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 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 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),
The LayerNorm is inside the branch, so the skip path carries unnormalized from the input to the output of the stack. The original transformer was post-norm, , 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 for every block, and unrolling gives for any earlier block . The chain rule then gives
where is the loss (the paper’s symbol). The first term, , 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 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 ) 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 over blocks gives the forward sum
Writing , the Jacobian of the whole stack is , which expands into the sum over all subsets of blocks of the ordered product of their , starting with . The gradient is its transpose times :
In the widget a block is locally, with the ReLU slopes (0 or 1), so . If the branch outputs have independent zero-mean contributions, their variances add: with branch variance times the input’s, , and gives . This is the reason for the 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 and (), the first linear layer () and the second (). After 50 zero-initialized blocks the gradient of the output sum at the input is still exactly . 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 to check the 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.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives, for , and : , and in the plain stack, and , and in the residual stack. For random Jacobians with the root mean square of the residual product is (theory ) against about for the plain one. With it is (theory ).
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 . The gradient length at depths 0, 8, 16 and 24 is , , and for the plain stack, , , and for the residual stack, and at every depth for the zero-initialized one. In training, the plain stack stays at (it predicts about 0 and the early layers do not move), the residual stack starts at and blows up at step 1, and the zero-initialized one goes from to at step 100 and at step 300.
Common mistakes
Quiz
Check your understanding
A 56-layer plain network has a higher training error than a 20-layer one. Why does this rule out overfitting as the explanation?
An overfit model fits the training data well and fails on new data, so its training error is low. A deeper network that has a higher training error is not fitting the data it was given, and the shallower network could be copied by it with identity layers, so the optimizer is failing. Overfitting does not depend on being below 20 layers, it can be measured on the training set (that is how it is spotted), and a deeper network has more parameters, not fewer.
A stack of 4 residual blocks has in every block (single numbers). By what factor is the gradient multiplied between the output and the input?
Each block has the derivative and the factors multiply, so four blocks give . The value is what a plain stack of these branches would give. The value adds the four terms of order one and drops all the products of two or more branches, which are part of the expansion. The value is one block only.
The last layer of the branch in every residual block is initialized to zero. What does the network compute at the start of training?
With the last layer at zero, the branch is zero, so each block outputs and the gradient goes through unchanged. The stack as a whole outputs its input, not zero, because the skip path carries the input. It is not the same as a plain network, in which a zero last layer would make every output zero. The layers before the last still have random weights, but their output is multiplied by zero until the last layer learns.
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?
The identity term of the product is still there and equal to the output gradient. The other terms, which pass through some of the branches, are large when the branches are large, and they are added to it. The weights do not remove the identity path. A skip fixes the fading, not the size of the sum. The loss sets the gradient at the output, and the growth is measured against that output gradient, so the loss cannot explain it.
In a pre-norm transformer block, . Where does the LayerNorm sit with respect to the skip path?
In this form the LayerNorm normalizes only the input of the branch, and is added back as it is, so the skip path has no normalization on it. A LayerNorm placed before the split would give the skip path a normalized , but the formula adds the original . A LayerNorm applied to the sum, , is the original post-norm form, which puts the normalization on the skip path.
Exercises
- Ten blocks each have the Jacobian (a single number). What is the gradient factor of a plain stack and of a residual stack?
Show answer
Plain: . Residual: . The skip changes a fading gradient into a mildly growing one. - A residual block has the Jacobian . The incoming gradient is . What is the gradient passed back? Which part of it is lost, and why?
Show answer
. The second component is lost: , so the branch exactly cancels the skip in that direction. The identity path is present but not guaranteed to survive the other terms. - A block takes a vector of 64 numbers, and its branch outputs 128 numbers. What goes wrong with , and what is the usual fix? What does the fix do to the identity path?
Show answer
The vectors have different lengths, so they cannot be added. A projection shortcut uses a matrix (a linear layer, or a convolution for images) and computes . The skip path then multiplies the gradient by and is no longer an exact identity, which is why ResNets use projections only where the shape changes. - Each block adds a branch whose output has a variance times the variance of its input, so the variance of the running vector is multiplied by per block. What is the total factor after 24 blocks with and with ?
Show answer
with , and with . Scaling the branch so that its variance is about of the input’s keeps the total near a constant, which is the scale on the branch’s weights. - A zero-initialized last layer makes the whole branch output zero at the start. Why does the branch still learn?
Show answer
The 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.