What it does: A CutMix-style augmentation. It samples a Beta(alpha, alpha) lambda, draws a patch (centered at a random (cx, cy)) whose area scales with sqrt(1-lambda), pastes the corresponding patch from a permuted image, and mixes the labels accordingly (lambda for y and (1-lambda) for permuted y). It returns a dict with input and target.
Strengths:
The patch size is tied to lambda using the classic sqrt(1-lambda) trick.
It recomputes lambda from the actual patch area, which is good when clipping happens at the image boundary.
It uses a random permutation to source the patch, consistent with CutMix.
Issues (most important ones):
Indexing with 0-dim tensors: cx, cy, rh, rw and the derived bbh1/bbh2/bbw1/bbw2 end up as 1-element tensors, which you can’t slice with in Python (e.g., bbh1:bbh2 where bbh1 is a 1-element Tensor). This will raise an error at runtime.
Lambda handling: lambd is a 1-element tensor. If you don’t convert to a Python scalar (or a proper scalar tensor) before using it in Python math or slicing, you’ll hit shape/typing pitfalls. Also, you sample beta with (1,) which yields a 1-element tensor; you should extract a scalar for clean math and indexing.
Per-sample vs batch lambda: The code uses a single lambda for all samples in the batch. This is a valid variant, but most CutMix implementations sample a lambda per image (per-sample lambda) to increase randomness.
Type of y: You’re using one-hot labels and mixing y with y[perm]. If your training loss expects class indices (e.g., CrossEntropyLoss), you’ll need to switch to a distribution-friendly loss (e.g., KLDivLoss on log-probabilities, or BCEWithLogitsLoss with one-hot targets). If you keep using CrossEntropyLoss with integer targets, the current mixing approach won’t line up. Your test uses one-hot as input, but ensure your trainer uses a compatible loss function.
Return type: The forward returns a dict. That’s fine for experimentation but uncommon for a PyTorch Module. Many users return a tuple (X_mix, y_mix) to keep it simple and compatible with typical loss calls.
Small correctness/robustness details: If the patch ends up of zero area (very unlikely with Beta(2,2), but possible if lambda is very close to 1 and you clamp), you’ll still be fine functionally, but lambda recomputation should be consistent with the actual patch area.
A robust, corrected version (per-sample lambda, int indices, and clearer return)
This version fixes the 0-dim indexing issue by turning coordinates into Python ints, samples a lambda per image, and applies per-sample mixing. It keeps the patch semantics but makes the code safer and easier to integrate with standard losses (you can still use one-hot labels and a distribution-based loss, or adapt to cross-entropy with per-sample mixing if you switch loss).
Code option 1: per-sample lambda with simple return (tuple)
python
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
class CutMix(nn.Module):
def __init__(self, alpha: float = 2.0):
super().__init__()
self.alpha = alpha
self.beta = torch.distributions.Beta(alpha, alpha)
def forward(self, X: torch.Tensor, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
# X: [N, C, H, W], y: [N, C] (one-hot) or [N, ...] depending on your loss
N, C, H, W = X.shape
device = X.device
# Permutation for each image
perm = torch.randperm(N, device=device)
X_mix = X.clone()
# If you want per-sample lambda, sample one per image
lam = self.beta.sample((N,)).to(X.dtype).to(X.device) # [N]
# We'll compute per-sample patches
for i in range(N):
lam_i = float(lam[i].item())
cut_h = int(H * math.sqrt(max(0.0, 1.0 - lam_i)))
cut_w = int(W * math.sqrt(max(0.0, 1.0 - lam_i)))
cx = random.randint(0, H - 1)
cy = random.randint(0, W - 1)
h1 = max(cx - cut_h // 2, 0)
h2 = min(cx + cut_h // 2, H)
w1 = max(cy - cut_w // 2, 0)
w2 = min(cy + cut_w // 2, W)
# Copy patch from permuted image
X_mix[i, :, h1:h2, w1:w2] = X[perm[i], :, h1:h2, w1:w2]
# Per-sample lambda for labels
y_mix = torch.zeros_like(y)
for i in range(N):
lam_i = float(lam[i].item())
y_mix[i] = lam_i * y[i] + (1.0 - lam_i) * y[perm[i]]
return X_mix, y_mix
Code option 2: keep batch lambda (less random but simpler)
If you really want a single lambda for all images (as in your original code), you can still fix the indexing issue and be explicit about types:
python
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
class CutMix(nn.Module):
def __init__(self, alpha: float = 2.0):
super().__init__()
self.alpha = alpha
def forward(self, X: torch.Tensor, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
N, C, H, W = X.shape
device = X.device
perm = torch.randperm(N, device=device)
lam = torch.distributions.Beta(self.alpha, self.alpha).sample((1,)).item() # scalar
X_mix = X.clone()
# Single patch for whole batch (as in your code)
cx = int(random.uniform(0, H))
cy = int(random.uniform(0, W))
cut_h = int(H * math.sqrt(max(0.0, 1.0 - lam)))
cut_w = int(W * math.sqrt(max(0.0, 1.0 - lam)))
bbh1 = max(cx - cut_h // 2, 0)
bbh2 = min(cx + cut_h // 2, H)
bbw1 = max(cy - cut_w // 2, 0)
bbw2 = min(cy + cut_w // 2, W)
cut = X[perm, :, bbh1:bbh2, bbw1:bbw2]
X_mix[:, :, bbh1:bbh2, bbw1:bbw2] = cut
# Recompute actual lambda based on the patch size
actual_lam = 1.0 - ((bbh2 - bbh1) * (bbw2 - bbw1)) / (H * W)
y_mix = actual_lam * y + (1.0 - actual_lam) * y[perm]
return X_mix, y_mix
Notes on the two options
If you plan to use standard CrossEntropyLoss with integer targets, you’ll want to switch to a loss that can handle soft targets (e.g., KLDivLoss on log-probabilities, or BCEWithLogitsLoss with one-hot targets). The original CutMix paper effectively uses a per-sample combination of losses, which is equivalent to a soft target approach, but you need the loss to support distributions.
If you want faster training, you might prefer the per-sample lambda approach (Option 1), which tends to produce stronger data augmentation diversity.
If you keep the dict return (as in your snippet), ensure your training loop expects that format, or switch to returning a tuple (X_mix, y_mix) for simpler integration.
A quick sanity test you can run
After fixing indexing, run a tiny test to ensure shapes line up:
python
import torch
import torch.nn.functional as F
N, C, H, W = 4, 3, 16, 16
X = torch.randn(N, C, H, W)
y = torch.randint(0, 10, (N,))
y_onehot = F.one_hot(y, num_classes=10).float()
cutmix = CutMix(alpha=2.0)
X_mix, y_mix = cutmix(X, y_onehot)
print(X_mix.shape) # should be (N, C, H, W)
print(y_mix.shape) # should be (N, num_classes)
Bottom line
The core idea is solid, but the original code as posted has an indexing bug due to 0-dim vs 1-dim tensor slicing, and lambda handling should be explicit (scalar vs per-sample). Also confirm your chosen loss can handle soft targets if you keep one-hot labels.
A clean fix is to convert indices to Python ints for slicing and (optionally) sample lambda per image, returning (X_mix, y_mix) or a dict in a consistent way with your training loop. The provided corrected snippets illustrate both approaches. If you want, I can tailor the fix to your exact loss setup (CrossEntropy vs KLDiv-based loss) and your preference for per-sample vs per-batch lambda.