TExcelTAD
Home › Math for Deep Learning & LLMs › Residual Connections

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, xl+1=xl+F(xl)\mathbf{x}_{l+1} = \mathbf{x}_l + F(\mathbf{x}_l). 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 F=0F = \mathbf{0}, 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 I+JFI + J_F. Unrolled over LL blocks,

xL=x0+∑l=0L−1Fl(xl),∂L∂x0=∂L∂xL∏l(I+JFl)\mathbf{x}_L = \mathbf{x}_0 + \sum_{l=0}^{L-1}F_l(\mathbf{x}_l), \qquad \frac{\partial\mathcal{L}}{\partial\mathbf{x}_0} = \frac{\partial\mathcal{L}}{\partial\mathbf{x}_L}\prod_{l}(I + J_{F_l})

Expanding the product, one term is II: the gradient reaches the first layer directly, however deep the network, instead of only through a product of LL possibly small Jacobians (Vanishing Gradients).

python · try it yourself
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 1/2L1/\sqrt{2L} (Initialization).

python · try it yourself
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 ∏(I+JFl)\prod(I + J_{F_l}) gives 2L2^L 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: xl+1=xl+F(xl)\mathbf{x}_{l+1} = \mathbf{x}_l + F(\mathbf{x}_l) is one Euler step of the differential equation x˙=F(x)\dot{\mathbf{x}} = F(\mathbf{x}), the idea behind neural ODEs.

Shapes must match

The addition needs F(x)F(\mathbf{x}) and x\mathbf{x} to have the same shape. When a block changes the width or resolution, the shortcut gets a projection (WsxW_s\mathbf{x}, a 1×11 \times 1 convolution in CNNs). Transformers keep the width dmodeld_{\text{model}} 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

F(x)=AxF(\mathbf{x}) = A\mathbf{x} with A=(00.1−0.10)A = \begin{pmatrix} 0 & 0.1 \\ -0.1 & 0 \end{pmatrix}. What is the block's Jacobian, and is it invertible?

Answer

I+AI + A, with determinant 1.011.01: invertible.

Solution

det⁡(10.1−0.11)=1+0.01=1.01\det\begin{pmatrix} 1 & 0.1 \\ -0.1 & 1 \end{pmatrix} = 1 + 0.01 = 1.01. Residual blocks with small FF 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

210=10242^{10} = 1024.

Solution

At each block a path either goes through FF or takes the shortcut: two choices, ten times.

Exercise 3: Euler steps (code)

With F(x)=−0.1xF(x) = -0.1x, apply 20 residual blocks to x0=1x_0 = 1 and compare with e−2e^{-2}, the solution of x˙=−x\dot{x} = -x at time 2.

Answer

0.920≈0.12160.9^{20} \approx 0.1216 versus e−2≈0.1353e^{-2} \approx 0.1353.

Solution

Each block is an Euler step of size h=0.1h = 0.1; smaller steps would approach the exact solution.

python · try it yourself
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…

  1. F(x)F(\mathbf{x})
  2. x+F(x)\mathbf{x} + F(\mathbf{x})
  3. x⋅F(x)\mathbf{x} \cdot F(\mathbf{x})
  4. F(F(x))F(F(\mathbf{x}))

Why do residual connections help gradients reach early layers?

  1. They increase the learning rate
  2. The Jacobian I+JFI + J_F contains an identity term, giving a direct path
  3. They remove nonlinearities
  4. They normalize the gradient

Why do transformers keep the hidden width constant across blocks?

  1. For simpler code only
  2. So every residual shortcut can be a plain identity addition
  3. Because attention requires it
  4. To save memory