Deep Residual Networks (ResNet)
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 , 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, —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 computed by a convolutional filter sliding over an input volume:
Here is called the layer’s fan-in: the count of input numbers multiplied and summed to produce one output pixel. For example, a filter reading input channels sums terms. At the start of training, we draw each weight independently at random with mean and variance . How large should we choose ?
Each input comes from passing the previous layer’s raw output through a rectified linear unit, . Suppose the previous layer’s raw outputs are distributed symmetrically around with variance . What happens to the average squared magnitude after clips the negative values?
- Half the time, , so and .
- The other half of the time, , so and .
Zeroing out exact half of a symmetric distribution cuts its average squared value in half:
Now compute the variance of the sum . Because each has mean and is drawn independently of and of the other weights, each product has mean and variance . Adding independent terms adds their variances:
Notice what happens across stacked layers if the multiplier differs even slightly from : layer ‘s output variance scales as . If that factor is , after layers the signal shrinks by ; if it is , it blows up by . Setting the multiplier equal to so variance stays constant from layer to layer () gives Kaiming initialization (He et al., early 2015):
Running the exact same variance calculation backward for the gradients flowing through transposed filters yields the mirror choice , where is the layer’s fan-out (how many output channels each patch feeds into). Either choice keeps initial forward activations and backward gradients well scaled across dozens of layers.
Drag the weight-variance numerator in below—comparing the linear Xavier scale (which ignores ‘s clipping) against Kaiming’s —to see how even a slight per-layer mismatch compounds across layers:
Batch Normalization
Kaiming initialization only guarantees healthy variance at training step . 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 activation. Unlike a fixed operation such as pooling or , a BatchNorm layer owns its own learnable parameters (a scale and a shift for each channel ), while leaving the feature volume’s spatial and channel dimensions unchanged:
To see what this layer computes during a forward pass, recall how neural networks are trained in practice. Computing a gradient over all 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 images at a time—called a minibatch (typically or images).
Recall that a convolutional filter produces a two-dimensional feature map for each input image. A layer with filters therefore produces feature maps per image, the output channels.
Suppose we process a minibatch of images, and each output feature map is . The layer produces an array of shape
We write a single value in this array as - the activation for image , in channel , at row and column .
Batch Normalization stabilizes each channel independently by pooling all numbers belonging to channel across every image and pixel in the current minibatch, computing their empirical mean and variance :
It then subtracts the mean and divides by the standard deviation so channel has mean and variance , before applying the layer’s learnable per-channel scale parameter (initialized to ) and shift parameter (initialized to )—for channels, just trainable scalars in total:
Two small details in the expressions that are worth noting:
- The constant inside the square root (typically ) is there solely for numerical safety, preventing division by zero if all entries in channel happen to take the same value.
- Why introduce learnable and right after normalizing? Forcing every channel to strict mean and unit variance right before could limit what a layer can compute—for instance, a channel might genuinely want to stay entirely positive so acts linearly. Giving gradient descent two scalar knobs and per channel lets the network choose whatever spread and bias reduces the loss while keeping gradients decoupled from how large the upstream weights 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 () deterministically without its
prediction depending on what other images happen to share a batch. During training, BatchNorm
therefore keeps a running exponential average of and , and freezes those stored
averages when evaluating. One nice side effect: if a convolutional layer is immediately followed by
BatchNorm, adding a convolutional bias would shift both and by ,
canceling identically inside while 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 minibatch BatchNorm pools together, and drag that channel’s and to watch how the affine step controls how much of the normalized activation survives :
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 , , or two-layer ReLU blocks initialized with Kaiming weights:
Learned function f(x) vs. target
Training MSE across SGD steps
Switch depth from to and . At , the plain network fits the target curve almost as cleanly as the residual network. By , the plain network has six times as many parameters as at , yet its training loss stalls orders of magnitude higher—even when you switch the target to the pure identity function .
Residual Learning
Why does a plain stack of convolutional layers struggle so badly to learn even the identity mapping ?
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:
-
Layer 1 convolves input volume with filters , normalizes each channel with Batch Normalization (), and applies to produce an intermediate feature volume :
where denotes convolution.
-
Layer 2 convolves with a second set of filters , normalizes again, and applies to produce the block’s output :
Now suppose earlier layers have already extracted a clean, useful feature map , and the best thing this two-layer block could do is leave untouched (). Even though and contain thousands of tunable weights, getting a plain block to act like a simple passthrough runs into three compounding obstacles:
-
First, erases negative values. Because Batch Normalization centers each channel around before scaling, roughly half of the numbers entering are negative and immediately clipped to 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, has no way to recover it.
To preserve both halves of across , the two layers have to coordinate an indirect workaround—either must dedicate two hidden channels to each signal (storing in one so keeps the positive peaks, and in another so flips the negative troughs above zero, which then subtracts via ), or BatchNorm’s shift must push the entire channel well above zero before applies.
-
Second, shrinking weights toward zero destroys the signal. If gradient descent pushes or toward , the convolutions output - wiping out rather than letting it pass through.
-
Third, random initialization starts far from an identity map. At training step , Kaiming weights and randomly mix channels while clips half of every hidden feature map. Chaining or plain blocks end to end scrambles 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 below to see why single-channel copying clips the negative half, how the two-channel split works around , and what zero or random weights do instead:
He et al. changed the question the layers are asked to solve. Suppose the ideal transformation a block should compute is . Define the residual to be the difference between that desired output and the input that already arrived at the layer in question:
Rearranging adds the input straight back onto the learned branch output:
Instead of asking a stack of weight layers to construct the entire output from scratch, we only task it with learning the residual beyond the output of the previous layer, wiring the input around the weight layers along a skip connection. Step through a complete residual block below:
Scroll sideways to follow the full diagram.
Incoming Representation
Block receives the multi-channel feature tensor from the previous block.
Residual Branch
Two convolutional layers compute a correction . Leaving off the second layer lets take both positive and negative values.
Identity Skip Path
Whenever height, width, and channel count stay the same across the block, travels straight around the weight layers along a parameter-free wire.
Addition and Activation
If an extra block is unnecessary, pushing makes and transmits through the sum. In the original 2015 block, a final follows the elementwise addition.
At first glance, adding 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 () produces the zero map , which wipes out the signal. In a residual block, driving the branch weights to zero produces and therefore .
- 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 around is vastly easier than re-learning 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 ) lives inside the branch , leaving the skip path as pure addition (the pre-activation block introduced in He et al.’s 2016 follow-up paper):
Substitute this rule into the next block, and then keep unrolling all the way to the final block :
Compare that last line to a plain deep network. In a plain network without skip connections, is a deeply nested composition of every layer from to ; in linear form, it behaves like a long matrix product . In a residual network, the final representation is the sum of any earlier representation plus all the residual corrections accumulated after it.
Now let us compute how the scalar training loss changes when we nudge the early feature volume . Imagine flattening all numbers of (and likewise ) into an -element vector so we can use standard multivariable calculus:
- The derivative is an table of partial derivatives—called a Jacobian matrix—whose entry records how much entry of changes per unit nudge to entry of .
- Differentiating with respect to itself produces the identity matrix (ones down the main diagonal and zeros everywhere else, because entry of changes at rate with respect to itself and rate with respect to every other entry ). Multiplying any vector by leaves that vector unchanged.
Applying the multivariable chain rule to gives:
Look closely at those two additive pieces:
- The first term, , arrives at layer directly from the end of the network without being multiplied by a single intermediate weight matrix. Whether layer sits blocks before the output or blocks before the output, it hears the loss gradient at full strength on step of training.
- Even if several intermediate branches currently have tiny weights or dead units so their derivatives are nearly zero, the total gradient at does not collapse—it gracefully falls back to . For the gradient at to cancel to zero, the summed branch Jacobians would have to align to exact 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 of each block was placed after
the skip addition (post-activation):
. Because that outer
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 layers on CIFAR-10 in 2016, however, those repeated
post-addition gates started impeding signal flow again. Moving BatchNorm and
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:
Scroll sideways to follow the full diagram.
Unobstructed Residual Stream
In the 2015 post-activation block, applying after the sum zeroes out negative entries on the main stream. Pre-activation ResNet removes all gates from the skip connection itself.
Normalize and Activate Inside the Branch
Batch Normalization and now run inside the branch before each convolution, and the second convolution adds its raw signed output directly onto the stream.
Exact Telescoping Sum
Unrolling from any shallow block to the final block produces a clean sum—every deeper block directly sees plus all intermediate updates.
Direct Backward Gradient Path
Differentiating with respect to yields an identity matrix alongside the branch derivatives, carrying directly back to early layers regardless of depth.
Drag the depth and per-layer derivative scale below to compare how quickly a plain multiplicative chain decays (or explodes) next to the post-activation and pre-activation residual paths:
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 speaks an entirely different coordinate language from layer . 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 percentage points)! Only when or 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 blocks reveals two complementary reasons:
- A shared representation that blocks refine incrementally. Because every block adds its output directly into the running tensor , 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 (), gradually sharpening edges, suppressing noise, and grouping object parts rather than scrambling channels at every step.
- An implicit collection of paths. At block , information can either follow the skip wire or pass through ; at block , each of those two signals again splits two ways. Across blocks there are distinct input-to-output paths! By the binomial theorem, the number of paths passing through nonlinear branches is , which concentrates tightly around . Most gradient flow travels along moderate-length paths of rough depth – even inside a -block ResNet, and removing one block leaves intact paths still carrying a coherent feature map to the classifier.
Explore both phenomena directly in the interactive residual stream below. Click through blocks
to to inspect the incoming stream , the signed correction
(blue for negative suppression, terracotta for positive
reinforcement), and the updated state —then click Disable block and toggle between
ResNet and Plain stack to run Veit et al.’s lesion experiment yourself:
To see the combinatorial side of that resilience, click any block in the unrolled trellis below to lesion it—comparing how a plain serial chain loses its single path immediately while a ResNet routes intact paths around the gap—and hover any path depth in the chart to see how backward gradient flow concentrates along shallower effective paths:
Click any block to lesion (delete) it at test time
Network Architecture
Scaling 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 is only well defined when and have the exact same shape . Within a stage, every convolution uses padding , stride , and constant channel count , 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 in the branch’s first convolution—halving height and width from to —while doubling channels from to .
Now the branch outputs shape while the raw input still has shape . To bring onto the new grid, ResNet places a stride-, convolution (followed by BatchNorm) on the shortcut path:
Stepping at stride samples every second pixel spatially to match , while the learned filters linearly project the old channels into the new -channel space. In a 34-layer ResNet ( residual blocks total), blocks use zero-parameter identity wires and only the stage-transition blocks need a projection matrix .
Hover or click any cell in the summed output below and toggle between s = 1 and
s = 2 to trace which input pixels feed the residual branch versus the shortcut path:
Bottleneck Blocks
ResNet-18 and ResNet-34 use the two-layer block shown earlier (called a basic block). When scaling to 50, 101, or 152 layers with wide residual streams (, and channels), running two full-width convolutions in every block would become prohibitively expensive.
Recall from the CNN note that a convolutional layer’s parameter count is : it scales with kernel area ( for vs. for ) and quadratically with channel width when . Two convolutions on a -channel stream require
in a single block—and more ( weights!) if .
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 before running the
spatial filter:
- A convolution squeezes channels down to compact channels ( weights).
- A spatial convolution operates inside that narrow -channel subspace ( weights— cheaper than a convolution at channels!).
- A second convolution expands channels back out to channels ( weights) so the branch can be added back onto the -channel skip stream.
Together, those three layers use weights—nearly fewer than two full-width layers while preserving a wide, high-capacity residual stream! Step through the three stages of the bottleneck block below:
Scroll sideways to follow the full diagram.
Wide Feature Stream
Deeper ResNets carry , , or channels along the skip path. Running two full convolutions directly on channels would require weights in a single block.
1×1 Channel Compression
First, a convolution compresses the channels at each pixel down to channels ( narrower) using only weights.
3×3 Filtering in the Narrow Subspace
Next, the spatial filter runs on only input and output channels. Because parameter count scales with , shrinking channel width by cuts the cost by .
1×1 Expansion Back to Stream Width
A second convolution expands channels back to ( weights) and adds the result onto . All three layers together use weights—about fewer than a two-layer block at width .
Four-Stage Pyramid and Compute Scaling
Zooming out to a full ImageNet ResNet ( RGB input), running dozens of convolutions at full resolution would burn enormous memory and compute on raw pixel neighborhoods. ResNet therefore opens with an aggressive stem—a convolution at stride () followed by a max-pooling layer at stride ()—immediately shrinking the grid along each axis to with channels before the residual stages begin.
From there, four residual stages follow a crisp rule: whenever spatial height and width are cut in half at a stage boundary, channel width doubles ( in ResNet-18/34, or in bottleneck ResNet-50/101/152):
Why double every time and 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
convolution with input and output channels over an grid, the number of
multiply-adds is . Halving and cuts the
number of spatial pixels by , while doubling multiplies by :
The two factors of cancel cleanly, meaning a block in Stage 1 (, channels) and a block in Stage 4 (, channels) cost the exact same number of floating-point operations!
Finally, look at how the network converts the Stage 4 output volume of shape into
category predictions. Earlier architectures like VGG-16 flattened that entire
-number volume into giant fully connected layers containing over
weights (). ResNet instead applies global average
pooling: for each of the channels, it simply averages the spatial numbers
into a single scalar summary, turning into a compact -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
multiply-adds per image—fewer than a 19-layer VGG network
()!
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:
Compute across Stages 1–4 (Multiply-Adds)
Parameters by Stage & Head (Millions)
Zero- 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 as usual except the final BatchNorm layer at the end of
each residual branch, which you initialize to .
At step of training, multiplying by makes every residual branch output exact zeros (), 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 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 down an unobstructed path while learned layers add incremental updates 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
- He, Zhang, Ren, & Sun, Deep Residual Learning for Image Recognition (CVPR 2016, arXiv Dec 2015). Introduces the degradation problem, residual blocks, projection shortcuts, and bottleneck architectures up to 152 and 1,202 layers.
- He, Zhang, Ren, & Sun, Identity Mappings in Deep Residual Networks (ECCV 2016). Analyzes signal propagation along the skip path and introduces pre-activation residual blocks up to 1,001 layers.
- He, Zhang, Ren, & Sun, Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification (ICCV 2015). Derives variance-preserving Kaiming initialization for ReLU networks.
- Ioffe & Szegedy, Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift (ICML 2015).
- Veit, Wilber, & Belongie, Residual Networks Behave Like Ensembles of Relatively Shallow Networks (NeurIPS 2016). Unrolls ResNets into paths of binomial effective depth and demonstrates lesion resilience when deleting individual blocks.