Notes / Robot Learning

Deep Residual Networks (ResNet)

Updated

Introduction

Suppose you have already trained a 20-layer convolutional neural network to solid accuracy on a set of training photographs, and someone hands you 36 extra convolutional layers to stack on top of it, creating a 56-layer network. At worst, how badly could the 56-layer network perform on the exact same training set?

In principle, its training error should be no worse than the 20-layer model’s. There is an explicit weight setting that guarantees it: let the first 20 layers copy the weights of the trained shallower network, and let each of the 36 added layers compute the identity mapping y=xy = x, meaning a layer that simply returns its input unchanged. Because the 56-layer family of functions contains every function the 20-layer network can express plus many more, the deeper model has strictly greater representational capacity.

When He and colleagues tested deeper plain networks in 2015, the opposite happened. On CIFAR-10, a standard image-classification benchmark, a 56-layer network had higher training error than a 20-layer network. They observed the same pattern on the larger ImageNet benchmark with 34-layer and 18-layer networks.

The surprising part was that the deeper networks performed worse on the examples they were trained on. That optimization failure—and their remarkably simple fix, y=F(x)+xy = \mathcal{F}(x) + x—produced ResNet, unlocking networks hundreds of layers deep and introducing the residual stream that underpins modern transformers.

The Degradation Problem

He et al. called this reversal the degradation problem where, past roughly 20 layers, stacking more plain convolutional layers makes both training error and test error worse. Let’s take a look at two logical explanations and explain why they don’t explain the pattern.

First, the degradation is not explained by overfitting. Overfitting happens when an overly expressive model memorizes quirks of the training images—driving training error close to zero while error on unseen test images climbs. Here, deeper networks had higher error on the training set itself. Good weight settings provably existed inside the 56-layer parameter space, yet gradient descent could not find them.

Second, the degradation is not explained by vanishing or exploding signals. In the early 2010s, poorly scaled random weights repeatedly amplified or shrank intermediate values from layer to layer during the forward pass—and did the same to gradients during backpropagation—driving numbers toward infinity or zero before training could even begin. By 2015, however, Kaiming initialization and Batch Normalization had already stabilized signal scale across layers, and He et al.’s failing 56-layer plain network used both of them.

Because every modern ResNet still relies on those two stabilization layers, let’s introduce both of them before going on.

Kaiming Initialization

Let’s consider a single scalar output entry yy computed by a convolutional filter sliding over an input volume:

y=∑i=1ninwixi.y = \sum_{i=1}^{n_{\mathrm{in}}} w_i x_i.

Here nin=Cin kh kwn_{\mathrm{in}} = C_{\mathrm{in}}\,k_h\,k_w is called the layer’s fan-in: the count of input numbers multiplied and summed to produce one output pixel. For example, a 3×33 \times 3 filter reading 6464 input channels sums nin=64×3×3=576n_{\mathrm{in}} = 64 \times 3 \times 3 = 576 terms. At the start of training, we draw each weight wiw_i independently at random with mean E[wi]=0\mathbb{E}[w_i] = 0 and variance Var⁡(wi)=E[wi2]=σw2\operatorname{Var}(w_i) = \mathbb{E}[w_i^2] = \sigma_w^2. How large should we choose σw2\sigma_w^2?

Each input xix_i comes from passing the previous layer’s raw output ziz_i through a rectified linear unit, xi=ReLU⁡(zi)=max⁡(0,zi)x_i = \operatorname{ReLU}(z_i) = \max(0, z_i). Suppose the previous layer’s raw outputs ziz_i are distributed symmetrically around 00 with variance Var⁡(z)=E[zi2]\operatorname{Var}(z) = \mathbb{E}[z_i^2]. What happens to the average squared magnitude E[xi2]\mathbb{E}[x_i^2] after ReLU⁡\operatorname{ReLU} clips the negative values?

  • Half the time, zi<0z_i < 0, so ReLU⁡(zi)=0\operatorname{ReLU}(z_i) = 0 and xi2=0x_i^2 = 0.
  • The other half of the time, zi>0z_i > 0, so ReLU⁡(zi)=zi\operatorname{ReLU}(z_i) = z_i and xi2=zi2x_i^2 = z_i^2.

Zeroing out exact half of a symmetric distribution cuts its average squared value in half:

E[xi2]=12 E[zi2]=12Var⁡(z).\mathbb{E}[x_i^2] = \frac{1}{2}\,\mathbb{E}[z_i^2] = \frac{1}{2}\operatorname{Var}(z).

Now compute the variance of the sum y=∑i=1ninwixiy = \sum_{i=1}^{n_{\mathrm{in}}} w_i x_i. Because each wiw_i has mean 00 and is drawn independently of xix_i and of the other weights, each product wixiw_i x_i has mean E[wi]E[xi]=0\mathbb{E}[w_i]\mathbb{E}[x_i] = 0 and variance E[wi2xi2]=E[wi2]E[xi2]=σw2 E[xi2]\mathbb{E}[w_i^2 x_i^2] = \mathbb{E}[w_i^2]\mathbb{E}[x_i^2] = \sigma_w^2\,\mathbb{E}[x_i^2]. Adding ninn_{\mathrm{in}} independent terms adds their variances:

Var⁡(y)=nin σw2 E[xi2]=12 nin σw2 Var⁡(z).\operatorname{Var}(y) = n_{\mathrm{in}}\,\sigma_w^2\,\mathbb{E}[x_i^2] = \frac{1}{2}\,n_{\mathrm{in}}\,\sigma_w^2\,\operatorname{Var}(z).

Notice what happens across LL stacked layers if the multiplier 12ninσw2\frac{1}{2} n_{\mathrm{in}} \sigma_w^2 differs even slightly from 11: layer LL‘s output variance scales as (12ninσw2)L\bigl(\frac{1}{2} n_{\mathrm{in}} \sigma_w^2\bigr)^L. If that factor is 0.50.5, after 3030 layers the signal shrinks by 0.530≈10−90.5^{30} \approx 10^{-9}; if it is 22, it blows up by 230≈1092^{30} \approx 10^9. Setting the multiplier equal to 11 so variance stays constant from layer to layer (Var⁡(y)=Var⁡(z)\operatorname{Var}(y) = \operatorname{Var}(z)) gives Kaiming initialization (He et al., early 2015):

σw2=2nin=2Cin kh kw.\sigma_w^2 = \frac{2}{n_{\mathrm{in}}} = \frac{2}{C_{\mathrm{in}}\,k_h\,k_w}.

Running the exact same variance calculation backward for the gradients flowing through transposed filters yields the mirror choice σw2=2/nout\sigma_w^2 = 2 / n_{\mathrm{out}}, where nout=Cout kh kwn_{\mathrm{out}} = C_{\mathrm{out}}\,k_h\,k_w is the layer’s fan-out (how many output channels each kh×kwk_h \times k_w patch feeds into). Either choice keeps initial forward activations and backward gradients well scaled across dozens of layers.

Drag the weight-variance numerator cc in σw2=c/nin\sigma_w^2 = c / n_{\mathrm{in}} below—comparing the linear Xavier scale c=1c = 1 (which ignores ReLU⁡\operatorname{ReLU}‘s 12\frac{1}{2} clipping) against Kaiming’s c=2c = 2—to see how even a slight per-layer mismatch compounds across 2020 layers:

ReLU Variance Halving & Kaiming Initialization
Preset

Batch Normalization

Kaiming initialization only guarantees healthy variance at training step 00. Once gradient descent starts updating the weights, the distribution of activations coming out of each layer shifts continuously, forcing later layers to chase a moving target.

Batch Normalization (Ioffe & Szegedy, 2015) fixes this by inserting a standalone normalization layer directly into the network—typically right between each convolutional layer and its ReLU⁡\operatorname{ReLU} activation. Unlike a fixed operation such as pooling or ReLU⁡\operatorname{ReLU}, a BatchNorm layer owns its own learnable parameters (a scale γc\gamma_c and a shift βc\beta_c for each channel cc), while leaving the feature volume’s spatial and channel dimensions unchanged:

A standalone BatchNorm layer placed between a convolutional layer and ReLU, preserving the C by H by W volume shape while applying 2C learnable parameters gamma and beta.

To see what this layer computes during a forward pass, recall how neural networks are trained in practice. Computing a gradient over all 1.28 million1.28\text{ million} ImageNet photos before taking a single step would be glacially slow, whereas updating on a single photo at a time produces erratic, noisy steps. Instead, stochastic gradient descent (SGD) processes a small group of BB images at a time—called a minibatch (typically B=64B = 64 or 256256 images).

Recall that a convolutional filter produces a two-dimensional feature map for each input image. A layer with 6464 filters therefore produces 6464 feature maps per image, the output channels.

Suppose we process a minibatch of 88 images, and each output feature map is 32×3232 \times 32. The layer produces an array of shape

(B,C,H,W)=(8,64,32,32):images, channels, height, width.(B, C, H, W) = (8, 64, 32, 32): \qquad \text{images, channels, height, width}.

We write a single value in this array as xb,c,i,jx_{b,c,i,j} - the activation for image bb, in channel cc, at row ii and column jj.

Batch Normalization stabilizes each channel cc independently by pooling all M=B⋅H⋅WM = B \cdot H \cdot W numbers belonging to channel cc across every image and pixel in the current minibatch, computing their empirical mean μc\mu_c and variance σc2\sigma_c^2:

μc=1M∑b,i,jxb,c,i,j,σc2=1M∑b,i,j(xb,c,i,j−μc)2.\mu_c = \frac{1}{M}\sum_{b,i,j} x_{b,c,i,j}, \qquad \sigma_c^2 = \frac{1}{M}\sum_{b,i,j} (x_{b,c,i,j} - \mu_c)^2.

It then subtracts the mean and divides by the standard deviation so channel cc has mean 00 and variance 11, before applying the layer’s learnable per-channel scale parameter γc\gamma_c (initialized to 11) and shift parameter βc\beta_c (initialized to 00)—for 6464 channels, just 2×64=1282 \times 64 = 128 trainable scalars in total:

x^b,c,i,j=xb,c,i,j−μcσc2+ϵ,yb,c,i,j=γc x^b,c,i,j+βc.\hat x_{b,c,i,j} = \frac{x_{b,c,i,j} - \mu_c}{\sqrt{\sigma_c^2 + \epsilon}}, \qquad y_{b,c,i,j} = \gamma_c\,\hat x_{b,c,i,j} + \beta_c.

Two small details in the expressions that are worth noting:

  • The constant ϵ\epsilon inside the square root (typically 10−510^{-5}) is there solely for numerical safety, preventing division by zero if all entries in channel cc happen to take the same value.
  • Why introduce learnable γc\gamma_c and βc\beta_c right after normalizing? Forcing every channel to strict mean 00 and unit variance right before ReLU⁡\operatorname{ReLU} could limit what a layer can compute—for instance, a channel might genuinely want to stay entirely positive so ReLU⁡\operatorname{ReLU} acts linearly. Giving gradient descent two scalar knobs γc\gamma_c and βc\beta_c per channel lets the network choose whatever spread and bias reduces the loss while keeping gradients decoupled from how large the upstream weights WW grow.

In short, the purpose of Batch Normalization is to stabilize the training signal by decoupling the task of picking out features from choosing their scale.

At test time, you often want to classify a single image (B=1B = 1) deterministically without its prediction depending on what other images happen to share a batch. During training, BatchNorm therefore keeps a running exponential average of μc\mu_c and σc2\sigma_c^2, and freezes those stored averages when evaluating. One nice side effect: if a convolutional layer is immediately followed by BatchNorm, adding a convolutional bias bcb_c would shift both xb,c,i,jx_{b,c,i,j} and μc\mu_c by +bc+b_c, canceling identically inside xb,c,i,j−μcx_{b,c,i,j} - \mu_c while βc\beta_c already provides a learnable channel offset. Convolutions right before BatchNorm therefore omit their bias (bias=False in PyTorch).

Click across channels below to see which slice of the (B,C,H,W)(B, C, H, W) minibatch BatchNorm pools together, and drag that channel’s γc\gamma_c and βc\beta_c to watch how the affine step controls how much of the normalized activation survives ReLU⁡\operatorname{ReLU}:

Batch Normalization Explorer
Channel

Optimization Failure in Plain Networks

Even with Kaiming initialization and normalization in place, deeper plain networks still stall at worse training error than shallower ones. You can watch this happen directly in the playground below, which runs live gradient descent in your browser on stacks of 22, 66, or 1212 two-layer ReLU blocks initialized with Kaiming weights:

Live Training Playground: Plain vs. Residual Depth
Depth
Target

Learned function f(x) vs. target

Training MSE across SGD steps

Switch depth from L=2L = 2 to L=6L = 6 and L=12L = 12. At L=2L = 2, the plain network fits the target curve almost as cleanly as the residual network. By L=12L = 12, the plain network has six times as many parameters as at L=2L = 2, yet its training loss stalls orders of magnitude higher—even when you switch the target to the pure identity function f(x)=xf(x) = x.

Residual Learning

Why does a plain stack of convolutional layers struggle so badly to learn even the identity mapping H(x)=x\mathcal{H}(x) = x?

To see why, look closely at the basic two-layer building block containing a chain of two normalized convolutional units (Conv -> BatchNorm -> ReLU) from the previous section:

  1. Layer 1 convolves input volume xx with 3×33 \times 3 filters W1W_1, normalizes each channel with Batch Normalization (BN⁡\operatorname{BN}), and applies ReLU⁡\operatorname{ReLU} to produce an intermediate feature volume hh:

    h=ReLU⁡(BN⁡(W1⋆x)),h = \operatorname{ReLU}\bigl(\operatorname{BN}(W_1 \star x)\bigr),

    where ⋆\star denotes convolution.

  2. Layer 2 convolves hh with a second set of 3×33 \times 3 filters W2W_2, normalizes again, and applies ReLU⁡\operatorname{ReLU} to produce the block’s output H(x)\mathcal{H}(x):

    H(x)=ReLU⁡(BN⁡(W2⋆h)).\mathcal{H}(x) = \operatorname{ReLU}\bigl(\operatorname{BN}(W_2 \star h)\bigr).
A plain two-layer convolutional block chaining Layer 1 (3x3 conv W1, BatchNorm, ReLU) and Layer 2 (3x3 conv W2, BatchNorm, ReLU) in series with no path around the weight layers.

Now suppose earlier layers have already extracted a clean, useful feature map xx, and the best thing this two-layer block could do is leave xx untouched (H(x)=x\mathcal{H}(x) = x). Even though W1W_1 and W2W_2 contain thousands of tunable weights, getting a plain block to act like a simple passthrough runs into three compounding obstacles:

  • First, ReLU⁡\operatorname{ReLU} erases negative values. Because Batch Normalization centers each channel around 00 before scaling, roughly half of the numbers entering ReLU⁡\operatorname{ReLU} are negative and immediately clipped to 00 unless the bias learns to propogate values through the ReLU activation. If the first hidden layer does not propogate the signal without any negative values, which are zeroed out, W2W_2 has no way to recover it.

    To preserve both halves of zz across ReLU⁡\operatorname{ReLU}, the two layers have to coordinate an indirect workaround—either W1W_1 must dedicate two hidden channels to each signal (storing +z+z in one so ReLU⁡(z)\operatorname{ReLU}(z) keeps the positive peaks, and −z-z in another so ReLU⁡(−z)\operatorname{ReLU}(-z) flips the negative troughs above zero, which W2W_2 then subtracts via ReLU⁡(z)−ReLU⁡(−z)=z\operatorname{ReLU}(z) - \operatorname{ReLU}(-z) = z), or BatchNorm’s shift β\beta must push the entire channel well above zero before ReLU⁡\operatorname{ReLU} applies.

  • Second, shrinking weights toward zero destroys the signal. If gradient descent pushes W1W_1 or W2W_2 toward 00, the convolutions output 00 - wiping out xx rather than letting it pass through.

  • Third, random initialization starts far from an identity map. At training step 00, Kaiming weights W1W_1 and W2W_2 randomly mix channels while ReLU⁡\operatorname{ReLU} clips half of every hidden feature map. Chaining 1010 or 2020 plain blocks end to end scrambles xx completely at initialization; turning that chain into a clean relay requires gradient descent to align dozens of coupled weight tensors simultaneously using only noisy minibatch gradients.

So, learning to propogate the signal perfectly isn’t impossible, but is extremely difficult.

Step through all four weight regimes on a centered 1D signal zz below to see why single-channel copying clips the negative half, how the two-channel ±\pm split works around ReLU⁡\operatorname{ReLU}, and what zero or random weights do instead:

Passing a Signed Feature Through Two Layers + ReLU

He et al. changed the question the layers are asked to solve. Suppose the ideal transformation a block should compute is H(x)\mathcal{H}(x). Define the residual F(x)\mathcal{F}(x) to be the difference between that desired output and the input that already arrived at the layer in question:

F(x):=H(x)−x.\mathcal{F}(x) := \mathcal{H}(x) - x.

Rearranging adds the input xx straight back onto the learned branch output:

H(x)=F(x,{Wi})+x.\mathcal{H}(x) = \mathcal{F}(x, \{W_i\}) + x.

Instead of asking a stack of weight layers to construct the entire output H(x)\mathcal{H}(x) from scratch, we only task it with learning the residual beyond the output of the previous layer, wiring the input xx around the weight layers along a skip connection. Step through a complete residual block below:

Basic Residual Block
Basic Residual BlockInput x splits into a two-layer 3x3 convolutional residual branch F(x) and a direct parameter-free skip connection x, then adds them before ReLU.
Input
xℓ∈RC×H×Wx_\ell \in \mathbb{R}^{C \times H \times W}
3×3 Conv + BN + ReLU
h=ReLU⁡(BN⁡(W1⋆xℓ))h = \operatorname{ReLU}(\operatorname{BN}(W_1 \star x_\ell))
3×3 Conv + BN
F(xℓ)=BN⁡(W2⋆h)\mathcal{F}(x_\ell) = \operatorname{BN}(W_2 \star h)
Identity Shortcut
xℓ  x_\ell \;\text{}
Add + ReLU
ReLU⁡(F(xℓ)+xℓ)\operatorname{ReLU}\bigl(\mathcal{F}(x_\ell) + x_\ell\bigr)

Scroll sideways to follow the full diagram.

Incoming Representation

Block ℓ\ell receives the multi-channel feature tensor xℓx_\ell from the previous block.

xℓ∈RC×H×Wx_\ell \in \mathbb{R}^{C \times H \times W}

At first glance, adding +x+ x can feel almost like a sleight of hand: if a linear convolution could in principle represent an identity kernel anyway, we have barely changed the family of functions the network can express. Why should changing how we write the formula alter what gradient descent finds?

Because gradient descent depends heavily on where weight space is centered. In a plain block, driving the weights to zero (W→0W \to 0) produces the zero map H(x)=0\mathcal{H}(x) = 0, which wipes out the signal. In a residual block, driving the branch weights to zero produces F(x)=0\mathcal{F}(x) = 0 and therefore H(x)=x\mathcal{H}(x) = x.

  • If an extra block in a 56-layer or 152-layer network is unnecessary early in training, shrinking its weights toward zero (which standard weight regularization already encourages) immediately turns the block into a harmless identity wire.
  • When a block does help, visual features rarely need to be torn down and rebuilt from zero at every depth; they benefit from small, progressive adjustments. Learning a small perturbation F(x)\mathcal{F}(x) around 00 is vastly easier than re-learning xx plus that perturbation.

Gradient Flow and Skip Connections

The deepest reason skip connections unlock extreme depth shows up as soon as we trace how backpropagation sends error signals from the output loss back to early layers.

To see the algebra in its cleanest form, consider a stack of residual blocks where every nonlinear operation (BatchNorm and ReLU⁡\operatorname{ReLU}) lives inside the branch Fℓ\mathcal{F}_\ell, leaving the skip path as pure addition (the pre-activation block introduced in He et al.’s 2016 follow-up paper):

xℓ+1=xℓ+Fℓ(xℓ,Wℓ).x_{\ell + 1} = x_\ell + \mathcal{F}_\ell(x_\ell, W_\ell).

Substitute this rule into the next block, and then keep unrolling all the way to the final block LL:

xℓ+2=xℓ+1+Fℓ+1(xℓ+1,Wℓ+1)=xℓ+Fℓ(xℓ,Wℓ)+Fℓ+1(xℓ+1,Wℓ+1),    ⋮xL=xℓ+∑k=ℓL−1Fk(xk,Wk).\begin{aligned} x_{\ell + 2} &= x_{\ell + 1} + \mathcal{F}_{\ell + 1}(x_{\ell + 1}, W_{\ell + 1}) = x_\ell + \mathcal{F}_\ell(x_\ell, W_\ell) + \mathcal{F}_{\ell + 1}(x_{\ell + 1}, W_{\ell + 1}), \\ &\;\;\vdots \\ x_L &= x_\ell + \sum_{k=\ell}^{L - 1} \mathcal{F}_k(x_k, W_k). \end{aligned}

Compare that last line to a plain deep network. In a plain network without skip connections, xLx_L is a deeply nested composition of every layer from ℓ\ell to L−1L - 1; in linear form, it behaves like a long matrix product (∏k=ℓL−1Wk)xℓ\bigl(\prod_{k=\ell}^{L-1} W_k\bigr) x_\ell. In a residual network, the final representation xLx_L is the sum of any earlier representation xℓx_\ell plus all the residual corrections accumulated after it.

Now let us compute how the scalar training loss L\mathcal{L} changes when we nudge the early feature volume xℓx_\ell. Imagine flattening all N=C⋅H⋅WN = C \cdot H \cdot W numbers of xℓx_\ell (and likewise xLx_L) into an NN-element vector so we can use standard multivariable calculus:

  • The derivative ∂xL∂xℓ\frac{\partial x_L}{\partial x_\ell} is an N×NN \times N table of partial derivatives—called a Jacobian matrix—whose (p,q)(p, q) entry records how much entry pp of xLx_L changes per unit nudge to entry qq of xℓx_\ell.
  • Differentiating xℓx_\ell with respect to itself produces the N×NN \times N identity matrix II (ones down the main diagonal and zeros everywhere else, because entry pp of xℓx_\ell changes at rate 11 with respect to itself and rate 00 with respect to every other entry q≠pq \neq p). Multiplying any vector by II leaves that vector unchanged.

Applying the multivariable chain rule to xL=xℓ+∑k=ℓL−1Fk(xk,Wk)x_L = x_\ell + \sum_{k=\ell}^{L-1} \mathcal{F}_k(x_k, W_k) gives:

∂L∂xℓ=∂L∂xL ∂xL∂xℓ=∂L∂xL(I+∂∂xℓ∑k=ℓL−1Fk(xk,Wk))=∂L∂xL+∂L∂xL ∂∂xℓ∑k=ℓL−1Fk(xk,Wk).\begin{aligned} \frac{\partial \mathcal{L}}{\partial x_\ell} &= \frac{\partial \mathcal{L}}{\partial x_L}\,\frac{\partial x_L}{\partial x_\ell} = \frac{\partial \mathcal{L}}{\partial x_L} \left( I + \frac{\partial}{\partial x_\ell} \sum_{k=\ell}^{L - 1} \mathcal{F}_k(x_k, W_k) \right) \\ &= \frac{\partial \mathcal{L}}{\partial x_L} + \frac{\partial \mathcal{L}}{\partial x_L}\,\frac{\partial}{\partial x_\ell} \sum_{k=\ell}^{L - 1} \mathcal{F}_k(x_k, W_k). \end{aligned}

Look closely at those two additive pieces:

  1. The first term, ∂L∂xL\frac{\partial \mathcal{L}}{\partial x_L}, arrives at layer ℓ\ell directly from the end of the network without being multiplied by a single intermediate weight matrix. Whether layer ℓ\ell sits 55 blocks before the output or 500500 blocks before the output, it hears the loss gradient at full strength on step 11 of training.
  2. Even if several intermediate branches Fk\mathcal{F}_k currently have tiny weights or dead ReLU⁡\operatorname{ReLU} units so their derivatives ∂Fk∂xℓ\frac{\partial \mathcal{F}_k}{\partial x_\ell} are nearly zero, the total gradient at xℓx_\ell does not collapse—it gracefully falls back to ∂L∂xL\frac{\partial \mathcal{L}}{\partial x_L}. For the gradient at xℓx_\ell to cancel to zero, the summed branch Jacobians ∂∂xℓ∑Fk\frac{\partial}{\partial x_\ell}\sum \mathcal{F}_k would have to align to exact −I-I simultaneously across an entire minibatch of images, which virtually never occurs.

Post-Activation vs. Pre-Activation Blocks

In the original 2015 ResNet paper, the final ReLU⁡\operatorname{ReLU} of each block was placed after the skip addition (post-activation): xℓ+1=ReLU⁡(xℓ+Fℓ(xℓ))x_{\ell + 1} = \operatorname{ReLU}(x_\ell + \mathcal{F}_\ell(x_\ell)). Because that outer ReLU⁡\operatorname{ReLU} clips negative values on the combined stream, the skip path is not quite a pure identity when entries dip below zero. Up to 100–150 layers, post-activation trains well and remains what PyTorch’s standard torchvision.models.resnet18 and resnet50 implement.

When He et al. pushed depth past 1,0001{,}000 layers on CIFAR-10 in 2016, however, those repeated post-addition ReLU⁡\operatorname{ReLU} gates started impeding signal flow again. Moving BatchNorm and ReLU⁡\operatorname{ReLU} inside the branch right before each convolution (pre-activation: BN -> ReLU -> Conv -> BN -> ReLU -> Conv) cleared every obstacle off the skip rail and enabled a 1,001-layer ResNet to train smoothly and beat shallower versions. Step through the unobstructed forward and backward paths below:

Pre-Activation Block (ResNet-v2)
Pre-Activation Block (ResNet-v2)Moving Batch Normalization and ReLU inside the residual branch leaves the skip path completely unobstructed in both forward and backward passes.
unobstructed skip path xℓ\text{unobstructed skip path } x_\ell
backward gradient ∂L/∂xL flows straight through +\text{backward gradient } \partial \mathcal{L} / \partial x_L \text{ flows straight through } +
Stream
xℓx_\ell
BN → ReLU → 3×3 Conv
h=W1⋆ReLU⁡(BN⁡(xℓ))h = W_1 \star \operatorname{ReLU}(\operatorname{BN}(x_\ell))
BN → ReLU → 3×3 Conv
Fℓ(xℓ)=W2⋆ReLU⁡(BN⁡(h))\mathcal{F}_\ell(x_\ell) = W_2 \star \operatorname{ReLU}(\operatorname{BN}(h))
Pure Sum
xℓ+1=xℓ+Fℓ(xℓ)x_{\ell+1} = x_\ell + \mathcal{F}_\ell(x_\ell)

Scroll sideways to follow the full diagram.

Unobstructed Residual Stream

In the 2015 post-activation block, applying ReLU⁡\operatorname{ReLU} after the sum zeroes out negative entries on the main stream. Pre-activation ResNet removes all gates from the skip connection itself.

xℓ+1=xℓ+Fℓ(xℓ)x_{\ell+1} = x_\ell + \mathcal{F}_\ell(x_\ell)

Drag the depth LL and per-layer derivative scale σ\sigma below to compare how quickly a plain multiplicative chain σL\sigma^L decays (or explodes) next to the post-activation and pre-activation residual paths:

Backward Gradient Scale Across Depth

The Residual Stream and Path Ensembles

Once a ResNet has been trained, how do its blocks actually process an image? Two landmark follow-up studies in 2016–2017 opened the black box and overturned the classical textbook picture of deep networks.

In a classical plain CNN, each layer completely replaces the previous representation with a new set of features, so layer 1010 speaks an entirely different coordinate language from layer 99. If you delete or zero out a single intermediate layer in a trained plain network like VGG-16 at test time (an experiment borrowed from neuroscience called a lesion study), downstream layers receive zeros or garbled coordinates and classification accuracy immediately drops to random chance.

When Andreas Veit, Michael Wilber, and Serge Belongie ran that exact lesion experiment on a trained ResNet in 2016, something surprising happened: deleting almost any single residual block in the middle of a trained 110-layer ResNet barely changed test accuracy at all (typically raising error by less than 0.50.5 percentage points)! Only when 1010 or 2020 blocks were deleted together did error climb smoothly and gradually.

Why is a trained ResNet resilient to losing whole layers on the fly? Unrolling the recurrence across LL blocks reveals two complementary reasons:

  1. A shared representation that blocks refine incrementally. Because every block adds its output Fℓ(xℓ−1)\mathcal{F}_\ell(x_{\ell - 1}) directly into the running tensor xℓ−1x_{\ell - 1}, all blocks within a stage read from and write into a common coordinate space—what modern interpretability research calls the residual stream. Empirically, each trained branch makes a relatively modest vector update (∥Fℓ(xℓ−1)∥<∥xℓ−1∥\|\mathcal{F}_\ell(x_{\ell-1})\| < \|x_{\ell-1}\|), gradually sharpening edges, suppressing noise, and grouping object parts rather than scrambling channels at every step.
  2. An implicit collection of 2L2^L paths. At block 11, information can either follow the skip wire or pass through F1\mathcal{F}_1; at block 22, each of those two signals again splits two ways. Across LL blocks there are 2L2^L distinct input-to-output paths! By the binomial theorem, the number of paths passing through kk nonlinear branches is (Lk)\binom{L}{k}, which concentrates tightly around k≈L/2k \approx L / 2. Most gradient flow travels along moderate-length paths of rough depth 1010–3535 even inside a 100100-block ResNet, and removing one block leaves 2L−12^{L-1} intact paths still carrying a coherent feature map to the classifier.

Explore both phenomena directly in the interactive residual stream below. Click through blocks 11 to 55 to inspect the incoming stream xℓ−1x_{\ell - 1}, the signed correction Fℓ(xℓ−1)\mathcal{F}_\ell(x_{\ell - 1}) (blue for negative suppression, terracotta for positive reinforcement), and the updated state xℓx_\ell—then click Disable block and toggle between ResNet and Plain stack to run Veit et al.’s lesion experiment yourself:

Residual Stream & Block Ablation Playground
Architecture

+

=

→

To see the combinatorial side of that resilience, click any block Fℓ\mathcal{F}_\ell in the unrolled trellis below to lesion it—comparing how a plain serial chain loses its single path immediately while a ResNet routes 2L−12^{L - 1} intact paths around the gap—and hover any path depth kk in the chart to see how backward gradient flow concentrates along shallower effective paths:

Unrolled Path Ensemble & Effective Depth
Blocks

Click any block to lesion (delete) it at test time

Network Architecture

Scaling y=F(x)+xy = \mathcal{F}(x) + x from a single toy block to 50-, 101-, and 152-layer models on full-resolution photographs requires solving three practical design questions: how to add tensors when dimensions change, how to keep wide layers computationally cheap, and how to balance compute from early high-resolution layers to late semantic layers.

Projection Shortcuts

Elementwise addition x+F(x)x + \mathcal{F}(x) is only well defined when xx and F(x)\mathcal{F}(x) have the exact same shape (C,H,W)(C, H, W). Within a stage, every 3×33 \times 3 convolution uses padding p=1p = 1, stride s=1s = 1, and constant channel count CC, so shapes match automatically and the skip path is a free identity wire with zero parameters.

Periodically, however, a vision backbone needs to shrink spatial resolution so receptive fields grow and memory stays bounded, while increasing the number of feature channels so richer object concepts can be stored. At the first block of a new stage, ResNet sets stride s=2s = 2 in the branch’s first convolution—halving height and width from (H,W)(H, W) to (H/2,W/2)(H/2, W/2)—while doubling channels from CC to 2C2C.

Now the branch outputs shape (2C,H/2,W/2)(2C, H/2, W/2) while the raw input xx still has shape (C,H,W)(C, H, W). To bring xx onto the new grid, ResNet places a stride-22, 1×11 \times 1 convolution Ws∈R2C×C×1×1W_s \in \mathbb{R}^{2C \times C \times 1 \times 1} (followed by BatchNorm) on the shortcut path:

y=F(x,{Wi})+BN⁡(Ws⋆s=2x).y = \mathcal{F}(x, \{W_i\}) + \operatorname{BN}(W_s \star_{s=2} x).

Stepping at stride 22 samples every second pixel spatially to match (H/2,W/2)(H/2, W/2), while the 2C2C learned 1×11 \times 1 filters linearly project the CC old channels into the new 2C2C-channel space. In a 34-layer ResNet (1616 residual blocks total), 1313 blocks use zero-parameter identity wires and only the 33 stage-transition blocks need a projection matrix WsW_s.

Hover or click any cell in the summed output xℓ+1x_{\ell + 1} below and toggle between s = 1 and s = 2 to trace which input pixels feed the 3×33 \times 3 residual branch versus the shortcut path:

Projection Shortcut Playground
Block type

64 ch→128 ch

64 ch→128 ch

Bottleneck Blocks

ResNet-18 and ResNet-34 use the two-layer 3×33 \times 3 block shown earlier (called a basic block). When scaling to 50, 101, or 152 layers with wide residual streams (256,512,1024256, 512, 1024, and 20482048 channels), running two full-width 3×33 \times 3 convolutions in every block would become prohibitively expensive.

Recall from the CNN note that a convolutional layer’s parameter count is Cout×Cin×kh×kwC_{\mathrm{out}} \times C_{\mathrm{in}} \times k_h \times k_w: it scales with kernel area (99 for 3×33 \times 3 vs. 11 for 1×11 \times 1) and quadratically with channel width when Cin=Cout=CC_{\mathrm{in}} = C_{\mathrm{out}} = C. Two 3×33 \times 3 convolutions on a 256256-channel stream require

2×(256×256×3×3)=1,179,648 weights2 \times (256 \times 256 \times 3 \times 3) = 1{,}179{,}648 \text{ weights}

in a single block—and 16×16\times more (18.9 million18.9\text{ million} weights!) if C=1024C = 1024.

He et al. replaced the two-layer block in ResNet-50/101/152 with a three-layer bottleneck block (1×1 -> 3×3 -> 1×1) that temporarily squeezes the channel width by 4×4\times before running the spatial 3×33 \times 3 filter:

  1. A 1×11 \times 1 convolution squeezes 256256 channels down to 6464 compact channels (64×256×1×1=16,38464 \times 256 \times 1 \times 1 = 16{,}384 weights).
  2. A 3×33 \times 3 spatial convolution operates inside that narrow 6464-channel subspace (64×64×3×3=36,86464 \times 64 \times 3 \times 3 = 36{,}864 weights—16×16\times cheaper than a 3×33 \times 3 convolution at 256256 channels!).
  3. A second 1×11 \times 1 convolution expands 6464 channels back out to 256256 channels (256×64×1×1=16,384256 \times 64 \times 1 \times 1 = 16{,}384 weights) so the branch can be added back onto the 256256-channel skip stream.

Together, those three layers use 16,384+36,864+16,384=69,63216{,}384 + 36{,}864 + 16{,}384 = 69{,}632 weights—nearly 17×17\times fewer than two full-width 3×33 \times 3 layers while preserving a wide, high-capacity residual stream! Step through the three stages of the bottleneck block below:

Bottleneck Block (ResNet-50 / 101 / 152)
Bottleneck Block (ResNet-50 / 101 / 152)A 1x1 convolution compresses 256 channels to 64, a 3x3 convolution filters spatially in 64 channels, and a 1x1 convolution expands back to 256 channels before joining the skip path.
256-channel skip path256\text{-channel skip path}
Wide Stream
xℓ  (256 ch)x_\ell \;(256\text{ ch})
1×1 Squeeze
256→64 ch256 \to 64\text{ ch}
3×3 Spatial
64→64 ch64 \to 64\text{ ch}
1×1 Expand
64→256 ch64 \to 256\text{ ch}
Add + ReLU
256 ch256\text{ ch}

Scroll sideways to follow the full diagram.

Wide Feature Stream

Deeper ResNets carry 256256, 512512, or 20482048 channels along the skip path. Running two full 3×33 \times 3 convolutions directly on 256256 channels would require 2×(256×256×9)=1,179,6482 \times (256 \times 256 \times 9) = 1{,}179{,}648 weights in a single block.

2×(256×256×3×3)=1,179,648 weights2 \times (256 \times 256 \times 3 \times 3) = 1{,}179{,}648\text{ weights}

Four-Stage Pyramid and Compute Scaling

Zooming out to a full ImageNet ResNet (224×224224 \times 224 RGB input), running dozens of convolutions at full 224×224224 \times 224 resolution would burn enormous memory and compute on raw pixel neighborhoods. ResNet therefore opens with an aggressive stem—a 7×77 \times 7 convolution at stride 22 (224→112224 \to 112) followed by a 3×33 \times 3 max-pooling layer at stride 22 (112→56112 \to 56)—immediately shrinking the grid 4×4\times along each axis to 56×5656 \times 56 with 6464 channels before the residual stages begin.

From there, four residual stages follow a crisp rule: whenever spatial height HH and width WW are cut in half at a stage boundary, channel width CC doubles (64→128→256→51264 \to 128 \to 256 \to 512 in ResNet-18/34, or 256→512→1024→2048256 \to 512 \to 1024 \to 2048 in bottleneck ResNet-50/101/152):

Four-stage ResNet pyramid halving spatial size and doubling channels at each transition, ending in global average pooling and a linear readout.

Why double CC every time HH and WW halve? Look at the compute cost of a convolutional block, measured in multiply-adds—the count of elementary sum += x * w steps (one multiplication plus one addition into a running accumulator) executed during a forward pass. For a 3×33 \times 3 convolution with CC input and CC output channels over an H×WH \times W grid, the number of multiply-adds is H⋅W⋅C⋅C⋅9∝H W C2H \cdot W \cdot C \cdot C \cdot 9 \propto H\,W\,C^2. Halving HH and WW cuts the number of spatial pixels by 44, while doubling CC multiplies C2C^2 by 44:

(H2)(W2)(2C)2=HW4⋅4C2=H W C2.\left(\frac{H}{2}\right)\left(\frac{W}{2}\right)(2C)^2 = \frac{HW}{4} \cdot 4C^2 = H\,W\,C^2.

The two factors of 44 cancel cleanly, meaning a block in Stage 1 (56×5656 \times 56, 6464 channels) and a block in Stage 4 (7×77 \times 7, 512512 channels) cost the exact same number of floating-point operations!

Finally, look at how the network converts the Stage 4 output volume of shape (512,7,7)(512, 7, 7) into 1,0001{,}000 category predictions. Earlier architectures like VGG-16 flattened that entire 512×7×7=25,088512 \times 7 \times 7 = 25{,}088-number volume into giant fully connected layers containing over 100 million100\text{ million} weights (25,088×4,09625{,}088 \times 4{,}096). ResNet instead applies global average pooling: for each of the 512512 channels, it simply averages the 7×7=497 \times 7 = 49 spatial numbers into a single scalar summary, turning (512,7,7)(512, 7, 7) into a compact 512512-element vector with zero learnable parameters. One final linear layer (nn.Linear(512, 1000)) then computes one raw unnormalized score per category (which can be converted into probabilities via softmax if needed). Thanks to bottleneck blocks and global average pooling, a 152-layer ResNet requires 11.3 billion11.3\text{ billion} multiply-adds per image—fewer than a 19-layer VGG network (19.6 billion19.6\text{ billion})!

Switch across ResNet-18 through ResNet-152 below to inspect constant per-block compute across all four stages, see where deeper backbones allocate their block budget, and compare Global Average Pooling against a VGG-style flattened readout head:

Four-Stage Pyramid: Compute & Parameter Inspector
Backbone
Head

Compute across Stages 1–4 (Multiply-Adds)

Parameters by Stage & Head (Millions)

Zero-γ\gamma Initialization

One practical refinement (popularized by Goyal et al., 2017, for large-batch ImageNet training and built into PyTorch via zero_init_residual=True) makes startup cleaner still: initialize every BatchNorm scale parameter to γ=1\gamma = 1 as usual except the final BatchNorm layer at the end of each residual branch, which you initialize to γ=0\gamma = 0.

At step 00 of training, multiplying by γ=0\gamma = 0 makes every residual branch output exact zeros (Fℓ(xℓ)=0\mathcal{F}_\ell(x_\ell) = 0), so even a 152-layer network begins life behaving identically to its tiny downsampling stem plus exact identity pass-throughs! Crucially, because the first convolution inside each branch still has nonzero Kaiming random weights, the final BatchNorm scale γ\gamma and convolution weights receive nonzero gradients on the very first backward pass and smoothly turn each block on as needed.

Conclusion

More than any single convolutional architecture, ResNet’s lasting contribution is the skip connection itself: passing a shared state xℓx_\ell down an unobstructed path while learned layers add incremental updates xℓ+1=xℓ+Fℓ(xℓ)x_{\ell + 1} = x_\ell + \mathcal{F}_\ell(x_\ell) has been reused directly across transformers, diffusion models, and modern state-space architectures. And while large-scale vision pretraining has largely shifted toward Vision Transformers and newer convnet variants, ResNet-18, ResNet-34, and ResNet-50 remain everyday workhorses in visuomotor robot policies, medical and industrial imaging, and real-time edge inference—settings where datasets are modest, convolutional inductive biases prevent overfitting, and fast, predictable encoders still matter.

References