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 and 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.
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?
- Add dropout and stronger weight decay
- Double the width of every layer
- Wrap every pair of layers in an identity shortcut, so each block learns a residual
- 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 , in the form where nothing but an addition sits on the shortcut: . Two lines of calculus show what the shortcut buys.
Unroll the recursion from any block to the top. The output is the input plus a sum of branch outputs, and no matrix ever multiplies itself:
Differentiate. With , one block's Jacobian is , and the chain rule multiplies them. Expanding the product gives terms, one for each subset of branches a signal can pass through:
A plain network keeps only the last term, a product of Jacobians, which is what vanishes or explodes. Backward, as a row vector, the gradient at block is the gradient at the top plus whatever flows through the branches:
The first term reaches every block unchanged, whatever the weights. For the gradient at 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.
In a residual network the gradient at block is . What would it take for it to vanish?
- Every branch Jacobian would have to be zero
- The weights would have to be very small
- The branch term would have to equal along the incoming gradient, cancelling the identity, for essentially every example
- The network would have to be deeper than it is wide
Show the answer
C. The branch term would have to equal along the incoming gradient, cancelling the identity, for essentially every example
The identity term delivers 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, , 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 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, (post-LN), which puts a normalization on the main path; the pre-LN block 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, has mean zero and is uncorrelated with . Cross terms vanish in expectation, so mean squares simply add, and the shortcut never removes anything.
Write for the stream's mean square (width ) and for the branch's. Because :
No normalization. A branch initialized to preserve its input's scale (He or LeCun initialization inside it) outputs with of order one, so every block multiplies the mean square by . Growth is exponential in depth, for :
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 no longer depends on , and the mean square grows only linearly. Block adds a fraction 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):
Scaled or zero-initialized branches. Multiply each branch by a constant and the factor becomes . A branch whose last layer starts at zero, or that is multiplied by a learnable gate starting at zero, gives : an exact identity at initialization. And keeps the growth bounded at any depth:
In a pre-LN residual network the input has mean square , and each branch adds a mean square of whatever the size of the stream. After 48 blocks, by what factor has the stream's RMS grown?
Show the answer
7 ×
, so the RMS is times the input's. Without the normalization, with branches that preserve their input's scale (), the same 48 blocks would multiply the mean square by and the RMS by .
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 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 ( to reduce the channels, , 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 of the last batch normalization in each residual block to , 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 , with 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).
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 followsA 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 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 is one forward-Euler step of size of the differential equation , 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 . Unrolled, , 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 per block, branches with normalized inputs add a constant (linear growth, each block about 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.
For blocks with , what is ?
Show the answer
D.
Each block's Jacobian is and the chain rule multiplies them. Expanded, the product contains the identity, every single , every product of two, and so on: terms, one per subset of branches.
The original ResNet block computes ; the pre-activation block computes , with batch normalization and ReLU moved inside . Why did the change matter most for a 1,001-layer network?
- The pre-activation block has fewer parameters, so the deep network overfits less
- 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
- Batch normalization is cheaper to compute before a convolution than after it
- 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 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.
At initialization, a residual network's branches each output a mean square equal to their input's (). How does the stream's mean square change over 30 blocks, without normalization, and with LayerNorm at each branch input (each branch then adds , starting from )?
- By about in both cases
- By without normalization, and to with it
- By in both cases: normalization inside the branch does not touch the shortcut
- It stays constant without normalization and grows to with it
Show the answer
B. By without normalization, and to 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.
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?
- Nothing in the branch can learn, because the branch outputs zero
- All units of the branch receive identical gradients forever, as with all-zero initialization
- The gradient bypasses the block through the shortcut, so the branch's weights never train
- 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
- Scaling Residual Branches with Depth · How residual branches should shrink as networks deepen, and which scaling lets hyperparameters transfer.
- Beyond Plain Residuals · Highway networks, dense connections and learned hyper-connections.
- Reading the Residual Stream · The logit lens, tuned lenses, iterative inference and redundant layers.
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.