AI Logic

Regularization

Shake-Shake

Updated:

Three views of a Shake-Shake residual block. On the left, the training forward pass multiplies the outputs of the two branches (ReLU, 3×3 convolution, and BN, twice) by α and 1 − α and adds them to the input. In the middle, the training backward pass splits the gradient from above between the two branches with a separate random number, β and 1 − β, and passes it down. On the right, at inference, both branches are multiplied by 0.5

Background and Overview

Shake-Shake is a regularization method that, in a residual block with two branches, mixes the branch outputs in a random ratio and, in the backward pass, redistributes the gradient with a different random number. Xavier Gastaldi proposed it in 2017, and it set new records among published single models at the time, with error rates of 2.86% on CIFAR-10 and 15.85% on CIFAR-100.

Residual networks such as ResNet are powerful, but they overfit on small datasets. Dropout used to be the standard way to curb overfitting, but once batch normalization spread, Dropout became less effective. This led to regularization methods that exploit the structure of multi-branch networks, such as Stochastic Depth, which randomly drops entire residual blocks.

Shake-Shake starts from this idea: "Data augmentation has only been applied to input images, but to a computer there is no difference between an input image and an intermediate representation. It should be possible to apply augmentation-like perturbations to intermediate representations as well." So, in a residual block with two branches like those of ResNeXt, it randomly mixes the outputs of the two branches. Because it scales a branch down rather than zeroing it out, the paper also positions Shake-Shake as a kind of drop-path, which drops branches.

ShakeDrop builds on this method and extends it to single-branch ResNets.

Theory (Forward, Backward, and Inference)

The explanation follows Equations (1) and (2) and Section 1.3 of the original paper. Let xi\boldsymbol{x}_i be the input to residual block ii, F\mathcal{F} the branch function (in the paper, ReLU, 3×3 convolution, and batch normalization repeated twice), and Wi(1),Wi(2)\boldsymbol{W}_i^{(1)}, \boldsymbol{W}_i^{(2)} the weights of the two branches.

  1. The starting point is a residual block that simply adds the outputs of the two branches. xi+1=xi+F(xi,Wi(1))+F(xi,Wi(2))\boldsymbol{x}_{i+1} = \boldsymbol{x}_i + \mathcal{F}(\boldsymbol{x}_i, \boldsymbol{W}_i^{(1)}) + \mathcal{F}(\boldsymbol{x}_i, \boldsymbol{W}_i^{(2)})
  2. Before the training forward pass, αi\alpha_i is drawn from the uniform distribution on 0 to 1, and the two branches are mixed in the ratio αi:1−αi\alpha_i : 1-\alpha_i. αi∼U(0,1),xi+1=xi+αi F(xi,Wi(1))+(1−αi) F(xi,Wi(2))\alpha_i \sim \mathcal{U}(0, 1), \qquad \boldsymbol{x}_{i+1} = \boldsymbol{x}_i + \alpha_i\,\mathcal{F}(\boldsymbol{x}_i, \boldsymbol{W}_i^{(1)}) + (1-\alpha_i)\,\mathcal{F}(\boldsymbol{x}_i, \boldsymbol{W}_i^{(2)})
  3. Before the training backward pass, the coefficient is redrawn as a new random number βi\beta_i. Branch 1 receives βi\beta_i times the gradient from above, and branch 2 receives 1−βi1-\beta_i times it (LL is the loss). βi∼U(0,1),∂L∂F(1)=βi ∂L∂xi+1,∂L∂F(2)=(1−βi) ∂L∂xi+1\beta_i \sim \mathcal{U}(0, 1), \qquad \frac{\partial L}{\partial \mathcal{F}^{(1)}} = \beta_i\,\frac{\partial L}{\partial \boldsymbol{x}_{i+1}}, \qquad \frac{\partial L}{\partial \mathcal{F}^{(2)}} = (1-\beta_i)\,\frac{\partial L}{\partial \boldsymbol{x}_{i+1}}
  4. Steps 2 and 3 repeat, with fresh random numbers for every forward and backward pass.
  5. At inference, following the same idea as Dropout, the coefficient is fixed at its expected value of 0.5. xi+1=xi+0.5 F(xi,Wi(1))+0.5 F(xi,Wi(2))\boldsymbol{x}_{i+1} = \boldsymbol{x}_i + 0.5\,\mathcal{F}(\boldsymbol{x}_i, \boldsymbol{W}_i^{(1)}) + 0.5\,\mathcal{F}(\boldsymbol{x}_i, \boldsymbol{W}_i^{(2)})

With ordinary backpropagation, a branch scaled by αi\alpha_i in the forward pass also receives a gradient scaled by αi\alpha_i in the backward pass. Shake-Shake deliberately uses a different random number here, perturbing the gradient that flows into a branch to βi/αi\beta_i/\alpha_i times its correct value (and (1−βi)/(1−αi)(1-\beta_i)/(1-\alpha_i) times for the other branch). This is why the coefficients differ between the left (forward) and middle (backward) panels of the figure above.

The paper compares combinations of how the forward and backward coefficients are chosen and the unit at which random numbers are drawn, using the following names.

NameMeaning
ShakeDraw a new random number
EvenFix at 0.5
KeepUse the same coefficient in the backward pass as in the forward pass
BatchUse the same coefficient for every image in the mini-batch
ImageUse a different coefficient for each image

For example, "Shake-Shake-Image" means drawing new random numbers for both the forward and backward passes, per image. The method's name comes from this combination of Shake in both the forward and backward passes.

Shake-Shake multiplies the entire tensor by a single scalar αi\alpha_i (or 1−αi1-\alpha_i). Unlike Dropout, it does not apply a separate random number to each element. Even when drawing per image (Image), the whole feature map of one image is multiplied by the same coefficient.

Why It Works

The paper and the ShakeDrop paper, which analyzes Shake-Shake, explain why it works from the following three angles.

  • Augmenting intermediate representations: Mixing the outputs of the two branches in a random ratio during the forward pass produces a slightly different intermediate representation each time. Drawing on earlier work showing that interpolating between two examples in feature space yields plausible augmented data, the ShakeDrop paper interprets this as "data augmentation in feature space."
  • Perturbing the gradient: Using a different random number in the backward pass adds noise to the gradient. The paper cites earlier work showing that adding noise to gradients improves generalization, and regards Shake-Shake as "gradient augmentation." The ShakeDrop paper explains that this perturbation keeps the parameters from getting trapped in local minima.
  • The two branches learn different things: In Section 3 of the paper, the correlation between the outputs of the two branches on test data was lower for models trained with Shake-Shake. Because the mixing ratio changes every time, the network cannot rely on just one branch, and each branch appears to learn different useful features.

As an analogy, picture a two-person job where the share of the work is decided by lottery each time, and how much of the credit goes back to each person is decided by a separate lottery. The pair never settles into relying on one person, and both develop skills that are useful on their own.

Experiments also show that the backward-pass random number matters. "Shake-Keep," which perturbs only the forward pass and uses the same coefficient in the backward pass, barely improved the error rate (table below). The paper suggests that when updates use the same ratio as the forward pass, the network can see through the perturbation.

The strength of the regularization can be adjusted by how far βi\beta_i is from αi\alpha_i (Section 4 of the paper). The farther βi\beta_i is from αi\alpha_i, the stronger the effect, and it became sharply stronger once it crossed 0.5 to the other side. With βi=1−αi\beta_i = 1-\alpha_i, the regularization was too strong and the training error stayed high.

Experimental Results

CIFAR-10 results from the original paper (Table 1: a 26-layer, two-branch ResNet; "32d" and so on are the number of channels in the first residual block; values are averages over 3 runs, except 96d, which averages 5). Values are error rates (%, lower is better).

ForwardBackwardUnit32d64d96d
EvenEven—4.273.763.58
ShakeKeepImage4.09——
ShakeEvenImage3.473.20—
ShakeShakeBatch3.673.07—
ShakeShakeImage3.552.982.86
  • Effect of perturbation: Compared with Even-Even (both fixed at 0.5, no perturbation), Shake-Shake-Image lowered the error from 3.58% to 2.86% at 96d.
  • Shake-Shake gains more in larger models: At 32d, Shake-Even and Shake-Shake are nearly equal, but at 64d Shake-Shake pulls ahead.
  • Per-image draws are better: For the same combination, Image gave lower error rates than Batch.

On CIFAR-100, with a two-branch ResNeXt-29 (2×4×64d), Even-Even scored 16.34%, Shake-Even-Image 15.85% (average of 3 runs), and Shake-Shake-Image 15.97% (1 run). The 2.86% of the 26-layer, 96d model on CIFAR-10 (26.2M parameters) is lower than the 3.46% of DenseNet-BC (25.6M parameters).

These experiments train on CIFAR for a long 1800 epochs (with the learning rate decayed from 0.2 by cosine annealing).

Practical Considerations

The number of training epochs grows substantially. Because the random perturbations are strong, the original paper trains every model for 1800 epochs. The ShakeDrop paper also recommends training Shake-Shake for 6 times the usual length. When the compute budget is limited, estimate this cost up front.

  • Requires two or more branches: Because the method mixes two branches, it does not apply as-is to single-branch ResNets. Use ShakeDrop in that case.
  • Weaken to Shake-Even when it is too strong: In a small model with the skip connections removed, Shake-Shake-Image was too strong and caused underfitting, while Shake-Even-Image, which fixes the backward coefficient at 0.5, did better.
  • No effect with a single convolution per branch: With only one ReLU-convolution-batch-normalization set inside each branch, the regularization had no effect. The paper suggests that the interplay between the two convolutions inside a branch contributes to the effect.
  • Prone to divergence without batch normalization: Without batch normalization, training only worked after narrowing the range of αi\alpha_i to [0.4,0.6][0.4, 0.6], and it diverged at [0.3,0.7][0.3, 0.7].
  • Sensitive to batch size: On CIFAR-100, even the baseline models did not do well unless the batch size was lowered from 128 to 32. Small batch sizes have a regularizing effect of their own, so tune the batch size together with the combination.
  • Fix the coefficient at 0.5 at inference: In PyTorch, implement it so that model.eval() switches the behavior (see the code example below).

Comparison with Other Methods

The table compares regularizers that apply random numbers to residual blocks or layers, by where the random numbers are applied and whether the forward and backward passes use the same random number.

MethodWhere randomness is appliedValue appliedBackward random numberApplicable architectures
DropoutUnits (per element)0 or 1Same as forwardAny layer
Stochastic DepthResidual block branch (entire)0 or 1Same as forwardResidual networks
Shake-ShakeMixing ratio of two branchesα\alpha and 1−α1-\alphaSeparate random number β\betaTwo or more branches (ResNeXt, etc.)
ShakeDropOutput of a single branchbl+α−blαb_l + \alpha - b_l\alphaSeparate random number β\betaResNet, PyramidNet, ResNeXt
  • For two-branch architectures with a budget for long training, Shake-Shake provides strong regularization.
  • For single-branch ResNet or PyramidNet, choose ShakeDrop. In the ShakeDrop paper, ShakeDrop often achieved lower error rates even on two-branch ResNeXt.
  • When training length must not grow, Stochastic Depth, which also speeds up training, is a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class ShakeShakeFunction(torch.autograd.Function):
    """Mix two branches with α in the forward pass and a separate random β in the backward pass (drawn per image: Image)"""

    @staticmethod
    def forward(ctx, x1, x2, training):
        if training:
            # One α ~ U(0, 1) per image, applied to the whole feature map
            alpha = torch.rand(x1.size(0), 1, 1, 1, device=x1.device, dtype=x1.dtype)
        else:
            alpha = torch.full((x1.size(0), 1, 1, 1), 0.5, device=x1.device, dtype=x1.dtype)
        return alpha * x1 + (1 - alpha) * x2

    @staticmethod
    def backward(ctx, grad_output):
        # Before the backward pass, redraw a random β separate from α (the key to Shake-Shake)
        beta = torch.rand(grad_output.size(0), 1, 1, 1,
                          device=grad_output.device, dtype=grad_output.dtype)
        return beta * grad_output, (1 - beta) * grad_output, None


def residual_branch(channels):
    # The paper's branch: ReLU - Conv3x3 - BN - ReLU - Conv3x3 - BN
    return nn.Sequential(
        nn.ReLU(),
        nn.Conv2d(channels, channels, 3, padding=1, bias=False),
        nn.BatchNorm2d(channels),
        nn.ReLU(),
        nn.Conv2d(channels, channels, 3, padding=1, bias=False),
        nn.BatchNorm2d(channels),
    )


class ShakeShakeBlock(nn.Module):
    """x_{i+1} = x_i + α F(x_i, W1) + (1 − α) F(x_i, W2) (a block that keeps the channel count and size)"""

    def __init__(self, channels):
        super().__init__()
        self.branch1 = residual_branch(channels)
        self.branch2 = residual_branch(channels)

    def forward(self, x):
        mixed = ShakeShakeFunction.apply(self.branch1(x), self.branch2(x), self.training)
        return x + mixed


block = ShakeShakeBlock(channels=32)
x = torch.randn(8, 32, 16, 16)

block.train()            # training: α in the forward pass, β in the backward pass
y = block(x)
y.sum().backward()

block.eval()             # inference: α fixed at 0.5 (same output every time)
with torch.no_grad():
    y1, y2 = block(x), block(x)
print(torch.allclose(y1, y2))  # True

FAQ

Q. Which should I use, Shake-Shake or Shake-Even?
A.

On CIFAR-10 in the paper, Shake-Shake-Image gave the best results for larger models widened to 64d or 96d channels. On the other hand, on CIFAR-100 (batch size 32) and in a small model with the skip connections removed, Shake-Even-Image, which fixes the backward coefficient at 0.5, did better. Try Shake-Shake-Image first, and weaken it to Shake-Even-Image if the training error stays high and the model looks underfit.

Q. Can it be used with an ordinary single-branch ResNet?
A.

Not as-is, because the method mixes the outputs of two branches. Applying random numbers the same way to a single branch (Single-branch Shake) was tested in the ShakeDrop paper and failed to train, with an error rate of 77.99% for PyramidNet on CIFAR-100. For single-branch networks, use ShakeDrop, which solves this problem.

Q. Should the coefficients be drawn per mini-batch or per image?
A.

Per image (Image) is recommended. In Table 1 of the paper, for the same combination, drawing per image gave lower error rates than using one coefficient for the whole mini-batch (Batch). In code, give the coefficient the shape (batch size, 1, 1, 1) and multiply each image's entire feature map by one value.

References

  1. X. Gastaldi, "Shake-Shake regularization," arXiv:1705.07485, 2017.
  2. X. Gastaldi, "shake-shake" (the paper's implementation, GitHub).
  3. Y. Yamada, M. Iwamura, T. Akiba, and K. Kise, "ShakeDrop Regularization for Deep Residual Learning," IEEE Access, 2019.
  4. G. Huang, Y. Sun, Z. Liu, D. Sedra, and K. Q. Weinberger, "Deep Networks with Stochastic Depth," ECCV, 2016.
  5. G. Larsson, M. Maire, and G. Shakhnarovich, "FractalNet: Ultra-Deep Neural Networks without Residuals," ICLR, 2017.