Residual connections and very deep networks¶
Add the input of a block back onto its output — $\mathbf y = \mathbf x + F(\mathbf x)$ — and a network can be hundreds or thousands of layers deep and still train. One line of code; the most widely used architectural idea in deep learning. Every transformer is a residual network.
10,000 ft
Depth is what makes deep learning deep: each layer composes features from the layer below, and more layers can represent more complex functions with fewer parameters. But until 2015, simply stacking more layers made networks worse — not on test data, on training data. He, Zhang, Ren and Sun's residual networks (ResNets) fixed this by letting each block learn a correction to its input rather than a whole new representation, and won ImageNet 2015 with 152 layers. The idea now runs through everything: every transformer block adds attention and MLP outputs to a "residual stream"; diffusion U-Nets are built from residual blocks; interpretability research reads models as layers writing to that shared stream. It is also the same trick as the LSTM's additive memory, applied across depth instead of time, and it is tightly coupled to initialisation and normalisation.
2,000 ft
A residual block computes \(\mathbf y = \mathbf x + F(\mathbf x)\), where \(F\) is a small stack of layers (conv–norm–ReLU–conv–norm in a ResNet; attention or an MLP, preceded by a norm, in a transformer). Three consequences make deep stacks trainable:
- Identity is the default. If \(F\) outputs zero, the block does nothing; a deeper network is then at least as good as a shallower one, and each block only has to learn a refinement.
- Gradients have a highway. \(\partial\mathbf y/\partial\mathbf x = I + \partial F/\partial\mathbf x\): the gradient reaching early layers always contains a direct, unattenuated copy of the gradient from the top.
- Many short paths. Unrolled, \(n\) blocks form \(2^n\) paths of different lengths; training mostly uses the short ones, so the network behaves like an ensemble of shallower networks.
The price is that signals add up: without scaling or normalisation inside the branch, the activations grow with depth.
Ground level¶
The degradation problem¶
Stack more layers and you add capacity: a 56-layer network can represent everything a 20-layer one can (set the extra 36 layers to the identity). So a deeper network should never have higher training error. Yet He et al. (2015) observed exactly that. On CIFAR-10 a 56-layer plain convolutional network had higher training and test error than a 20-layer one; on ImageNet a plain 34-layer network was worse than a plain 18-layer one (28.54% vs 27.94% top-1 validation error).
This is not overfitting — training error is worse. And the authors checked that it was not simply vanishing gradients either: the networks used batch normalisation, and the gradients reaching early layers had healthy norms. The solver could not find the good solutions that provably existed. Something about the parameterisation made identity-like functions hard to reach: a stack of conv–BN–ReLU layers initialised at random computes something far from the identity, and gradient descent has to discover it through dozens of non-linear layers.
The residual reformulation¶
Instead of asking a block to learn the desired mapping \(H(\mathbf x)\), ask it to learn the residual \(F(\mathbf x) = H(\mathbf x)-\mathbf x\) and add the input back:
If the best thing a block can do is nothing, it only needs to drive \(F\) to zero, which is easy (shrink the weights). If the best mapping is close to the identity, \(F\) only needs to model a small perturbation. With the same layers, the same parameter count and essentially the same compute, the results flipped: ResNet-34 beat ResNet-18 (25.03% vs 27.88% top-1), the 18-layer versions converged faster, and depth kept paying — ResNet-152 reached 21.43% top-1 single-model (10-crop) at 11.3 billion multiply-adds, less than VGG-16's 15.3 billion. An ensemble reached 3.57% top-5 test error and won ILSVRC 2015. On CIFAR-10 a 110-layer ResNet reached 6.43% error, and a 1,202-layer one trained to under 0.1% training error with no optimisation difficulty (its test error, 7.93%, was worse — it overfitted the small dataset).
When the block changes the shape (downsampling, more channels) the skip cannot be a pure identity. The options are zero-padding the extra channels, or a projection shortcut: a 1×1 convolution with stride 2, \(\mathbf y = W_s\mathbf x + F(\mathbf x)\). ResNets use projections only at the few places where shapes change.
The bottleneck block¶
For ResNet-50/101/152, each block is 1×1 (reduce channels) → 3×3 → 1×1 (expand), the bottleneck design.
Worked example: why the bottleneck
A stage operating on 256 channels at 56×56.
- Two 3×3 convolutions at 256 channels: \(2\times9\times256^2 = 1{,}179{,}648\) weights.
- Bottleneck 256 → 64 → 64 → 256: \(256\times64 + 9\times64^2 + 64\times256 = 16{,}384+36{,}864+16{,}384 = 69{,}632\) weights — 17× fewer — while the identity skip still carries the full 256-channel signal.
The expensive 3×3 runs on a narrow 64-channel representation; the cheap 1×1s move in and out of it. This is how ResNet-50 has 3.8 billion multiply-adds (He et al., Table 1) — barely more than ResNet-34's 3.6 billion — despite being much deeper. Transformers invert the shape: their MLP block expands \(d \to 4d \to d\), an "inverted bottleneck" that ConvNeXt and MobileNetV2 also adopt.
Why it works: three complementary views¶
1. The gradient highway. Stack blocks \(\mathbf x_{l+1} = \mathbf x_l + F_l(\mathbf x_l)\). Then, for any earlier block \(l\) and later block \(L\),
The first term passes the top gradient to any layer unchanged. In a plain network the gradient is a product of \(L-l\) Jacobians, which can shrink or grow exponentially, and whose direction becomes increasingly random. He et al.'s follow-up, Identity Mappings in Deep Residual Networks (2016), derived this and showed it only holds if the skip path is clean: in the original block the ReLU came after the addition, so the "identity" path still passed through a nonlinearity. Moving normalisation and ReLU into the branch — the pre-activation block, \(\mathbf y = \mathbf x + W_2\,\phi(\operatorname{BN}(W_1\,\phi(\operatorname{BN}(\mathbf x))))\) — let a 1,001-layer ResNet reach 4.62% error on CIFAR-10. Transformers use the same idea under the name pre-LN: \(\mathbf x + \operatorname{Attn}(\operatorname{LN}(\mathbf x))\).
2. Gradients that stay meaningful. Balduzzi et al. (2017) pointed out that even with batch normalisation and good initialisation, the gradients of a deep plain network with respect to its input become decorrelated across nearby inputs — they "shatter" into something like white noise, so following them is hardly better than random search. With skip connections the correlation decays far more slowly. This explains the degradation result better than "vanishing gradients": the gradients in the plain 34-layer network were not small, they were uninformative.
3. An ensemble of shallow paths. Expand three blocks: \(\mathbf x_3 = \mathbf x_0 + F_1 + F_2(\mathbf x_0+F_1) + F_3(\dots)\). Every block is either taken or skipped, so \(n\) blocks give \(2^n\) paths whose lengths follow a binomial distribution. Veit, Wilber and Belongie (2016) showed that deleting a single block from a trained ResNet at test time barely hurts it, whereas deleting a layer from VGG is catastrophic, and that in a 110-layer ResNet most of the gradient comes from paths only 10–34 layers deep. A ResNet is not so much a very deep network as a very large ensemble of moderately deep ones sharing weights.
A fourth, visual view: Li et al. (2018) plotted loss landscapes and found that removing skip connections from a 56-layer network turned a smooth, nearly convex bowl into a chaotic surface full of local structure.
Signals add up: why residual networks need scaling¶
Variances add under addition of independent terms. If each branch output has the same variance as its input,
and after \(L\) blocks the activations are \(2^{L/2}\) times larger: about \(3\times10^7\) for \(L=50\).
Every successful deep residual architecture controls this somehow:
- Normalisation inside the branch: ResNet's BatchNorm; transformers' pre-LN / RMSNorm. The stream still grows (linearly rather than exponentially, since each branch sees a normalised input), so pre-LN transformers end with a final norm before the output layer.
- Start each branch at zero. Goyal et al. (2017) initialise the last BatchNorm scale \(\gamma\) in every residual block to zero, so each block starts as the identity. ReZero (Bachlechner et al., 2020) multiplies each branch by a learnable scalar initialised at 0 and trained 120-layer transformers without normalisation; Fixup (Zhang, Dauphin and Ma, 2019) rescales initial weights by a depth-dependent factor and trained 10,000-layer ResNets without normalisation.
- Scale by depth. Multiply each branch (or its initial weights) by something like \(1/\sqrt{L}\), so the total added variance stays bounded: \((1+1/L)^L\to e\). GPT-2 scales the initial weights of each residual projection by \(1/\sqrt{N}\) for \(N\) residual layers; DeepNet (Wang et al., 2022) up-weights the skip and down-scales the initialisation and trained 1,000-layer transformers.
Post-LN vs pre-LN in transformers¶
The original transformer put LayerNorm after the addition: \(\operatorname{LN}(\mathbf x + F(\mathbf x))\). That normalises the stream itself, so the skip path is no longer an identity and gradients near the output are larger than near the input. Xiong et al. (2020) showed post-LN transformers need careful learning-rate warm-up to train at all, while pre-LN (\(\mathbf x + F(\operatorname{LN}(\mathbf x))\)) trains stably without it. Almost every large language model since GPT-2 uses pre-norm. Post-LN can generalise slightly better when it trains, which is what DeepNet's modified post-LN tried to recover.
The family¶
| Design | Combination rule | Notes |
|---|---|---|
| Highway network (Srivastava, Greff and Schmidhuber, 2015) | \(\mathbf y = T(\mathbf x)\odot F(\mathbf x)+(1-T(\mathbf x))\odot\mathbf x\) | LSTM-style gates over depth; trained nets hundreds of layers deep with plain SGD, months before ResNet |
| ResNet (2015) | \(\mathbf y = \mathbf x + F(\mathbf x)\) | ungated — the gate turned out to be unnecessary |
| Wide ResNet (2016) | same, fewer and wider blocks | a 16-layer wide net outperformed far deeper thin ones, including 1,000-layer ResNets |
| ResNeXt (2016) | \(\mathbf x + \sum_g F_g(\mathbf x)\) | grouped branches ("cardinality") |
| DenseNet (2016) | \(\mathbf y = [\mathbf x, F(\mathbf x)]\) (concatenate) | every layer sees all earlier feature maps |
| U-Net (2015) | skips from encoder to decoder at each resolution | the backbone of segmentation and diffusion models |
| Stochastic depth (2016) | randomly drop whole branches in training | regularises; see regularisation |
| Transformer (2017) | \(\mathbf x + \operatorname{Attn}(\cdot)\), then \(\mathbf x + \operatorname{MLP}(\cdot)\) | the residual stream |
Residual networks as differential equations¶
Write a block as \(\mathbf x_{l+1} = \mathbf x_l + h\,f(\mathbf x_l,\theta_l)\) with \(h = 1\). That is one step of Euler's method for the ordinary differential equation \(\dot{\mathbf x}(t) = f(\mathbf x(t),\theta(t))\). A ResNet is a discretised flow that moves the representation gradually from input to output. This view (Haber and Ruthotto, 2017; Lu et al., 2017) imported tools from numerical analysis — stability of the discretisation explains why branches must be small — and inspired Neural ODEs (Chen et al., 2018), which replace the stack with an adaptive ODE solver and continuous depth. The same continuous-time lens returns in diffusion and flow matching.
The residual stream in transformers¶
In a transformer, the residual connection is not a detail but the organising principle. The embedding enters the stream; every attention and MLP layer reads from it (through a norm and a projection) and writes back an additive update; the unembedding reads the final state. Elhage et al. (2021), A Mathematical Framework for Transformer Circuits, made this the basis of mechanistic interpretability: because everything is additive, the output can be decomposed into contributions of individual heads and paths, and layers communicate through subspaces of the stream like a shared bus. Recent work questions whether a single stream is optimal — hyper-connections (Zhu et al., 2024) learn several parallel streams with learned mixing — but as of 2026 the plain pre-norm residual stream is still the standard.
First principles¶
Why should "identity plus a correction" be easier to learn than the mapping itself? Look at the Jacobian at initialisation. A plain layer's Jacobian is a random matrix \(D_l W_l\) (with \(D_l\) the diagonal of activation slopes). A product of \(L\) independent random matrices has singular values that spread out exponentially with \(L\): some directions explode, others vanish, and the network's input–output map is badly conditioned no matter how carefully you set the average scale. Initialisation schemes such as He init fix the average (the variance), not the spread.
A residual block's Jacobian is \(I + \alpha J_l\). With a small branch (\(\alpha J_l\) small), it is close to the identity, and a product of near-identity matrices stays near the identity: all singular values near 1. This property is called dynamical isometry, and it is what lets gradients carry information intact through many layers. The residual form gets close to it by construction, for any reasonable initialisation of the branch.
The same principle explains the links across the field:
- An LSTM's cell update \(\mathbf c_t = \mathbf f\odot\mathbf c_{t-1} + \dots\) is a residual connection over time with a learned gate; with \(\mathbf f = 1\) it is exactly ResNet's skip. Highway networks were the bridge.
- Normalisation and residual connections are partners: residuals keep the Jacobian well-conditioned, normalisation keeps the forward scale from drifting. Fixup and ReZero show either can be traded for careful initialisation.
- Over-parameterised networks are easier to optimise when every new layer can start "switched off" and grow in. A residual network can always fall back to a shallower one, so adding depth cannot hurt the optimum it can reach.
What breaks if you change it? Put a nonlinearity on the skip path (original ResNet's post-addition ReLU, or post-LN) and the identity path is no longer clean; very deep versions become hard to train. Gate the skip with learned weights (highway networks) and the network can learn to close it — more flexible, not better in practice. Remove scaling and normalisation and the stream explodes, as the code shows.
The maths¶
Shapes. In a ResNet stage, \(\mathbf x_l\in\mathbb R^{N\times C\times H\times W}\) and \(F_l\) must preserve the shape for the identity skip. In a transformer, \(\mathbf x_l\in\mathbb R^{B\times T\times d}\), and both attention and the MLP map \(d\to d\).
Derivation: the gradient through a residual stack has an identity term
With \(\mathbf x_{i+1} = \mathbf x_i + F_i(\mathbf x_i)\), summing from \(l\) to \(L-1\) gives \(\mathbf x_L = \mathbf x_l + \sum_{i=l}^{L-1}F_i(\mathbf x_i)\). The chain rule then gives
Expanding the product: \(I + \sum_i J_i + \sum_{i<j}J_jJ_i + \dots + J_{L-1}\cdots J_l\). There are \(2^{L-l}\) terms, one per subset of blocks, i.e. one per path; a path through \(k\) branches contributes a product of \(k\) Jacobians. If each \(\|J_i\|\le\varepsilon\), a path of length \(k\) contributes at most \(\varepsilon^k\) and there are \(\binom{L-l}{k}\) of them. Short paths dominate the gradient — the ensemble view, derived. The term \(I\) ensures the gradient at \(\mathbf x_l\) always contains \(\partial\mathcal L/\partial\mathbf x_L\) itself, so it cannot vanish regardless of depth (it can still be cancelled by the other terms, but not systematically).
Derivation: variance growth and the 1/√L scaling
Let the branch be \(\alpha F(\mathbf x)\) where, at initialisation, \(F(\mathbf x)\) has zero mean, is uncorrelated with \(\mathbf x\), and has variance \(c\cdot\operatorname{Var}(\mathbf x)\) (He init with ReLU gives \(c = 1\) for \(W\operatorname{relu}(\mathbf x)\)). Then
With \(\alpha = 1, c = 1\): \(2^L\), standard deviation \(2^{L/2}\) — for \(L = 50\), \(3.4\times10^7\) (measured: \(2.7\times10^7\)). With \(\alpha^2 = 1/L\): \((1+c/L)^L\to e^c\), a constant independent of depth — standard deviation \(e^{1/2}\approx1.65\) for \(c = 1\) (measured: 1.76) and \(e^{1/4}\approx1.28\) for LeCun init's \(c = 1/2\) (measured: 1.18).
ReZero. \(\mathbf x_{l+1} = \mathbf x_l + \alpha_l F(\mathbf x_l)\) with scalar \(\alpha_l\) initialised to 0, so \(\partial\mathbf x_L/\partial\mathbf x_0 = I\) exactly at initialisation: perfect dynamical isometry. \(\alpha_l\) receives gradient \(\langle\partial\mathcal L/\partial\mathbf x_{l+1}, F(\mathbf x_l)\rangle\) and grows as the branch becomes useful.
Euler view. \(\mathbf x_{l+1} = \mathbf x_l + h f(\mathbf x_l)\); stability of explicit Euler for \(\dot{\mathbf x} = A\mathbf x\) requires the eigenvalues of \(I + hA\) to lie within the unit circle — the discrete analogue of keeping branches small.
Build it¶
NumPy. A 50-layer, 64-wide ReLU network at initialisation: plain versus residual, with He and LeCun initialisation and with and without \(1/\sqrt L\) branch scaling. We measure activation scale at blocks 10 and 50 and the norm of the input gradient.
import numpy as np
rng = np.random.default_rng(0)
D, L = 64, 50 # width, depth
def make(gain): # Var(W_ij) = gain / D. gain=2 is He init (right for ReLU), gain=1 is LeCun init
return [rng.normal(0, np.sqrt(gain / D), (D, D)) for _ in range(L)]
def forward(x, Ws, mode, alpha):
"""mode 'plain': h = relu(W h); mode 'res': h = h + alpha * W relu(h)."""
hs = [x]
for W in Ws:
h = hs[-1]
hs.append(np.maximum(W @ h, 0) if mode == "plain" else h + alpha * (W @ np.maximum(h, 0)))
return hs
def input_grad(x, Ws, v, mode, alpha):
"""d(v . h_L)/dx, by backprop through the stack."""
hs = forward(x, Ws, mode, alpha); g = v.copy()
for W, h in zip(reversed(Ws), reversed(hs[:-1])):
if mode == "plain": g = W.T @ (g * (W @ h > 0))
else: g = g + alpha * (W.T @ g) * (h > 0) # identity + branch
return g
x0, v = rng.normal(size=D), rng.normal(size=D) / np.sqrt(D)
print(f"{'network':34s} {'std(h_10)':>10s} {'std(h_50)':>10s} {'|dy/dx|':>10s}")
for gain in (2.0, 1.0):
Ws = make(gain)
for mode, alpha in [("plain", 1.0), ("res", 1.0), ("res", 1 / np.sqrt(L))]:
if mode == "res" and alpha == 1.0 and gain == 1.0: continue
hs = forward(x0, Ws, mode, alpha)
g = np.linalg.norm(input_grad(x0, Ws, v, mode, alpha))
name = f"{mode}, init gain {gain:.0f}, alpha {alpha:.2f}"
print(f"{name:34s} {hs[10].std():10.2e} {hs[-1].std():10.2e} {g:10.2e}")
Output:
network std(h_10) std(h_50) |dy/dx|
plain, init gain 2, alpha 1.00 7.24e-01 4.26e-01 1.12e+00
res, init gain 2, alpha 1.00 2.54e+01 2.71e+07 1.43e+07
res, init gain 2, alpha 0.14 1.02e+00 1.76e+00 1.42e+00
plain, init gain 1, alpha 1.00 3.05e-02 1.46e-08 7.69e-09
res, init gain 1, alpha 0.14 9.64e-01 1.18e+00 1.67e+00
Read it as three lessons. The plain network is fine only at exactly the right initialisation; a factor of 2 in weight variance costs eight orders of magnitude after 50 layers. An unscaled residual stack explodes. A scaled residual stack is robust to the initialisation — the property that makes very deep networks practical.
The standard pre-activation block in PyTorch:
import torch.nn as nn
class PreActBlock(nn.Module):
def __init__(self, c):
super().__init__()
self.branch = nn.Sequential(
nn.BatchNorm2d(c), nn.ReLU(), nn.Conv2d(c, c, 3, padding=1, bias=False),
nn.BatchNorm2d(c), nn.ReLU(), nn.Conv2d(c, c, 3, padding=1, bias=False))
nn.init.zeros_(self.branch[-1].weight) # start as the identity (zero-init the last layer)
def forward(self, x):
return x + self.branch(x) # clean identity path
Things to try
- Extend the code to \(L = 200\) and \(L = 1000\). Which configurations survive? Compare the scaled residual's final standard deviation with the prediction \(e^{c/2}\).
- Replace
alphaby a ReZero scalar initialised at 0 and confirm \(\partial\mathbf x_L/\partial\mathbf x_0 = I\). - Measure "shattering": compute the input gradient at 200 points along a line through input space for the plain and residual nets, and plot the gradients. Vary the spacing and depth; what do you find, and how does it compare with Balduzzi et al.'s figures?
- Train a 20-layer and a 56-layer plain CNN and their residual versions on CIFAR-10 for a few epochs each, and plot training loss. You have reproduced Figure 1 of the ResNet paper.
- Delete one block at a time from a trained ResNet-18 (
torchvision) and record ImageNet-val or CIFAR accuracy, as in Veit et al.'s lesion study.
Check yourself¶
Why was the degradation problem not overfitting?
The deeper plain network had higher training error. Overfitting means low training error and high test error. The deeper network failed to fit the data it was trained on, so the problem was optimisation.
What is the Jacobian of a residual block, and why does it help gradient flow?
\(\partial\mathbf y/\partial\mathbf x = I + \partial F/\partial\mathbf x\). Backpropagated gradients always include an identity term, so the gradient at early layers contains the top gradient unchanged plus corrections, rather than a product of many possibly shrinking Jacobians.
Compute the weights in a bottleneck block 512 → 128 → 128 → 512 and in two 3×3 convs at 512 channels.
Bottleneck: \(512\cdot128 + 9\cdot128^2 + 128\cdot512 = 65{,}536+147{,}456+65{,}536 = 278{,}528\). Two 3×3 at 512: \(2\cdot9\cdot512^2 = 4{,}718{,}592\), about 17× more.
Why do pre-LN transformers train without warm-up when post-LN ones often need it?
In pre-LN the skip path is a pure identity and each sub-layer sees a normalised input, so gradient norms are roughly uniform across depth. In post-LN the normalisation sits on the stream after each addition; Xiong et al. showed the expected gradients of the parameters near the output are large at initialisation, so a large learning rate destabilises training unless it is warmed up.
With 50 residual blocks, how many paths does the unrolled network have, and what is the most common path length?
\(2^{50}\approx1.1\times10^{15}\) paths; lengths are Binomial(50, ½), so the most common length is 25 blocks. Veit et al. found the gradient comes mostly from paths shorter than average, because each extra branch multiplies in another (typically small) Jacobian.
Hard: Explain the connection between ResNets, LSTMs and Euler's method in two sentences each.
ResNet: \(\mathbf x_{l+1} = \mathbf x_l + F(\mathbf x_l)\), an additive update across depth. LSTM: \(\mathbf c_t = \mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\tilde{\mathbf c}_t\), an additive (gated) update across time, which reduces to the ResNet form when \(\mathbf f = 1\). Euler: \(\mathbf x(t+h) \approx \mathbf x(t) + h f(\mathbf x(t))\), so a ResNet is the explicit Euler discretisation of an ODE with step \(h = 1\). All three keep the Jacobian near the identity, which is why they propagate information over many steps.
Go deeper¶
Papers
- Deep Residual Learning for Image Recognition — He, Zhang, Ren and Sun, 2015. Figure 1 (degradation), Figure 4 and Table 2 (plain vs residual), Section 4.2 (the 1,202-layer CIFAR net).
- Identity Mappings in Deep Residual Networks — He et al., 2016. The propagation derivation and pre-activation blocks.
- Highway Networks — Srivastava, Greff and Schmidhuber, 2015. Gated skip connections, the immediate predecessor.
- Residual Networks Behave Like Ensembles of Relatively Shallow Networks — Veit, Wilber and Belongie, 2016.
- The Shattered Gradients Problem — Balduzzi et al., 2017.
- Visualizing the Loss Landscape of Neural Nets — Li, Xu, Taylor, Studer and Goldstein, 2018. Figure 1: ResNet-56 with and without skips.
- Fixup Initialization — Zhang, Dauphin and Ma, 2019; ReZero is All You Need — Bachlechner et al., 2020. Training deep residual nets without normalisation.
- On Layer Normalization in the Transformer Architecture — Xiong et al., 2020. Pre-LN vs post-LN.
- DeepNet: Scaling Transformers to 1,000 Layers — Wang et al., 2022.
- Densely Connected Convolutional Networks — Huang et al., 2016.
- Neural Ordinary Differential Equations — Chen, Rubanova, Bettencourt and Duvenaud, 2018.
Videos and lectures
- Deep Residual Networks: Deep Learning Gets Way Deeper (ICML 2016 tutorial slides) — Kaiming He. The author's own account of the design choices, with the follow-up results.
- Building makemore Part 3: Activations & Gradients, BatchNorm — Andrej Karpathy. Watching activation and gradient statistics through depth, by hand — the diagnostics this page relies on.
Articles and blog posts
- A Mathematical Framework for Transformer Circuits — Elhage et al., Anthropic, 2021. The residual stream as the organising concept of a transformer.
Courses and books
- Understanding Deep Learning — Simon Prince, 2023. Chapter 11 (residual networks) derives the variance growth and the ensemble view with clear figures.
- Dive into Deep Learning: ResNet — Implementation from scratch.
Code
- huggingface/pytorch-image-models (timm) — Every ResNet variant, with the modern training recipes (see also "ResNet strikes back", Wightman et al., 2021).
Where this leads¶
- The transformer block — pre-norm residual blocks of attention and MLP, the residual stream in full.
- Initialisation and normalisation — the partner of residual connections in keeping signals well scaled.
- A recipe for training (and debugging) networks — how to check activation and gradient statistics in your own model.
- Mechanistic interpretability — reading a network as layers writing to a shared residual stream.
- Score matching and flow matching — continuous-time flows, the ODE view of depth taken seriously.