AI Logic

Regularization

Stochastic Depth (DropPath)

Updated:

Stochastic Depth during training and inference. On the left, during training, each of 5 residual blocks multiplies its transformation f by a b of 0 or 1; blocks with b = 0 (the 3rd and 5th in the example) skip the transformation entirely and pass only the identity shortcut. The survival probability p decreases linearly from 0.9 for the block nearest the input to 0.5 for the last block. On the right, during inference, all blocks are used, and the transformation's output is multiplied by the survival probability p before being added to the shortcut

Background and Overview

Stochastic Depth is a regularization method that trains very deep residual networks faster and better by randomly skipping the entire transformation of residual blocks during training. Huang and colleagues presented it at ECCV in 2016. Today it is also widely known as DropPath (the origin of that name is explained in a later section).

Networks with hundreds of stacked layers, such as ResNet, are highly expressive, but training them faces three difficulties.

  • Vanishing gradients: As the error is propagated back toward the input, the gradient keeps shrinking (the vanishing gradient problem).
  • Diminishing features: Even in the forward computation, the input and earlier-layer features fade as they are multiplied by weights again and again.
  • Long training time: Computation grows in proportion to the number of layers.

Shallow networks are easy to train but lack expressive power. So the paper proposed a seemingly contradictory combination: shallow during training, deep during inference. It starts with a deep residual network and, during training, picks some blocks for each mini-batch and skips their transformations. In a skipped block, only the identity shortcut (skip connection), which passes the input on unchanged, remains. At inference, all blocks are used.

It is like a team that rests a few members at every practice and plays short-handed, then enters the real game with everyone present. Each member is trained to keep things running no matter who is absent, and in the real game the whole team's strength is combined. Whereas Dropout drops units to make the network "thinner," Stochastic Depth drops blocks to make it "shorter."

Theory (Training and Inference)

The explanation follows Equations (1)–(5) in Section 3 of the original paper. The network is a stack of LL residual blocks (ResBlocks); HℓH_\ell is the output of the ℓ\ell-th block and fℓf_\ell its transformation (in the paper: convolution → batch normalization → ReLU → convolution → batch normalization).

  1. An ordinary ResBlock adds the transformation's output to the identity shortcut and applies ReLU (Equation 1). Hℓ=ReLU(fℓ(Hℓ−1)+id(Hℓ−1))H_\ell = \mathrm{ReLU}\bigl(f_\ell(H_{\ell-1}) + \mathrm{id}(H_{\ell-1})\bigr)
  2. During training, each block draws bℓ∈{0,1}b_\ell \in \{0, 1\}, which indicates whether it is used, from a Bernoulli distribution. The probability pℓp_\ell that bℓ=1b_\ell = 1 is called the survival probability. bℓ∼Bernoulli(pℓ)b_\ell \sim \mathrm{Bernoulli}(p_\ell)
  3. Multiply the transformation's output by bℓb_\ell (Equation 2). If bℓ=1b_\ell = 1, the block is an ordinary ResBlock; if bℓ=0b_\ell = 0, the transformation disappears and the block simply passes its input through (Equation 3). Hℓ=ReLU(bℓ fℓ(Hℓ−1)+id(Hℓ−1)),bℓ=0  ⇒  Hℓ=id(Hℓ−1)H_\ell = \mathrm{ReLU}\bigl(b_\ell\, f_\ell(H_{\ell-1}) + \mathrm{id}(H_{\ell-1})\bigr), \qquad b_\ell = 0 \;\Rightarrow\; H_\ell = \mathrm{id}(H_{\ell-1})
  4. The survival probability decreases linearly from the input side (p0=1p_0 = 1) to the last block (pLp_L) (Equation 4). The paper uses pL=0.5p_L = 0.5 in all experiments. pℓ=1−ℓL (1−pL)p_\ell = 1 - \frac{\ell}{L}\,(1 - p_L)
  5. Repeat steps 2–3, redrawing bℓb_\ell for each mini-batch.
  6. At inference, use all blocks and multiply the transformation's output by the survival probability pℓp_\ell (Equation 5). HℓTest=ReLU(pℓ fℓ(Hℓ−1Test)+Hℓ−1Test)H_\ell^{\text{Test}} = \mathrm{ReLU}\bigl(p_\ell\, f_\ell(H_{\ell-1}^{\text{Test}}) + H_{\ell-1}^{\text{Test}}\bigr)

The multiplication by pℓp_\ell in step 6 matches the output scale to its average during training, just as in Dropout. Since fℓf_\ell participates in only a fraction pℓp_\ell of the updates during training, it is added with weight pℓp_\ell at inference too.

In step 3, ReLU(Hℓ−1)=Hℓ−1\mathrm{ReLU}(H_{\ell-1}) = H_{\ell-1} when bℓ=0b_\ell = 0 because the block's input Hℓ−1H_{\ell-1} is always non-negative (the previous block ends with a ReLU). So a skipped block becomes a layer that truly does nothing, and its forward and backward computation can be skipped entirely.

The linear decay in step 4 reflects the idea that "layers near the input produce basic features used by all later layers, so they should always be present." With pL=0.5p_L = 0.5, the expected number of blocks actually used during training is as follows.

E(L~)=∑ℓ=1Lpℓ=3L−14\mathbb{E}(\tilde{L}) = \sum_{\ell=1}^{L} p_\ell = \frac{3L - 1}{4}

For the paper's 110-layer ResNet (L=54L = 54), this is about 40 blocks. During training, the network is effectively a shallow one with 40 blocks on average, and at inference it uses all 54. Because computation is skipped, training time drops by about 25%.

Why It Works

The paper gives two reasons the test error goes down.

  • Gradients reach the input side more easily: Because the network is shallower during training, the paths for propagating the error backward are shorter. In the paper's CIFAR-10 experiment (Figure 7), the magnitude of the gradient reaching the first convolutional layer was consistently larger than in an ordinary ResNet, and the gap was especially large after the learning rate was lowered.
  • It forms an ensemble of networks of different depths: There are 2L2^L combinations of using or not using each of the LL blocks, and each mini-batch trains one of them while sharing weights. Inference with Equation 5 can be viewed as merging all of them into one network and averaging. Whereas Dropout's ensemble consists of "networks of the same depth but different widths," this one consists of "networks of different depths," which the paper suggests can make the ensemble more diverse.

The paper also shows that Stochastic Depth acts as a regularizer even when combined with batch normalization. In contrast, it reports that adding Dropout to a 110-layer ResNet with batch normalization brought almost no improvement (even when varying the drop rate).

Experimental Results

Results reported in Tables 1 and 2 and Section 4 of the original paper. All use linear decay with pL=0.5p_L = 0.5, and show the test error at the epoch with the lowest validation error ("+" means data augmentation with horizontal flips and translations).

DatasetNetworkOrdinary ResNetStochastic Depth
CIFAR-10+110 layers6.41%5.25%
CIFAR-100+110 layers27.76%24.98%
CIFAR-10 (no augmentation)110 layers13.63%11.66%
CIFAR-100 (no augmentation)110 layers44.74%37.8%
SVHN152 layers1.80%1.75%
CIFAR-10+1202 layers6.67%4.91%
ImageNet (validation error)152 layers21.78%21.98%
  • Resists overfitting even when deeper: The ordinary ResNet got worse at 1202 layers than at 110 layers (6.67%). With Stochastic Depth, going to 1202 layers lowered the error further, from 5.25% at 110 layers to 4.91%.
  • Faster training: Training time went from 20 h 42 min to 15 h 7 min on CIFAR-10+ and from 33 h 43 min to 25 h 33 min on SVHN, roughly 25% shorter in each case (Table 2).
  • Insensitive to pLp_L: For the 110-layer network on CIFAR-10, linear decay was always better than giving every block the same probability, and results were stable for pLp_L between 0.4 and 0.8. Even lowering it to pL=0.2p_L = 0.2 kept the error equal to the ordinary ResNet while cutting training time by about 40% (Figure 8).
  • No improvement on ImageNet: For a 152-layer ResNet trained for 120 epochs in both cases, Stochastic Depth was slightly worse. The paper suggests that ImageNet needs larger models and that, at this model size, the regularization had little room to help.

The paper's value for the ordinary ResNet on CIFAR-100+ is inconsistent between Table 1 (27.76%) and the main text (27.22%). The table above uses the Table 1 value.

The Name DropPath and Library Implementations

The name "DropPath" originally belonged to a method from a different paper. FractalNet by Larsson et al. (ICLR 2017) is a network with a "fractal" structure that runs several paths in parallel and averages them, and it named its regularizer, which randomly drops the inputs (paths) into join points, drop-path. The FractalNet paper cites Stochastic Depth and explains the difference: "like Stochastic Depth, it drops large components, but it uses the fractal structure to decide which ones to drop."

Later, the image-model library timm named its operation that drops a residual block's transformation per sample DropPath (the function is drop_path). The description in timm's source code reads "Drop paths (Stochastic Depth) per sample," and notes that it was previously called DropConnect but was renamed because DropConnect is a different method that drops weights. Today, DropPath almost always means Stochastic Depth for residual networks. For example, DeiT uses Stochastic Depth (drop probability 0.1) to train a Vision Transformer.

Library implementations differ from the paper's equations in the following three ways.

Library arguments are drop probabilities, and outputs are rescaled during training. Both torchvision's StochasticDepth(p, mode) and timm's DropPath(drop_prob) take not the paper's survival probability pℓp_\ell but the drop probability 1−pℓ1 - p_\ell. They also multiply the kept output by 1/(1−p)1/(1-p) during training and do nothing at inference (the same approach as inverted dropout). The goal of matching the average output is the same as in the paper's Equation 5.

  • Unit of dropping: The paper decides once per mini-batch whether to use a block. timm's DropPath and torchvision's mode="row" decide per sample within the mini-batch. To match the paper, use torchvision's mode="batch". Per-sample dropping cannot skip computation for the mini-batch as a whole, so it does not shorten training time as in the paper.
  • Where it is applied: It is applied to the residual branch (the transformation's output), as in x + drop_path(f(x)), and the identity shortcut is left untouched. Dropping the shortcut too would cut off the flow of information there.
  • How probabilities are set: timm's calculate_drop_path_rates increases the drop probability linearly, block by block, from 0 to a specified maximum. This is essentially the same idea as the paper's linear decay.

Practical Considerations

It only applies to architectures with identity shortcuts (residual connections). Stochastic Depth assumes that the shortcut passes the input along in place of a skipped block. Skipping layers in a network without shortcuts cuts off the flow of information at that point.

  • Weaken it for shallow networks: In Figure 8 (right) of the paper, pL=0.5p_L = 0.5 worked best for deeper networks, while shallower networks did better with less skipping (a larger pLp_L). The paper also notes that without a sufficiently deep model, it is hard to beat an ordinary ResNet by a wide margin.
  • Start with linear decay and pL=0.5p_L = 0.5 (a drop probability of 0.5): This is the value used in all of the paper's experiments. For Vision Transformers, smaller values such as DeiT's drop probability of about 0.1 are also used.
  • Do not forget model.eval(): The computation differs between training and inference. Without calling model.eval() before evaluation, blocks are skipped at random on every inference.
  • Learning curves tend to fluctuate: In the paper, the test error fluctuated a bit more than for an ordinary ResNet (because the depth changes randomly). Choosing the epoch with the best validation error is a safe approach.

Comparison with Other Methods

All of these randomly disable parts of the network during training, but they differ in the unit that is disabled and the architecture they assume.

MethodUnit disabledWhat flows in its placeAssumed architecture
DropoutUnits (output elements), one at a time0Any layer
Stochastic Depth (DropPath)A residual block's entire transformationThe input via the identity shortcutResidual connections
FractalNet's drop-pathInput paths into a join pointAverage of the remaining pathsFractal structure of parallel paths
ZoneoutElements of an RNN's hidden state, one at a timeThe value from the previous time stepRNN (recurrence over time)
  • When training deep residual networks or Vision Transformers, Stochastic Depth is the first candidate. Besides regularization, the paper's per-mini-batch method also reduces training time.
  • To regularize fully connected layers without residual connections, or fine-grained parts inside a block, use Dropout. The two can also be combined.
  • The Zoneout paper notes that Zoneout can be viewed as "per-unit Stochastic Depth." Whereas Stochastic Depth turns all units of a layer into the identity at once, Zoneout does so unit by unit along the time dimension of an RNN.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import StochasticDepth


# 1. A ResBlock following the paper's equations (f = conv → BN → ReLU → conv → BN)
class ResBlockSD(nn.Module):
    def __init__(self, channels, survival_prob):
        super().__init__()
        self.p = survival_prob  # survival probability p_ℓ (the paper's p, the keep probability)
        self.f = nn.Sequential(
            nn.Conv2d(channels, channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(channels, channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(channels),
        )

    def forward(self, x):
        if self.training:
            # Decide once per mini-batch whether to use this block (b ~ Bernoulli(p))
            if torch.rand(1).item() < self.p:
                return F.relu(self.f(x) + x)      # b = 1: ordinary ResBlock (Eq. 2)
            return x                              # b = 0: skip without computing the transformation (Eq. 3; x is post-ReLU, so non-negative)
        return F.relu(self.p * self.f(x) + x)     # inference: scale the transformation's output by p and add (Eq. 5)


# Linear decay of survival probability (Eq. 4): p_ℓ = 1 − (ℓ / L)(1 − p_L)
L, p_L = 54, 0.5
probs = [1 - (l / L) * (1 - p_L) for l in range(1, L + 1)]
print(round(probs[0], 3), probs[-1])        # 0.991 0.5
print(round(sum(probs), 2))                 # 40.25 (expected number of blocks used in training, (3L − 1) / 4)

net = nn.Sequential(*[ResBlockSD(16, p) for p in probs[:3]])
x = torch.relu(torch.randn(8, 16, 32, 32))  # block inputs are non-negative
net.train()
y_train = net(x)   # the skipped blocks change on every call
net.eval()
y_test = net(x)    # all blocks are used


# 2. torchvision's StochasticDepth (argument p is the *drop* probability; scales by 1/(1 − p) in training, does nothing at inference)
class ResBlockTV(nn.Module):
    def __init__(self, channels, drop_prob):
        super().__init__()
        self.f = nn.Sequential(
            nn.Conv2d(channels, channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(channels, channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(channels),
        )
        # mode="batch": decide once for the whole mini-batch (same as the paper)
        # mode="row"  : decide per sample (same as timm's DropPath)
        self.drop_path = StochasticDepth(p=drop_prob, mode="row")

    def forward(self, x):
        return F.relu(x + self.drop_path(self.f(x)))  # apply only to the residual branch; leave the shortcut alone


block = ResBlockTV(16, drop_prob=1 - probs[-1])  # the paper's survival probability 0.5 is a drop probability of 0.5
block.train()
out = block(x)
block.eval()
out = block(x)

FAQ

Q. Are DropPath and Stochastic Depth the same thing?
A.

In today's libraries (timm's DropPath and torchvision's StochasticDepth), both refer to the same operation: randomly dropping a residual block's transformation and passing only the identity shortcut. However, FractalNet's drop-path, from which the name DropPath comes, is a method that drops paths into the join points of a fractal structure, and it is different from Stochastic Depth. Also, timm's DropPath drops per sample, which is a different unit from the paper's per-mini-batch method.

Q. How should the survival probability (drop probability) be chosen?
A.

In all experiments, the paper set the last block's survival probability to p_L = 0.5 and decreased it linearly from the input side. For the 110-layer network on CIFAR-10, results were stable for p_L between 0.4 and 0.8. For shallow networks, less skipping (a larger p_L) gave better results. For Vision Transformers, small values such as DeiT's drop probability of about 0.1 are also used.

Q. Don't I need to multiply the output by p at inference?
A.

Not if you use a library implementation. torchvision and timm multiply the output of kept blocks by 1/(1 − drop probability) during training and do nothing at inference. As with the paper's Equation 5 (multiply by p at inference), this matches the average output between training and inference. Multiply by p at inference only if you implement the paper's version yourself.

References

  1. G. Huang, Y. Sun, Z. Liu, D. Sedra, and K. Q. Weinberger, "Deep Networks with Stochastic Depth," ECCV, 2016.
  2. G. Larsson, M. Maire, and G. Shakhnarovich, "FractalNet: Ultra-Deep Neural Networks without Residuals," ICLR, 2017.
  3. H. Touvron, M. Cord, M. Douze, F. Massa, A. Sablayrolles, and H. Jégou, "Training data-efficient image transformers & distillation through attention," ICML, 2021.
  4. D. Krueger et al., "Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations," ICLR, 2017.
  5. PyTorch Documentation, "torchvision.ops.StochasticDepth."
  6. R. Wightman, "PyTorch Image Models (timm): timm/layers/drop.py."