Residual Connections
In 2015, plain networks deeper than about 20 layers trained worse than shallower ones, even on the training set. ResNet's fix was almost trivially simple: let each block add a correction to its input instead of replacing it, . Residual connections made networks with hundreds of layers trainable, and every transformer is built around them.
Why adding the input helps
Easy identity. If the best thing a block can do is nothing, a residual block only has to learn , which small weights already approximate. A plain block would have to learn the identity map through its nonlinearities, which is surprisingly hard.
Gradient highway. The Jacobian of a residual block is . Unrolled over blocks,
Expanding the product, one term is : the gradient reaches the first layer directly, however deep the network, instead of only through a product of possibly small Jacobians (Vanishing Gradients).
import numpy as np
rng = np.random.default_rng(0)
n, L = 64, 50
Ws = [rng.normal(0, 0.5 / np.sqrt(n), (n, n)) for _ in range(L)] # deliberately small weights
def grad_to_input(residual):
x = rng.normal(size=n); acts = []
for W in Ws:
a = W @ x; acts.append(a)
x = (x if residual else 0) + np.tanh(a)
g = np.ones(n)
for W, a in zip(reversed(Ws), reversed(acts)):
g_block = W.T @ (g * (1 - np.tanh(a)**2))
g = (g if residual else 0) + g_block
return np.linalg.norm(g)
print(f"plain network, {L} layers: gradient norm at input {grad_to_input(False):.2e}")
print(f"residual network: gradient norm at input {grad_to_input(True):.2e}")plain network, 50 layers: gradient norm at input 2.64e-15
residual network: gradient norm at input 7.97e+01
The residual stream
In a transformer, every attention and MLP sublayer reads from and adds to a single vector per token, the residual stream. Its variance grows with depth because each block adds to it, which is why pre-norm transformers normalize the input of each sublayer (Layer Normalization) and many initializations scale the block outputs by (Initialization).
import numpy as np
rng = np.random.default_rng(1)
d, L = 256, 48
for scale_name, s in (("no scaling", 1.0), ("1/sqrt(2L)", 1 / np.sqrt(2 * L))):
x = rng.normal(size=(100, d)); stds = []
for l in range(L):
h = x / np.sqrt(np.mean(x**2, -1, keepdims=True)) # RMSNorm before the block
W = rng.normal(0, 1 / np.sqrt(d), (d, d))
x = x + s * (h @ W.T)
stds.append(x.std())
print(f"{scale_name:11s}: residual stream std after 1, 12, 48 blocks = {stds[0]:.2f}, {stds[11]:.2f}, {stds[-1]:.2f}")no scaling : residual stream std after 1, 12, 48 blocks = 1.41, 3.59, 6.96
1/sqrt(2L) : residual stream std after 1, 12, 48 blocks = 1.01, 1.07, 1.23
Networks as ensembles and as ODEs
Expanding gives paths of different lengths; trained ResNets behave like ensembles dominated by fairly short paths, and deleting a single block hurts only a little. Another view: is one Euler step of the differential equation , the idea behind neural ODEs.
Shapes must match
The addition needs and to have the same shape. When a block changes the width or resolution, the shortcut gets a projection (, a convolution in CNNs). Transformers keep the width constant through all blocks precisely so that every shortcut is a plain identity.
In software
- A transformer block in code:
x = x + attn(norm1(x)); x = x + mlp(norm2(x)). - ResNet blocks:
out = relu(bn2(conv2(relu(bn1(conv1(x))))) + shortcut(x)). - Some initializations zero the last layer of each residual branch ("zero-init residual"), making every block start as the identity.
Exercises
Exercise 1: Jacobian of a residual block
with . What is the block's Jacobian, and is it invertible?
Answer
, with determinant : invertible.
Solution
. Residual blocks with small stay close to the identity and do not lose information.
Exercise 2: Paths through a ResNet
How many distinct input-to-output paths does a network of 10 residual blocks have?
Answer
.
Solution
At each block a path either goes through or takes the shortcut: two choices, ten times.
Exercise 3: Euler steps (code)
With , apply 20 residual blocks to and compare with , the solution of at time 2.
Answer
versus .
Solution
Each block is an Euler step of size ; smaller steps would approach the exact solution.
import numpy as np
x = 1.0
for _ in range(20):
x = x + (-0.1 * x)
print(round(x, 4), round(np.exp(-2), 4))0.1216 0.1353
Test yourself
A residual block computes…
Why do residual connections help gradients reach early layers?
- They increase the learning rate
- The Jacobian contains an identity term, giving a direct path
- They remove nonlinearities
- They normalize the gradient
Why do transformers keep the hidden width constant across blocks?
- For simpler code only
- So every residual shortcut can be a plain identity addition
- Because attention requires it
- To save memory