Sub topic 10
Mixing samples: mixup and CutMix
This chapter assumes you can write a PyTorch training loop, you know cross-entropy loss, and you have already built a per-image augmentation pipeline (flips, crops, color changes). Mixing methods differ from those transforms. They operate on a batch, not on a single image, and they change the label as well as the pixels.
Why mix samples at all
Per-image transforms keep one image and one hard label. A model can still become overconfident on the training set, predicting probability near 1.0 for every example. Mixing methods attack this directly. They build a new training example from two real ones and give it a soft label that reflects the blend.
Two effects follow:
- The model sees inputs that lie between classes, so decision boundaries are encouraged to change linearly between training examples instead of jumping sharply.
- The targets are no longer one-hot, so the loss cannot be driven to zero by extreme logits. This acts like label smoothing, and it usually improves calibration.
The cost is that mixed images are not natural images. Mixing is a regularizer, so it helps most when the model is large relative to the data or training runs for many epochs. It can hurt on short schedules or small models that are already underfitting.
Mixup
Mixup takes two examples (x_i, y_i) and (x_j, y_j) and forms:
x = λ · x_i + (1 − λ) · x_jy = λ · y_i + (1 − λ) · y_j
The weight λ is drawn from a Beta distribution, λ ~ Beta(α, α), with a single hyperparameter α.
| α | Shape of Beta(α, α) | Typical effect |
|---|---|---|
| 0.1 to 0.2 | U-shaped, most draws near 0 or 1 | Mild: most mixed images look almost like one source |
| 1.0 | Uniform on [0, 1] | Strong: every blend ratio is equally likely |
| Greater than 1 | Peaked near 0.5 | Very strong: most images are close to a 50/50 blend |
The partner for each image is found cheaply. Instead of sampling pairs from the dataset, you shuffle the current batch with torch.randperm and pair each image with its shuffled counterpart. This needs no extra data loading.
Because cross-entropy is linear in the target, mixing the labels is equivalent to mixing the two losses with the same weights. That is why the code below never builds a soft label vector.
import torch
import torch.nn.functional as F
def mixup_step(model, x, y, alpha=0.2):
lam = torch.distributions.Beta(alpha, alpha).sample().item()
perm = torch.randperm(x.size(0), device=x.device)
x_mixed = lam * x + (1 - lam) * x[perm]
logits = model(x_mixed)
loss = lam * F.cross_entropy(logits, y) + (1 - lam) * F.cross_entropy(logits, y[perm])
return lossA few details matter here:
- One
λis shared by the whole batch. This is the common implementation and it is cheap. Per-sampleλis possible but needs a broadcast shape such aslam.view(-1, 1, 1, 1). - Mixing happens after normalization, on tensors. A blend of normalized images is still a linear blend, so the order of normalization and mixing does not change the result.
- Mixing should be skipped for evaluation. Validation batches use the clean, deterministic pipeline and the ordinary loss.
CutMix
Mixup blends every pixel, which produces ghostly overlays. CutMix instead cuts a rectangle from one image and pastes it into another. The label is mixed in proportion to the area each source contributes.
The steps for one batch:
- Draw
λ ~ Beta(α, α). - Compute a box whose area is
(1 − λ)of the image: widthW · sqrt(1 − λ)and heightH · sqrt(1 − λ). - Pick the box center uniformly at random. Clip the box to the image borders.
- Paste that region from the shuffled batch into the original batch.
- Recompute
λas the exact fraction of pixels that remain from the original image, because clipping shrinks the box.
Step 5 is the part most often forgotten. If the box is clipped at a border, the nominal λ no longer matches the real area, and the label weights become wrong.
import numpy as np
import torch
import torch.nn.functional as F
def rand_bbox(h, w, lam, rng):
cut_ratio = np.sqrt(1.0 - lam)
cut_h, cut_w = int(h * cut_ratio), int(w * cut_ratio)
cy, cx = rng.integers(0, h), rng.integers(0, w)
y1, y2 = np.clip(cy - cut_h // 2, 0, h), np.clip(cy + cut_h // 2, 0, h)
x1, x2 = np.clip(cx - cut_w // 2, 0, w), np.clip(cx + cut_w // 2, 0, w)
return y1, y2, x1, x2
def cutmix_step(model, x, y, alpha=1.0, rng=None):
rng = rng or np.random.default_rng()
lam = float(rng.beta(alpha, alpha))
perm = torch.randperm(x.size(0), device=x.device)
h, w = x.shape[2], x.shape[3]
y1, y2, x1, x2 = rand_bbox(h, w, lam, rng)
x = x.clone()
x[:, :, y1:y2, x1:x2] = x[perm][:, :, y1:y2, x1:x2]
lam = 1.0 - ((y2 - y1) * (x2 - x1)) / (h * w) # exact kept area
logits = model(x)
return lam * F.cross_entropy(logits, y) + (1 - lam) * F.cross_entropy(logits, y[perm])The clone matters. x[perm] creates a copy by advanced indexing, but assigning into x in place would change the input tensor that the caller still holds. Cloning keeps the function free of side effects.
Mixup versus CutMix
| Property | Mixup | CutMix |
|---|---|---|
| Pixel content | Every pixel is a blend | Pixels come from exactly one source |
| Local texture | Washed out | Preserved inside each region |
| Label weight | λ from the Beta draw | Area fraction after clipping |
| Typical α | 0.1 to 0.4 | 1.0 |
| Useful for localization | Weak | Stronger, since the model must classify from partial views |
| Risk | Unnatural overlays, lower accuracy on short runs | The pasted patch may hide the object, so the label is noisy |
CutMix also resembles the occlusion transforms from earlier in this tutorial. Cutout fills a region with a constant, while CutMix fills it with real content from another class. The model has to use evidence from several parts of the image, which is why CutMix often helps detection and localization backbones.
A common recipe applies one of the two on each batch, chosen at random (for example with probability 0.5 each), and sometimes applies neither. Torchvision provides transforms.v2.MixUp and transforms.v2.CutMix, which expect one-hot or integer labels and return soft labels, so you apply them after batching, typically in a collate_fn.
import torch
from torch.utils.data import default_collate
from torchvision.transforms import v2
NUM_CLASSES = 100
mix = v2.RandomChoice([
v2.MixUp(alpha=0.2, num_classes=NUM_CLASSES),
v2.CutMix(alpha=1.0, num_classes=NUM_CLASSES),
])
def collate_mixed(batch):
return mix(*default_collate(batch))
# loader = torch.utils.data.DataLoader(train_ds, batch_size=64, collate_fn=collate_mixed)
# images, soft_targets = next(iter(loader))
# loss = torch.nn.functional.cross_entropy(model(images), soft_targets)With soft targets of shape (N, num_classes), F.cross_entropy accepts class probabilities directly, so you do not need the two-term loss.
Edge cases and failure modes
- Metrics on mixed batches. Training accuracy computed against the dominant label is only an approximation. Judge progress with validation accuracy on clean images, not training accuracy.
- Batch size 1 or tiny batches. The shuffled partner may be the image itself, so nothing is actually mixed. Small batches also give noisy mixing.
- Same-class partners. With few classes, a partner often shares the label. The result is a harmless but useless sample. This is normal and does not need handling.
- Dense tasks. For segmentation and detection, mixing labels is not a single weighted loss. CutMix can paste masks and boxes along with pixels, but mixup needs task-specific handling. Do not apply classification mixing code to these tasks unchanged.
- Batch normalization. Mixed images shift activation statistics slightly. This is normally fine. It becomes a concern only when you fine-tune with very small batches or evaluate with statistics from heavily mixed data.
- Label-sensitive domains. If a small region carries the label, such as a tiny lesion in a medical image, CutMix may paste over it or paste in a patch that contains none of it. The soft label then misstates the content. Prefer milder settings, or skip mixing.
- Strong stacking. Combining RandAugment, random erasing, mixup, and CutMix at full strength often underfits. Increase one at a time and measure.
Where it fits in the pipeline
Tuning
Start without mixing to get a baseline. Then add one method and sweep α over a small set, such as 0.1, 0.2, and 0.4 for mixup, and 0.5 and 1.0 for CutMix. Compare validation accuracy and, if you care about probability quality, validation loss or expected calibration error. Mixing generally needs longer training to pay off, so compare at the same epoch count that you plan to use for the final run, not a shortened one.
Exercise
In your CutMix implementation, a box centered near the top-left corner is clipped by the image border, and only 5 percent of the image area is actually pasted. The Beta draw gave λ = 0.7, so the nominal pasted area was 30 percent. Which weights should you use in the loss, and why?
Show answer
Use 0.95 for the original image's label and 0.05 for the partner's label. Clipping removed part of the box, so the nominal λ no longer describes the image. You must recompute λ as the fraction of pixels that still come from the original image, which is 1 minus the pasted area fraction. Using 0.7 and 0.3 would tell the model that 30 percent of the image belongs to the partner class when only 5 percent does.
Exercise
A teammate applies mixup to the validation loader "to keep training and validation consistent" and reports a lower validation accuracy. What is wrong, and what should the validation pipeline do instead?
Show answer
Mixing is a training-time regularizer and it changes both inputs and labels, so validation images become blends and the accuracy no longer measures performance on real images. The validation loader should use only the deterministic evaluation transforms (resize, center crop, normalize) with hard labels and the ordinary cross-entropy loss, so results are reproducible and comparable between runs.