Back to paper library
Paper notesarXiv 2016ECCV 2016

Stochastic Depth

This Layer Is Taking the Day Off

Original paper

Deep Networks with Stochastic Depth

Paper authors

Gao Huang · Yu Sun · Zhuang Liu · Daniel Sedra · Kilian Weinberger

Publication
ECCV 2016Conference
First submitted to arXiv
arXiv:1603.09382
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{classiccnnsstochasticdepth2016,
  title = {{Deep Networks with Stochastic Depth}},
  author = {Gao Huang and Yu Sun and Zhuang Liu and Daniel Sedra and Kilian Weinberger},
  year = {2016},
  eprint = {1603.09382},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1603.09382}
}
On this page

Training very deep networks comes with a dilemma.

In a shallow network, signals flow smoothly forward and backward and training is fast, but its expressive power is limited. A deep network is more expressive, but gradients vanish, features computed early on get washed out by layer after layer of weights, and training time grows along with depth, so a 152-layer ResNet takes weeks to train on ImageNet even with several GPUs.

What if you trained a shallow network and tested a deep one?

That sounds self-contradictory. In March 2016, Gao Huang, Yu Sun, Daniel Sedra, and Kilian Q. Weinberger of Cornell University, together with Zhuang Liu of Tsinghua University, released this paper. They build the network just as deep, but for every mini-batch during training, they randomly remove some of the residual blocks, leaving only their shortcuts.

Defining the Problem

The authors list three problems that very deep networks run into:

  1. Vanishing gradients: as gradients propagate backward, they're multiplied by small weights again and again, so by the time they reach the early layers they've become tiny.
  2. Diminishing forward features: input features, or features computed by early layers, are multiplied again and again by randomly initialized weights until they're “washed out” further on, which makes it hard for later layers to find meaningful gradient directions.
  3. Training takes too long: forward and backward propagation time both grow linearly with depth.

ResNet and Highway Networks tackle the first two problems with shortcuts that let features and gradients bypass weight layers. The third problem remains. However deep the network is, every step has to compute that many layers.

Is there a way to make a network shallower “on average” during training while keeping its full depth at test time?

Solving the Problem

Letting Blocks Randomly Sit Out

The authors use ResNet's original residual block. The output of block ℓ\ell is:

Hℓ=ReLU(fℓ(Hℓ−1)+id(Hℓ−1))H_\ell = \mathrm{ReLU}\big(f_\ell(H_{\ell-1}) + \mathrm{id}(H_{\ell-1})\big)

fℓf_\ell is “convolution, BN, ReLU, convolution, BN,” and id\mathrm{id} is the identity shortcut.

Stochastic depth adds just one Bernoulli random variable, bℓ∈{0,1}b_\ell \in \{0, 1\}:

Hℓ=ReLU(bℓ fℓ(Hℓ−1)+id(Hℓ−1))H_\ell = \mathrm{ReLU}\big(b_\ell\, f_\ell(H_{\ell-1}) + \mathrm{id}(H_{\ell-1})\big)

When bℓ=1b_\ell = 1, this is the original residual block. When bℓ=0b_\ell = 0, the residual branch disappears entirely, leaving ReLU(Hℓ−1)\mathrm{ReLU}(H_{\ell-1}).

Hℓ−1H_{\ell-1} is the output of the previous block's final ReLU, so it's never negative (the input to the first block is also the output of a “convolution, BN, ReLU” stack), which means ReLU(Hℓ−1)=Hℓ−1\mathrm{ReLU}(H_{\ell-1}) = H_{\ell-1}. An absent block is therefore exactly an identity mapping, and the signal passes to the next block untouched.

The probability that bℓ=1b_\ell = 1 is written pℓp_\ell, which the authors call the survival probability. It's redrawn for every mini-batch, and a block drawn to sit out costs nothing at that step, with no forward pass, no backward pass, and no weight update.

Early Layers Show Up More Often

How should each block's survival probability be set? The simplest choice is to make them all the same. The authors recommend a linear decay, with p0=1p_0 = 1 at the input, pLp_L for the last block, and a proportional decrease in between:

pℓ=1−ℓL(1−pL)p_\ell = 1 - \frac{\ell}{L}(1 - p_L)
The top half is a row of bars labeled 1.0, 0.9, 0.8, 0.7, 0.6, and 0.5; their blue portions represent the survival probability and get shorter from left to right, and a small inset illustrates the two block states, active and inactive. The bottom half has a photo of a flower as the Input, followed by five residual blocks f1 to f5 with H1 to H4 between them; f3 and f5 are crossed out with red X's, meaning they're skipped this time
Fig. 2 from the paper, excerpted from page 5 of the v3 PDF. Linear decay with p0=1p_0 = 1 and pL=0.5p_L = 0.5; the input to the first block is treated as an always-present H0H_0.

Early layers extract low-level features that every later layer uses, so the authors argue that they should show up more reliably. The experiments also show linear decay beating a uniform probability; and since results aren't very sensitive to pLp_L, they use pL=0.5p_L = 0.5 throughout the paper.

Take the 110-layer ResNet commonly used in CIFAR experiments. It has L=54L = 54 residual blocks, with survival probabilities falling linearly from 0.991 for the first block to 0.5 for the last. During training, each pass uses only about 40 blocks on average, while testing uses all 54. The expected depth is ∑ℓpℓ=(3L−1)/4\sum_\ell p_\ell = (3L-1)/4, about 3L/43L/4; the quarter left uncomputed is what training time saves. The depth of each sampled network also varies a lot, so some updates go through especially short networks, and the gradient's path to the early layers is more direct.

Multiply by the Survival Probability at Test Time

At test time, every block has to be present so the full capacity of the network gets used. But during training, fℓf_\ell appears in only a fraction pℓp_\ell of the updates, and the next layer's weights are calibrated to that fraction. So at test time, each block's output is multiplied by its survival probability:

HℓTest=ReLU(pℓ fℓ(Hℓ−1Test;Wℓ)+Hℓ−1Test)H_\ell^{\text{Test}} = \mathrm{ReLU}\big(p_\ell\, f_\ell(H_{\ell-1}^{\text{Test}}; W_\ell) + H_{\ell-1}^{\text{Test}}\big)

Let's write a block and compare its outputs during training and testing. To keep things easy to see, the residual function here is a single linear layer, and we leave out the final ReLU for now:

Python
import torch
import torch.nn as nn

class StochasticDepthBlock(nn.Module):
    def __init__(self, f, p):
        super().__init__()
        self.f, self.p = f, p                      # p: this block's survival probability

    def forward(self, x):
        if self.training:
            if torch.rand(()) < self.p:            # survives: compute the residual as usual
                return x + self.f(x)
            return x                               # doesn't survive: the whole block becomes an identity mapping
        return x + self.p * self.f(x)              # testing: multiply by the survival probability

torch.manual_seed(0)
block = StochasticDepthBlock(nn.Linear(4, 4), p=0.6)
x = torch.randn(1, 4)

block.train()
with torch.no_grad():
    outs = torch.stack([block(x) for _ in range(20000)])
block.eval()
with torch.no_grad():
    test = block(x)

print("During training, the block produces", torch.unique(outs.round(decimals=4), dim=0).shape[0], "distinct outputs")
print("Mean of training outputs:", [f"{v:.3f}" for v in outs.mean(0).squeeze()])
print("Output at test time:     ", [f"{v:.3f}" for v in test.squeeze()])
Text
During training, the block produces 2 distinct outputs
Mean of training outputs: ['-0.479', '0.711', '-1.017', '1.223']
Output at test time:      ['-0.479', '0.713', '-1.017', '1.223']

During training, this block's output either includes the residual or doesn't. Averaged over twenty thousand runs, it is almost identical to the test-time output, which multiplies by p=0.6p = 0.6.

Why Does It Work?

The authors give three reasons.

  • Faster training: skipped blocks aren't computed, so forward and backward propagation time follows the expected depth rather than the full depth.
  • Stronger gradients: the network is shorter during training, so gradients pass through fewer layers, and the early layers receive larger gradients.
  • An implicit ensemble: with 54 blocks, each either present or absent, there are 2542^{54} combinations in all. Each mini-batch samples one weight-sharing sub-network to update, and at test time the formula above merges them into a single network. The record-breaking results in the ResNet paper came precisely from an ensemble of ResNets of different depths.

This ensemble view resembles dropout. The difference is that dropout makes the network narrower, while stochastic depth makes it shallower. The authors also note that dropout often becomes less effective when combined with batch normalization. They tried various dropout rates on a 110-layer ResNet with BN and saw almost no improvement, while stochastic depth still worked on the same network.

Discussion

Error Rates and Training Time

Table: Selected rows excerpted from Table 1 of the paper, test error (%); “+” means standard data augmentation is used. “Constant depth” is the authors' own reproduction of He et al.'s experiments.
MethodCIFAR-10+CIFAR-100+SVHNImageNet
Highway Network7.6032.24––
Gen. Pool6.0528.021.69–
ResNet, constant depth6.4127.761.8021.78
ResNet, stochastic depth5.2524.981.7521.98

CIFAR-10 uses a 110-layer ResNet trained for 500 epochs. With constant depth, the error is 6.41%; adding stochastic depth brings it down to 5.25%, an 18% relative improvement. The training and network settings are exactly the same; the only difference is randomly skipping blocks during training. CIFAR-100 uses the same network and goes from 27.76% to 24.98%.

Two sets of training curves: on the left, a 110-layer ResNet on CIFAR-10; on the right, CIFAR-100. The red line is the test error with constant depth, the blue line the test error with stochastic depth, and the two thin lines are their training losses. After the learning rate drops at epoch 250, the blue line is clearly below the red one; the left plot marks 6.41% and 5.25%, and the right marks 27.88% and 24.98%
Fig. 3 from the paper, excerpted from page 8 of the v3 PDF. Test error and training loss on CIFAR-10 (left) and CIFAR-100 (right); the dots mark the epoch with the lowest validation error.

After the first learning-rate drop, the constant-depth test error more or less stalls, while stochastic depth keeps going down. The authors also notice that the stochastic-depth test error fluctuates more, presumably because the depth keeps changing during training.

Without data augmentation, stochastic depth also gives about a 15% relative improvement on both CIFAR-10 and CIFAR-100, from 13.63% to 11.66% and from 44.74% to 37.8%, respectively. SVHN uses a 152-layer network; with constant depth it starts to overfit as soon as the second phase begins, ending at 1.80% error, while stochastic depth gets 1.75%.

Training time compared:

Table: Excerpted from Table 2 of the paper, with linear decay and pL=0.5p_L = 0.5.
CIFAR-10+CIFAR-100+SVHN
Constant depth20 h 42 min20 h 51 min33 h 43 min
Stochastic depth15 h 7 min15 h 20 min25 h 33 min

Every setting saves about a quarter of the time, consistent with the expected depth computed earlier.

Twelve Hundred Layers

The ResNet paper tried a 1202-layer network, which overfit, ending with 7.93% test error, worse than 110 layers. The authors redo this experiment with the same 1202-layer network, training for 300 epochs with a warm-up learning rate of 0.01 for the first 10 epochs.

The constant-depth 1202-layer network gets 6.67% error, again worse than the 110-layer network's 6.41%. With stochastic depth, the error is 4.91%, a 27% relative improvement over the constant-depth 1202-layer network and better than the stochastic-depth 110-layer network (5.25%) as well, with no sign of overfitting. The authors say this is the first time a network with more than a thousand layers has reduced test error further than a shallower network.

No Win on ImageNet

ImageNet uses the 152-layer ResNet. Trained for 90 epochs with constant depth, it gets 23.06% error; with stochastic depth, it's at 23.38% at epoch 90, slightly worse. The authors observed that the stochastic-depth validation error was still clearly falling, and since stochastic depth saves 25% of the computation, training it for 30 more epochs takes about the same total time as 90 epochs at constant depth. With the extra training, stochastic depth reaches 21.98%; but constant depth was also run for 30 more epochs, and it reached 21.78%.

So in this setting, stochastic depth brings no accuracy benefit. The authors cite an anonymous reviewer's view that models for ImageNet are still in a different regime from those for CIFAR. The model complexity ImageNet calls for may far exceed a 152-layer ResNet, and stochastic depth may only show its effect with larger models.

Are the Gradients Really Stronger?

A line chart with epochs on the horizontal axis (0 to 500) and the first convolutional layer's mean gradient magnitude on the vertical axis (in units of 10 to the minus 5). The red line is constant depth and the blue line is stochastic depth. Two dashed lines mark the learning-rate drops at epochs 250 and 375, where the gradients fall sharply; the blue line stays above the red throughout, and the gap is more pronounced after the learning-rate drops
Fig. 7 from the paper, excerpted from page 12 of the v3 PDF. Mean gradient magnitude per epoch of the first convolutional layer of the first residual block on CIFAR-10; the dashed lines mark when the learning rate is divided by 10.

The two sharp drops come from the learning-rate schedule. Stochastic depth's gradients are larger throughout, and the gap widens after the learning-rate drops, which supports the authors' claim that it alleviates vanishing gradients.

What Should the Survival Probability Be?

Left: test error of a 110-layer ResNet on CIFAR-10 as the survival probability p_L varies. The solid line is linear decay, the dashed line is a uniform probability, and the red dashed line is constant depth at 6.41%. The linear-decay curve is lowest around a p_L of 0.5, at about 5.25%, labeled with a 1.33x speedup; at a p_L of 0.2 it's still close to constant depth, labeled 1.67x; the uniform curve is mostly higher, dipping below linear decay only around a p_L of 0.8, and is labeled 2x at a p_L of 0.5. Right: a heat map with p_L on the vertical axis (1.0 to 0.5) and network depth on the horizontal axis (20 to 110 layers), with test errors in the cells; at 20 layers, a p_L between 0.9 and 0.7 beats constant depth and anything lower is worse, at 110 layers a p_L of 0.5 is best, and the lowest values lie roughly along the diagonal
Fig. 8 from the paper, excerpted from page 13 of the v3 PDF. Left: CIFAR-10 test error of a 110-layer ResNet for different values of pLp_L; right: test error across pLp_L and network depth, where the pL=1p_L = 1 row is constant depth.

pLp_L is the method's only hyperparameter, and the left plot shows how it affects the error rate.

  1. As long as pLp_L is set reasonably, both rules beat constant depth.
  2. For most values of pLp_L, linear decay beats a uniform probability.
  3. Linear decay isn't very sensitive to pLp_L, giving good results for pLp_L between 0.4 and 0.8.
  4. Even at pL=0.2p_L = 0.2, linear decay's error is on par with constant depth, while training time drops by 40%.

The heat map on the right adds depth. For a 20-layer network, skipping a little (pLp_L between 0.9 and 0.7) beats constant depth, but skipping more makes it worse, with the error rising from 8.31% to 9.39% at pL=0.5p_L = 0.5. For a 110-layer network, pL=0.5p_L = 0.5 is best. The best-performing cells lie roughly along the diagonal, meaning the deeper the network, the more aggressive the skipping it can handle. The network has to be deep enough for stochastic depth to clearly beat constant depth; for shallower networks, more conservative skipping still helps.

Conclusion

Stochastic depth is a training method that leaves the test-time network unchanged. It randomly skips residual blocks during training, bringing the expected depth down to about three quarters, then combines all the blocks at test time using the survival probabilities. Experimentally, error rates fall on CIFAR and SVHN, training time drops by about a quarter, and the 1202-layer network no longer overfits. The 152-layer ResNet on ImageNet, however, shows no accuracy benefit.

In some libraries, it goes by the name DropPath. A few months later, Gao Huang, Zhuang Liu, and Kilian Q. Weinberger from this paper proposed DenseNet, whose introduction cites stochastic depth right at the start, arguing that if training still works when layers are randomly skipped, then many layers in a residual network actually contribute very little.

Using stochastic depth just means multiplying each residual branch by a random 0 or 1 during training and by the survival probability at test time. Most libraries today divide by the survival probability during training instead, like torchvision's stochastic_depth, so nothing needs to change at test time.

Back then, the authors guessed that stochastic depth might only pay off on ImageNet with larger models. Later, the training recipes of large models such as ConvNeXt and DINOv2 did indeed include it.