AI Logic

Regularization

Manifold Mixup

Updated:

Manifold Mixup. Left: one training step (shuffle the mini-batch, sample the mixing layer k and λ, forward to layer k, mix hidden representations and labels, forward from layer k to the output, compute the loss, update all layers). Right: an example with λ = 0.7 and k = 1, showing inputs x and x′ passed through the same-weight first part g_k, their hidden representations mixed and passed through the second part f_k, a bar chart of the labels mixed with the same λ, and the candidate mixing layers (input, outputs of the 1st and 2nd residual blocks)

Background and overview

Manifold Mixup is a regularization method that mixes the hidden representations (intermediate features) of two examples at an intermediate layer of the network, and mixes their labels in the same proportion. It extends Mixup, which mixes inputs, to hidden layers. It was presented at ICML 2019 by Verma et al.

The paper points out two weaknesses of conventionally trained neural networks.

  • Decision boundaries lie close to the data and are sharp: Predictions easily switch to another class with only a small shift from the training data.
  • High confidence across most of the hidden representation space: Even in regions between training examples where there is no data, the network predicts with nearly 100% confidence.

Manifold Mixup trains the network to output "an unconfident prediction matching the mixing ratio" for points obtained by mixing two examples in a hidden layer. As a result, confidence drops in the regions between data, and decision boundaries become smooth and move away from the data. It has also been shown that hidden representations of the same class concentrate along fewer directions (become flatter).

The extra computation is only additions and a shuffle, so it can be implemented in a few lines. In the paper's experiments, both the image classification error rate and the reliability of predicted probabilities (test negative log-likelihood) improved over Mixup.

Theory (procedure and equations)

The original Mixup mixes the inputs and the labels of two examples in the same proportion λ\lambda. The following figure shows the training flow and mixing of Mixup.

Mixup. Left: the training flow. Right: an example of mixing two images and their labels with λ = 0.7, and the distribution of λ

Manifold Mixup performs this mixing at an intermediate layer instead of the input. The explanation follows Section 2 of the paper. The network is viewed as f(x)=fk(gk(x))f(x) = f_k(g_k(x)), split into the first part gkg_k up to layer kk and the second part fkf_k from layer kk to the output.

  1. Choose the mixing layer kk at random from a predefined set of candidate layers SS. SS may include the input (k=0k = 0).
  2. Pass two mini-batches (x,y)(x, y) and (x′,y′)(x', y') normally up to layer kk to obtain hidden representations gk(x)g_k(x) and gk(x′)g_k(x').
  3. Mix the hidden representations and the (one-hot) labels with the same λ\lambda. As in Mixup, λ\lambda is drawn from Beta(α,α)\mathrm{Beta}(\alpha, \alpha). g~k=Mixλ(gk(x), gk(x′)),y~=Mixλ(y, y′),Mixλ(a,b)=λ a+(1−λ) b\tilde{g}_k = \mathrm{Mix}_\lambda\big(g_k(x),\, g_k(x')\big), \qquad \tilde{y} = \mathrm{Mix}_\lambda(y,\, y'), \qquad \mathrm{Mix}_\lambda(a, b) = \lambda\, a + (1 - \lambda)\, b
  4. Pass the mixed hidden representation g~k\tilde{g}_k from layer kk to the output.
  5. Compute the loss from the output and y~\tilde{y}, and update the weights of all layers, including those before layer kk.

Overall, the following loss is minimized (Eq. (1) in the paper), where ℓ\ell is a loss such as cross-entropy.

L(f)=E(x,y) E(x′,y′) Eλ∼Beta(α,α) Ek∼S  ℓ(fk(Mixλ(gk(x),gk(x′))),  Mixλ(y,y′))L(f) = \mathbb{E}_{(x,y)}\, \mathbb{E}_{(x',y')}\, \mathbb{E}_{\lambda \sim \mathrm{Beta}(\alpha,\alpha)}\, \mathbb{E}_{k \sim S}\; \ell\Big( f_k\big(\mathrm{Mix}_\lambda(g_k(x), g_k(x'))\big),\; \mathrm{Mix}_\lambda(y, y') \Big)

With S={0}S = \{0\}, mixing happens only at the input, which is identical to the original Mixup. In practice, as in Mixup, a shuffled copy of one mini-batch serves as the partner, and a single pair of kk and λ\lambda is drawn per mini-batch. The paper reports that drawing them per example did not change the results.

It is important to let gradients flow into the layers before layer kk as well. In an experiment that blocked gradients from flowing before the mixing layer (CIFAR-10, PreActResNet18), the paper reports an error rate of 4.33%, better than standard training but worse than Mixup and Manifold Mixup. Manifold Mixup works not only on the layers after the mixing point but by changing the representations of the earlier layers themselves.

Why it works (representations become flat)

The paper summarizes the effects of Manifold Mixup in three points.

  • Decision boundaries become smoother and move away from the data: Since intermediate predictions are required at mixed points, predictions no longer switch abruptly between data points.
  • Deeper-layer information adds training signal: Hidden representations in deep layers capture high-level information such as object shape and category. Mixing there creates more meaningful intermediate examples than mixing input pixels.
  • Per-class representations become flat: Hidden representations of the same class are organized so that they spread along only a few directions.

On the third point, the paper explains as follows. At a position obtained by mixing two points, different targets may be required depending on the pair: for one pair (A1 and B2) "50% red, 50% blue," and for another pair (A2 and B1) "95% blue, 5% red." In Manifold Mixup the hidden representations themselves also move during training, so the representations of each class are pushed to line up flat so that predictions do not conflict no matter which pairs are mixed.

Under idealized conditions (a sufficiently large network), the paper shows that the loss can be driven to 0 if the hidden layer dimension dim⁡(H)\dim(H) satisfies dim⁡(H)≥d−1\dim(H) \ge d - 1 for dd classes (Theorem 1). In that case, the hidden representations of each class's training data lie in a subspace of dimension dim⁡(H)−d+1\dim(H) - d + 1 (Corollary 1). In other words, the number of directions used by the representations decreases.

This "flattening" has also been confirmed in real networks. The table shows the singular value decomposition of the per-class representations in the first hidden layer of a fully connected network trained on MNIST.

RegularizationLargest singular valueSum of the remaining singular values
None51.7378.67
Weight Decay33.7673.36
Dropout28.8377.47
Mixup (input)33.4666.89
Manifold Mixup31.6540.98

Other regularization methods lower the largest singular value but barely lower the sum of the rest. Only Manifold Mixup substantially lowers the remaining sum, showing that the representations hardly spread beyond the main directions. Because the volume occupied by the representations shrinks, points that fall in the regions between them are more likely to receive unconfident predictions.

Experimental results

Results from Tables 1 and 2 of the paper (test error rate, %). Mixup uses α=1\alpha = 1 and Manifold Mixup uses α=2\alpha = 2, with the candidate mixing layers being the input and the outputs of the 1st and 2nd residual blocks (for Wide-ResNet, the input and the output of the 1st residual block).

DataModelNoneMixupManifold Mixup
CIFAR-10PreActResNet184.833.822.95
CIFAR-10Wide-ResNet-28-103.992.922.55
CIFAR-100PreActResNet1824.0122.1120.34
CIFAR-100Wide-ResNet-28-1021.7218.8918.04
SVHNPreActResNet182.892.762.27
  • Error rate: Lower than Mixup on every dataset and model.
  • Reliability of probabilities: The test negative log-likelihood (lower is better) for PreActResNet18 on CIFAR-10 dropped from 0.190 (none) to 0.137. The paper reports improvements of up to 50% on CIFAR-10.
  • Comparison with other regularization: In a comparison training PreActResNet50 on CIFAR-10 for 600 epochs with settings chosen on validation data, the error rates were 4.96 for none, 5.09 for Dropout, 4.77 for Cutout, 4.25 for Mixup, and 3.77 for Manifold Mixup.
  • Robustness to unseen deformations: When trained on CIFAR-100 and tested on images rotated within −20 to 20 degrees, accuracy was 52.96% for none, 55.55% for Mixup (α=1\alpha = 1), and 60.08% for Manifold Mixup.
  • Robustness to single-step adversarial examples: On CIFAR-10, accuracy on adversarial examples generated with FGSM was 36.32% for none, 71.51% for Mixup, and 77.50% for Manifold Mixup.

Practical considerations

It does not provide robustness against strong attacks. The paper reports that while Manifold Mixup becomes robust to FGSM, which is computed in a single step, it barely improves robustness against strong attacks built through many iterations, such as PGD. This is because it offers no protection against perturbations in directions other than the mixing direction (the line connecting two examples). If robustness to adversarial attacks is needed, use adversarial training.

  • α\alpha depends on the data: On CIFAR-10, any α\alpha from 0.5 to 2.0 gave accuracy equal to or better than Mixup, with α=2.0\alpha = 2.0 performing best (Table 6). On Tiny ImageNet, however, α=0.2\alpha = 0.2 was best with a top-1 accuracy of 58.70%, while α=2.0\alpha = 2.0 gave 48.14%, worse than none (55.52%) (Table 3). On new data, also try smaller values such as 0.2.
  • Do not mix at layers that are too deep: For PreActResNet18 on CIFAR-10, accuracy was best at 97.23% when the candidate set SS was "input, outputs of the 1st and 2nd residual blocks," 96.73% with the input only (same as Mixup), and 95.19% with only the output of the 2nd block (Table 5). Use the input plus shallow-to-middle layers as candidates.
  • The paper's results come from long training: The experiments in Table 1 train for 1200 epochs, and the comparison with other regularization for 600 epochs. Whether the same effect appears with short training was not verified in the paper.
  • Rebalance the strength of other regularization: The paper's experiments train with SGD with momentum, a learning rate of 0.1, and Weight Decay of 10−410^{-4}. Since it acts as regularization just like Mixup, retune the strength of other regularization such as Weight Decay on validation data.
  • Mix only during training: At inference, pass the original input through the network as is.

Comparison with other methods

Manifold Mixup and methods it is often compared with, from the same perspectives.

MethodWhat is modifiedLabelsImplementation effort
MixupInput (mix two examples)Mixed in the same proportionA few lines after data loading
Manifold MixupHidden layer (mix the hidden representations of two examples)Mixed in the same proportionRewrite the model's forward pass
CutMixInput (paste a rectangular region from another image)Mixed by the pasted area ratioA few lines after data loading
DropoutHidden layer (drop units)UnchangedJust add a layer
Label SmoothingLabels (lower the correct class slightly)Spread slightly over all classesJust change a loss argument
  • Already using Mixup and want a further gain: Try Manifold Mixup. In the paper's experiments, it lowered the error rate below Mixup on every dataset. Setting S={0}S = \{0\} reproduces Mixup, so both can be compared with the same implementation.
  • Cannot modify the model internals: When the forward pass is hard to rewrite, such as when using a pretrained model as a component, use Mixup or CutMix, which only need the input.
  • Comparing as hidden-layer regularization: Dropout and Manifold Mixup both modify hidden layers. In the paper's comparison (PreActResNet50, CIFAR-10), Dropout did not lower the error rate, while Manifold Mixup did.

PyTorch example

Show code
python
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F


class ManifoldMixupNet(nn.Module):
    """A network of stacked blocks. During training, pick k from the candidate layers S and mix at the output of layer k"""

    def __init__(self, num_classes=10):
        super().__init__()
        self.blocks = nn.ModuleList([
            nn.Sequential(nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU()),
            nn.Sequential(nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU()),
            nn.Sequential(nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU()),
        ])
        self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, num_classes))
        self.num_classes = num_classes

    def forward(self, x, y=None, alpha=2.0, eligible=(0, 1, 2)):
        if y is None:                                   # Inference: no mixing
            for block in self.blocks:
                x = block(x)
            return self.head(x)

        k = random.choice(eligible)                     # 1. Choose the mixing layer k (0 is the input = Mixup)
        lam = float(np.random.beta(alpha, alpha))       # λ ~ Beta(α, α)
        index = torch.randperm(x.size(0), device=x.device)  # Use a shuffled copy as the partner
        y = F.one_hot(y, self.num_classes).float()

        h = x
        if k == 0:
            h, y = lam * h + (1 - lam) * h[index], lam * y + (1 - lam) * y[index]
        for i, block in enumerate(self.blocks, start=1):
            h = block(h)                                # 2. Forward up to layer k
            if i == k:                                  # 3. Mix hidden representations and labels with the same λ
                h, y = lam * h + (1 - lam) * h[index], lam * y + (1 - lam) * y[index]
        return self.head(h), y                          # 4. Forward through the remaining layers


model = ManifoldMixupNet()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)

x = torch.randn(32, 3, 32, 32)                          # Dummy mini-batch (CIFAR-like)
y = torch.randint(0, 10, (32,))

# Training: cross-entropy with the mixed label ỹ (5. gradients flow to all layers)
model.train()
logits, y_mix = model(x, y, alpha=2.0, eligible=(0, 1, 2))
loss = -(y_mix * F.log_softmax(logits, dim=-1)).sum(dim=-1).mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()

# Inference: forward as is without mixing
model.eval()
with torch.no_grad():
    pred = model(x).argmax(dim=-1)

FAQ

Q. How does it differ from Mixup?
A.

The place where mixing happens differs. Mixup mixes inputs (such as image pixels), while Manifold Mixup mixes hidden representations at intermediate layers of the network. Both mix the labels in the same proportion. If the only candidate mixing layer is the input, Manifold Mixup is identical to Mixup.

Q. Which layers should be used for mixing?
A.

For PreActResNet in the paper, the candidates were the input and the outputs of the 1st and 2nd residual blocks, and one was chosen at random per mini-batch. This combination worked best on CIFAR-10, and using only deep layers as candidates actually made results worse. As a guideline, use the input plus shallow-to-middle layers as candidates.

Q. Is mixing also done at inference?
A.

No. Mixing is done only during training; at inference the original input is passed through the network as is. In the code example, no mixing happens when the model is called without labels.

References

  1. V. Verma, A. Lamb, C. Beckham, A. Najafi, I. Mitliagkas, A. Courville, D. Lopez-Paz, and Y. Bengio, "Manifold Mixup: Better Representations by Interpolating Hidden States," ICML, 2019.
  2. H. Zhang, M. Cisse, Y. N. Dauphin, and D. Lopez-Paz, "mixup: Beyond Empirical Risk Minimization," ICLR, 2018.
  3. vikasverma1077/manifold_mixup (code for the paper's experiments)