TExcelTAD

Residual Connections

Before 2015, adding layers to a convolutional network beyond about 20 made it worse, and not because of overfitting: the training error of a 56-layer plain network was higher than that of a 20-layer one. A deeper network can represent everything the shallower one can (the extra layers could just copy their input), yet gradient descent could not find that solution. He, Zhang, Ren and Sun's fix in ResNet was to make copying the default: each block computes a correction F(x)F(x) and adds it to its input,

y=x+F(x)y = x + F(x)

With that one change they trained 152-layer networks, and the residual connection (skip connection) is now in nearly every deep architecture: ResNets, transformers, U-Nets, diffusion models, modern MLPs. The theory (the Jacobian of a block, the ensemble-of-paths view, the link to ODEs) is in Residual Connections. This lesson measures the effect on gradients and on training, and builds the standard blocks in PyTorch.

x BN ReLU conv BN ReLU conv + y shortcut: identity (1x1 conv if the shape changes) residual branch F(x) y = x + F(x), so dy/dx = I + dF/dx

Why the gradient survives

Differentiate the block: ∂y/∂x=I+∂F/∂x\partial y / \partial x = I + \partial F / \partial x. Through LL blocks the chain rule multiplies these Jacobians,

∂L∂x0=∂L∂xL∏l=L1(I+∂Fl∂xl−1)\frac{\partial L}{\partial x_0} = \frac{\partial L}{\partial x_L} \prod_{l=L}^{1} \left( I + \frac{\partial F_l}{\partial x_{l-1}} \right)

In a plain network each factor is ∂Fl/∂xl−1\partial F_l / \partial x_{l-1} alone, and a product of many such matrices shrinks or grows exponentially (Vanishing and Exploding Gradients). With the identity added, the product expands into a sum over all 2L2^L paths, one of which is the pure identity: the gradient at the top reaches the bottom unchanged even if every branch has a tiny Jacobian. The other side of the same formula: if the branches are large, the (I+Jl)(I + J_l) factors can multiply up. Residual networks therefore come with a way to keep the branches small at the start: a final normalisation, a zero-initialised last layer in each branch, or a branch scaled by about 1/L1/\sqrt{L}.

The NumPy experiment sends a gradient of norm 1 backward through 50 tanh layers of width 64 for three weight scales (the standard deviation of WW is scale /64/\sqrt{64}), and three kinds of layer: plain h←tanh⁡(hW)h \leftarrow \tanh(hW), residual h←h+tanh⁡(hW)h \leftarrow h + \tanh(hW), and residual with the branch scaled by 1/501/\sqrt{50}.

python · try it yourself
import numpy as np

d, L = 64, 50

def backprop_norms(mode, scale, seed=0):
    """Send a unit gradient back through L layers: plain h -> tanh(hW), residual h -> h + a tanh(hW)."""
    rng = np.random.default_rng(seed)
    a = {"plain": 0.0, "residual": 1.0, "scaled": 1 / np.sqrt(L)}[mode]   # weight of the branch
    h, Ws, zs = rng.normal(0, 1, d), [], []
    for _ in range(L):                                  # forward, keep W and z
        W = rng.normal(0, scale / np.sqrt(d), (d, d))
        z = h @ W
        Ws.append(W); zs.append(z)
        h = np.tanh(z) if mode == "plain" else h + a * np.tanh(z)
    g = rng.normal(0, 1, d); g /= np.linalg.norm(g)    # dL/dh_L with norm 1
    norms = {}
    for l in range(L - 1, -1, -1):                      # backward: multiply by the transposed Jacobian
        branch = (g * (1 - np.tanh(zs[l]) ** 2)) @ Ws[l].T
        g = branch if mode == "plain" else g + a * branch   # residual: Jacobian I + a F'
        norms[L - l] = float(np.linalg.norm(g))
    return norms

print("||dL/dh|| after going back 10, 25 and 50 layers, starting from 1")
for scale in (0.5, 1.0, 2.0):
    for mode in ("plain", "residual", "scaled"):
        n = backprop_norms(mode, scale)
        print(f"  weight scale {scale}  {mode:8s}" + "".join(f"{n[k]:11.3g}" for k in (10, 25, 50)))
||dL/dh|| after going back 10, 25 and 50 layers, starting from 1
  weight scale 0.5  plain       0.00152      5e-08      9e-16
  weight scale 0.5  residual       1.14       1.66       7.34
  weight scale 0.5  scaled         1.02       1.06       1.13
  weight scale 1.0  plain          1.47       1.41      0.241
  weight scale 1.0  residual       1.46       2.43       55.6
  weight scale 1.0  scaled         1.04       1.14       1.35
  weight scale 2.0  plain          2.08       9.45        500
  weight scale 2.0  residual       1.62       5.75        263
  weight scale 2.0  scaled         1.06       1.23       1.72
  • The plain network's gradient vanishes when the weights are small (9×10−169 \times 10^{-16} after 50 layers at scale 0.5) and explodes when they are large (500 at scale 2.0). Only at scale 1.0 does it stay usable over 25 layers, and even there it has fallen to 0.241 after 50.
  • The residual network never vanishes: at scale 0.5 the gradient is 1.14 after 10 layers and 7.34 after 50. It grows instead, to 55.6 and 263 for the larger scales, because 50 full-size branches add up.
  • The scaled residual network stays between 1.02 and 1.72 everywhere: the identity path carries the gradient and the small branches only modify it. This is the idea behind zero-initialising the last layer of each branch, and behind GPT-2's 1/N1/\sqrt{N} scaling of residual projections.

Training a 20-block network in NumPy

A residual MLP on Digits with a hand-written backward pass: an input layer 64→3264 \to 32, then 20 blocks, then a linear output layer. The plain network uses blocks h←ReLU⁡(hA)h \leftarrow \operatorname{ReLU}(hA); the residual network uses h←h+ReLU⁡(hA) Bh \leftarrow h + \operatorname{ReLU}(hA)\,B with B=0B = 0 at the start, so each block begins as the identity. Both use He initialisation for AA, SGD with learning rate 0.02 and batch 32 for 30 epochs, and are evaluated on the validation split. The first line of each run is the gradient norm ∥∂L/∂h∥\lVert \partial L / \partial h \rVert after the last block and before the first, on one batch at initialisation.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
D, L = 32, 20                                         # width, number of blocks

def init(kind, rng):
    P = {"Win": rng.normal(0, np.sqrt(2 / 64), (64, D)), "Wout": rng.normal(0, np.sqrt(1 / D), (D, 10))}
    for l in range(L):
        P[f"A{l}"] = rng.normal(0, np.sqrt(2 / D), (D, D))
        if kind == "residual":                        # branch F(h) = relu(h A) B, with B = 0 at the start
            P[f"B{l}"] = np.zeros((D, D))
    return P

def forward(P, x, kind):
    h, cache = x @ P["Win"], []
    for l in range(L):
        a = np.maximum(h @ P[f"A{l}"], 0)
        cache.append((h, a))
        h = h + a @ P[f"B{l}"] if kind == "residual" else a
    return h @ P["Wout"], h, cache

def step(P, x, yb, kind, lr):
    logits, h, cache = forward(P, x, kind)
    p = np.exp(logits - logits.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    d = p.copy(); d[np.arange(len(yb)), yb] -= 1; d /= len(yb)        # dL/dlogits
    G = {"Wout": h.T @ d}
    g = d @ P["Wout"].T                                               # dL/dh after the last block
    G["g_top"] = np.linalg.norm(g)
    for l in range(L - 1, -1, -1):
        hin, a = cache[l]
        if kind == "residual":
            G[f"B{l}"] = a.T @ g
            ga = (g @ P[f"B{l}"].T) * (a > 0)
            G[f"A{l}"] = hin.T @ ga
            g = g + ga @ P[f"A{l}"].T                                 # identity path + branch
        else:
            ga = g * (a > 0)
            G[f"A{l}"] = hin.T @ ga
            g = ga @ P[f"A{l}"].T
    G["Win"] = x.T @ g
    G["g_bottom"] = np.linalg.norm(g)                                 # dL/dh before the first block
    for k in P:
        P[k] -= lr * G[k]
    return G

for kind in ("plain", "residual"):
    rng = np.random.default_rng(0)
    P = init(kind, rng)
    G = step({k: v.copy() for k, v in P.items()}, X_tr[:256], y_tr[:256], kind, 0.0)   # probe, no update
    print(f"{kind}: at init ||dL/dh|| after block {L} {G['g_top']:.3f}, before block 1 {G['g_bottom']:.3f}")
    for epoch in range(1, 31):
        order = rng.permutation(len(y_tr))
        for s in range(0, len(order), 32):
            idx = order[s:s + 32]
            step(P, X_tr[idx], y_tr[idx], kind, 0.02)
        if epoch in (1, 5, 10, 20, 30):
            acc = (forward(P, X_va, kind)[0].argmax(1) == y_va).mean()
            print(f"   epoch {epoch:2d}  val acc {acc:.3f}")
plain: at init ||dL/dh|| after block 20 0.071, before block 1 0.155
   epoch  1  val acc 0.164
   epoch  5  val acc 0.178
   epoch 10  val acc 0.403
   epoch 20  val acc 0.794
   epoch 30  val acc 0.914
residual: at init ||dL/dh|| after block 20 0.060, before block 1 0.060
   epoch  1  val acc 0.717
   epoch  5  val acc 0.922
   epoch 10  val acc 0.928
   epoch 20  val acc 0.972
   epoch 30  val acc 0.972

At initialisation the residual network's gradient is exactly the same before block 1 as after block 20 (0.060 both): with B=0B = 0 every block is the identity. The plain network's gradient is not vanishing here (0.071 at the top, 0.155 at the bottom, thanks to He initialisation), yet it trains far more slowly: 0.178 validation accuracy after 5 epochs, 0.403 after 10, 0.794 after 20 and 0.914 after 30. The residual network is at 0.717 after one epoch, 0.922 after 5 and 0.972 after 20. Good gradient norms at the start are not enough; a deep plain stack has to coordinate 20 nonlinear layers before the output means anything, while the residual stack starts as a shallow linear model and adds depth as the branches grow. (To be fair about capacity, each residual block has two 32×3232 \times 32 matrices against one in the plain block; the plain network's difficulty is depth, not size, as the 20-layer runs in the gradients lesson also showed.)

Residual blocks in PyTorch

Two details matter when you write a block.

Where the normalisation and activation go. The original ResNet block was conv-BN-ReLU-conv-BN, then the addition, then a ReLU. The pre-activation block (He et al., 2016) moves BN and ReLU in front of each convolution, so the shortcut path is a clean identity from the input of the network to its output, with nothing applied after the addition. Pre-norm transformers (Layer Normalisation and RMSNorm) follow the same principle: x+F(LN⁡(x))x + F(\operatorname{LN}(x)).

Shapes. x+F(x)x + F(x) needs equal shapes. When a block changes the number of channels or downsamples with stride 2, the shortcut becomes a projection, a 1×11 \times 1 convolution with the same stride (in an MLP, a linear layer). Use it only where needed; identity shortcuts everywhere else.

A tiny pre-activation ResNet for the 8×88 \times 8 Digits images, and its plain twin with the shortcuts removed (same layers otherwise), trained with SGD (learning rate 0.05, momentum 0.9, weight decay 5×10−45 \times 10^{-4}) for 8 epochs; recorded with PyTorch 2.14.1 on CPU:

python · try it yourself
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

class PreActBlock(nn.Module):
    """BN-ReLU-conv-BN-ReLU-conv, plus a shortcut. Projection (1x1 conv) when the shape changes."""
    def __init__(self, c_in, c_out, stride=1, residual=True):
        super().__init__()
        self.residual = residual
        self.bn1, self.conv1 = nn.BatchNorm2d(c_in), nn.Conv2d(c_in, c_out, 3, stride, 1, bias=False)
        self.bn2, self.conv2 = nn.BatchNorm2d(c_out), nn.Conv2d(c_out, c_out, 3, 1, 1, bias=False)
        self.shortcut = nn.Identity()
        if residual and (stride != 1 or c_in != c_out):
            self.shortcut = nn.Conv2d(c_in, c_out, 1, stride, bias=False)
    def forward(self, x):
        out = self.conv1(torch.relu(self.bn1(x)))
        out = self.conv2(torch.relu(self.bn2(out)))
        return self.shortcut(x) + out if self.residual else out

def net(residual, blocks_per_stage=4):
    layers = [nn.Conv2d(1, 16, 3, 1, 1, bias=False)]
    c = 16
    for c_out, stride in ((16, 1), (32, 2)):               # 8x8x16, then 4x4x32
        for i in range(blocks_per_stage):
            layers.append(PreActBlock(c, c_out, stride if i == 0 else 1, residual))
            c = c_out
    layers += [nn.BatchNorm2d(c), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(c, 10)]
    return nn.Sequential(*layers)

torch.manual_seed(0)
block = PreActBlock(16, 32, stride=2)
x = torch.randn(2, 16, 8, 8)
print("block 16->32, stride 2:", tuple(x.shape), "->", tuple(block(x).shape), " shortcut:", block.shortcut)

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32).view(-1, 1, 8, 8) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))

for residual in (False, True):
    torch.manual_seed(0)
    model = net(residual)
    n_conv = sum(isinstance(m, nn.Conv2d) and m.kernel_size == (3, 3) for m in model.modules())
    opt = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9, weight_decay=5e-4)
    gen, accs = torch.Generator().manual_seed(0), []
    for epoch in range(1, 9):
        model.train()
        for idx in torch.randperm(len(y_tr), generator=gen).split(64):
            loss = nn.functional.cross_entropy(model(X_tr[idx]), y_tr[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        if epoch in (1, 2, 4, 8):
            model.eval()
            with torch.no_grad():
                accs.append(f"{(model(X_va).argmax(1) == y_va).float().mean().item():.3f}")
    name = "residual" if residual else "plain"
    print(f"{name:8s} {n_conv} conv layers, {sum(p.numel() for p in model.parameters())} parameters,"
          f" val acc after epochs 1, 2, 4, 8: {accs}")
block 16->32, stride 2: (2, 16, 8, 8) -> (2, 32, 4, 4)  shortcut: Conv2d(16, 32, kernel_size=(1, 1), stride=(2, 2), bias=False)
plain    17 conv layers, 88826 parameters, val acc after epochs 1, 2, 4, 8: ['0.103', '0.253', '0.308', '0.917']
residual 17 conv layers, 89338 parameters, val acc after epochs 1, 2, 4, 8: ['0.186', '0.792', '0.708', '0.972']

The block with stride 2 maps 16×8×816 \times 8 \times 8 to 32×4×432 \times 4 \times 4, and its shortcut is a 1×11 \times 1 convolution with stride 2. Both networks have 17 convolution layers of size 3×33 \times 3 and nearly the same parameter count (the residual one has 512 more, the projection). Even with batch normalisation in every block, the plain network is slower: 0.253 validation accuracy after 2 epochs against 0.792, and 0.917 against 0.972 after 8. (The residual run dips at epoch 4, to 0.708, which is the noise of a high learning rate; by epoch 8 it is at 0.972. Single runs wobble, so compare curves, not one epoch.) The ResNet in torchvision, which you fine-tune in Transfer learning with ResNet, is built from the post-activation version of these blocks, with the projection shortcut stored in a submodule called downsample; CNN Architectures builds it up from LeNet.

The MLP version for tabular data or transformer feed-forward layers looks like this:

python
class ResidualMLPBlock(nn.Module):
    def __init__(self, d, hidden):
        super().__init__()
        self.norm = nn.LayerNorm(d)
        self.ff = nn.Sequential(nn.Linear(d, hidden), nn.GELU(), nn.Linear(hidden, d))
        nn.init.zeros_(self.ff[2].weight)            # the block starts as the identity
        nn.init.zeros_(self.ff[2].bias)
    def forward(self, x):
        return x + self.ff(self.norm(x))

Pitfalls

  • A ReLU after the addition. In post-activation blocks the final ReLU cuts negative values from the identity path, so the path is no longer the identity. Prefer pre-activation for deep stacks.
  • Projections everywhere. A 1×11 \times 1 convolution on every shortcut adds parameters and removes the clean identity path; use it only where the shape changes.
  • Forgetting that the stream grows. Without normalisation or branch scaling, the sum of many branches grows with depth, as the scale 1.0 and 2.0 rows above showed. Zero-initialise the last layer of each branch, or zero_init_residual=True for torchvision ResNets (it zeroes the γ\gamma of the last BN in each block).
  • In-place operations on the input. x += self.branch(x) modifies a tensor autograd may need for the backward pass and can raise "a variable needed for gradient computation has been modified by an inplace operation"; write x = x + self.branch(x).
  • Mismatched shapes broadcasting silently. Adding a (N,1)(N, 1) tensor to an (N,d)(N, d) tensor does not fail, it broadcasts. Assert the shapes of x and F(x) in a new block.

Practice

  1. A residual block has F(x)=W2ReLU⁡(W1x)F(x) = W_2 \operatorname{ReLU}(W_1 x). What does the block compute at initialisation if W2=0W_2 = 0, and do W1W_1 and W2W_2 receive gradients?
Answer

It computes y=xy = x. W2W_2 receives the gradient ReLU⁡(W1x)⊤\operatorname{ReLU}(W_1 x)^{\top} times the incoming gradient, which is not zero, so it moves away from 0 in the first step. W1W_1's gradient passes through W2W_2, so it is 0 in the first step and becomes nonzero once W2W_2 does. This is why the last layer, not the first, is zero-initialised: zeroing W1W_1 instead would make the ReLU output 0 and could leave both gradients at zero.

  1. A ResNet stage changes from 64 channels at 32×3232 \times 32 to 128 channels at 16×1616 \times 16. Which shortcut does its first block need, and how many weights does it have?
Answer

A 1×11 \times 1 convolution with stride 2 from 64 to 128 channels: 64⋅128=819264 \cdot 128 = 8192 weights (usually without bias, followed by BN in the post-activation design).

  1. Through how many paths does a gradient travel in a network of 10 residual blocks, and how many of them pass through exactly 3 branches?
Answer

Each block offers two routes (identity or branch), so 210=10242^{10} = 1024 paths. Those through exactly 3 branches number (103)=120\binom{10}{3} = 120. Most paths are of medium length, which is the "ensemble of shallow networks" view of ResNets.

Test yourself

What is the Jacobian of a residual block y=x+F(x)y = x + F(x)?

  1. ∂F/∂x\partial F / \partial x
  2. I+∂F/∂xI + \partial F / \partial x
  3. II
  4. I−∂F/∂xI - \partial F / \partial x

In the 50-layer NumPy experiment with weight scale 0.5, what happened to the gradient?

  1. Plain and residual both vanished
  2. Plain vanished to about 9×10−169 \times 10^{-16}; residual stayed above 1
  3. Both exploded
  4. Residual vanished and plain did not

When does a residual block need a projection shortcut?

  1. Always
  2. When the branch changes the number of channels or the spatial size
  3. Only in the first block of the network
  4. When the block uses batch norm

Why are residual branches often initialised so that F(x)=0F(x) = 0 at the start?

  1. To save memory
  2. So every block starts as the identity and the stream does not grow with depth
  3. Because zeros train faster than random weights in every layer
  4. To make the model linear forever

What is the defining change in a pre-activation residual block?

  1. It removes batch norm
  2. BN and ReLU come before each convolution, so nothing is applied to the sum on the shortcut path
  3. It uses two shortcuts
  4. It applies ReLU after the addition