GridMask is a data augmentation technique that, during training, fills a set of squares arranged at regular intervals in a grid with 0 and trains with the label unchanged. It was proposed by Chen et al. in 2020.
Cutout and Random Erasing erase a single large rectangle. Depending on the rectangle's position and size, this can erase the object entirely or miss the object completely. The former yields an unanswerable image, and the latter an image that is effectively unchanged. GridMask spreads small squares evenly across the whole image, making it easier to produce "just right" images in which only part of the object is erased.
In formulas:
x~=x×M,y~=y
Here, x is the image and M∈{0,1}H×W is a grid-shaped mask that is 0 only where pixels are erased. The ground-truth label y is not changed.
As an analogy, it is like looking outside through a window fitted with a lattice. The lattice bars hide part of the view, but every object remains partly visible, so it is still possible to tell what is there.
GridMask is not a method that chooses erased locations at random, but one that gives the erased locations a fixed structure (a grid). The paper also tried a variant that randomly decides, with a fixed probability, whether to erase each unit's square, but accuracy dropped.
Procedure
The mask is built by tiling square "units" of side d across the whole image (bottom right of the top figure). In each unit, bands of width r⋅d along the top and left are kept, and the remaining square of side (1−r)d is set to 0. The shape of the mask is determined by four numbers (r,d,δx,δy).
For each image, the following is done during training (left of the top figure).
If using the usual data augmentation such as cropping and horizontal flipping, apply it first, then normalize the image. GridMask is applied after normalization.
Decide with probability p whether to apply GridMask. Images not selected are used as is.
Randomly choose the unit side d from the range [dmin,dmax].
Randomly choose the grid offsets δx and δy, each from 0 to d−1. δx and δy are the distances from the image edge to the first complete unit.
Build the mask M from the chosen d, δx, δy and the preset r. In the ImageNet experiments, the mask is rotated before use.
Multiply the image by the mask and, without changing the label, train as usual with a loss such as cross-entropy.
Ignoring incomplete units at the edges, the fraction of the image kept (the keep ratio) k is given by the following formula.
k=H×Wsum(M)=1−(1−r)2
r determines the keep ratio, and d determines only the size of the erased squares. Changing d does not change the keep ratio.
Eq. (4) in the paper writes the side of the erased square as l=r×d. However, consistent with the keep ratio formula (Eq. (3)) and the official implementation (which uses l = ceil(d * ratio) as the width of the kept bands and sets everything else to 0), what is kept is bands of width r⋅d, and the erased square has side (1−r)d. The larger r is, the more is kept.
GridMask is used only during training. For evaluation and inference, feed the original image as is.
Choosing the hyperparameters
Three things are tuned: r, which sets the keep ratio; the unit size range [dmin,dmax]; and the probability of applying it. The values chosen in the paper are as follows.
Setting
ImageNet (ResNet-50 etc.)
CIFAR-10
COCO (object detection)
r
0.6
0.4
0.5
Range of d
[96,224] (images are 224 × 224)
−
−
Probability
Raised from 0 to 0.8 over 240 epochs, then held until epoch 300
Same schedule as ImageNet
Constant p=0.7
r: The paper compared r = 0.4–0.8 on ImageNet and 0.2–0.6 on CIFAR-10, choosing 0.6 and 0.4 respectively. Keeping more for harder datasets (avoiding underfitting) and erasing more for easier datasets (suppressing overfitting) worked better.
d: Smaller d reduces failures (erasing too much or too little of the object), but squares that are too small mean little to convolutions. The results of varying the range on ImageNet are shown below; choosing from a wide range for diversity worked better than fixing a narrow range.
Range of d
ImageNet top-1 accuracy (%)
[40,60]
77.26
[96,120]
77.58
[150,170]
77.61
[200,224]
77.57
[96,224]
77.89
Probability of applying: The paper compared applying with a constant probability p against raising it linearly to an upper limit P as training progresses, and reports that the latter was better in most experiments.
Why it works
The paper argues that for information-deleting data augmentation to succeed, a balance between deleting too much and keeping too much is essential.
Deleting too much: If the object and its surrounding context are erased entirely, the remaining information cannot determine the answer, and the sample is no different from noisy data.
Keeping too much: If the object is not touched at all, the image is the same as an unaugmented one and does nothing to build robustness.
Cutout and Random Erasing erase one large region, so depending on its position and size they easily fall into one of these failures. Hide-and-Seek, which extends the idea of dropout to regions (dividing the image into small squares and erasing them at random), improves on this, but adjacent squares can happen to be erased or kept together. Because GridMask arranges squares at regular intervals, only part of an object tends to be erased wherever it is.
The paper simulated 100,000 images of size 224 × 224 containing objects of size 40–160 with the keep ratio fixed at 0.75, and counted the rate of failures where "99% or more of the object is erased, or kept." Larger squares increase failures, but GridMask's failure rate was always lower than that of Cutout (extended to multiple squares) and Hide-and-Seek, and grew more slowly. The paper therefore says GridMask is easy to use even with fairly large squares.
Also, comparing CAM (a map of where in the image the model looked to decide) for ResNet-50 trained on ImageNet, the model trained with GridMask attended to a wider range of important regions than the model trained with only the usual data augmentation. An example is shown of an image with two mobile phones in which the GridMask model attended to both.
Results reported in the paper
Results for ImageNet image classification (top-1 accuracy, %). GridMask means adding only GridMask to the usual data augmentation (cropping, horizontal flipping); no color-changing augmentation is used.
In object detection, with longer training, the model without GridMask lost accuracy to overfitting (37.4% at 2× epochs, 35.7% at 4×), whereas with GridMask it rose to 39.2% at 4× epochs. Varying the application probability p from 0.3 to 0.9 barely changed mAP (38.0–38.3%).
The paper also tried a regularization combining the grid shape with Mixup (replacing CutMix's rectangle with a grid), reporting 78.7% for ResNet-50 on ImageNet (CutMix: 78.6%).
Practical considerations
Apply it after normalization. Then the regions filled with 0 take on the mean color and do not distort the statistics much. Filling with 0 while values are still in 0–1 produces a pure black grid.
Adjust r to the difficulty of the dataset. In the paper, ImageNet used 0.6 (about 16% erased) and CIFAR-10 used 0.4 (about 36% erased). Erasing too much on a hard dataset leads to underfitting.
Do not fix d to a single value; choose it from a range. Narrowing the range lowered accuracy. Also avoid d that is too small.
The method tends to pay off with long training. The paper's ImageNet experiments used 300 epochs, and the object detection comparisons also used longer-than-usual training. With short training, learning may appear slower because of the erased information.
It does not change labels. Even if part of an object is erased, the original label is kept, so for tasks with per-pixel ground truth such as segmentation, apply the mask only to the input image and leave the ground-truth mask unchanged.
torchvision has no transform named GridMask. Write it yourself following the same procedure as the paper's official implementation (the Grid class), as in the implementation example below. The official implementation has a switch (mode) for an "inverted GridMask" that swaps the mask's 0s and 1s; the paper's GridMask corresponds to mode=1.
Comparison with similar methods and how to choose
The following table compares methods that "erase part of an image or feature" from the same perspectives.
Method
What is erased
What fills the erased region
How erased locations are chosen
Label
GridMask
Multiple squares arranged at regular intervals in a grid
Object sizes and positions vary, and erasing too much or too little should be reduced: Use GridMask. Because of the grid, only part of an object tends to be erased wherever it is.
A single hyperparameter is preferred: Use Cutout. Only the side length of the square needs tuning.
The erased pixels should also be used for learning: Use CutMix. It pastes another image into the erased region and mixes labels by area ratio.
Regions should be erased inside the network rather than in the input: Use DropBlock.
GridMask can also be combined with data augmentation that selects transformations, such as AutoAugment. In the paper's CIFAR-10 experiments, using AutoAugment and GridMask together gave higher accuracy than either alone.
PyTorch example
▶Show code
python
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms.functional as TF
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
"""
CIFAR-10 image classification (training with GridMask)
"""
# Hyperparameters
batch_size = 128 # batch size
epochs = 10 # number of epochs
learning_rate = 1e-3 # learning rate
ratio = 0.4 # r: fraction of each unit kept as bands (the paper's CIFAR-10 setting; ImageNet uses 0.6)
d_min, d_max = 8, 32 # range for the unit side d (the paper's ImageNet setting is [96, 224] for 224 × 224 images)
max_prob = 0.8 # upper limit P of the application probability
rise_epochs = 8 # epochs over which the probability rises from 0 to P (240 of 300 epochs for ImageNet in the paper)
rotate = 1 # upper limit of mask rotation angle (degrees). 1 means no rotation. The ImageNet setting rotates
# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
class GridMask:
# Same procedure as the paper's official implementation (Grid class in JIA-Lab-research/GridMask, mode=1).
# In each unit of side d, keep bands (vertical and horizontal) of width l = ceil(d·r) and set the remaining (1 − r)d square to 0
def __init__(self, d_min, d_max, ratio, rotate=1, prob=1.0):
self.d_min, self.d_max = d_min, d_max
self.ratio = ratio
self.rotate = rotate
self.max_prob = prob
self.prob = prob
def set_prob(self, epoch, rise_epochs):
# Raise the application probability linearly to the upper limit as training progresses
self.prob = self.max_prob * min(1.0, epoch / rise_epochs)
def __call__(self, img): # img: normalized [C, H, W] tensor
if np.random.rand() > self.prob:
return img
h, w = img.size(1), img.size(2)
hh = math.ceil(math.sqrt(h * h + w * w)) # build on a square with the diagonal length so it still covers the image after rotation
d = np.random.randint(self.d_min, self.d_max) # unit side d
l = math.ceil(d * self.ratio) # width of kept bands r·d
st_h, st_w = np.random.randint(d), np.random.randint(d) # grid offsets δy, δx (0 to d−1)
keep = torch.zeros(hh, hh)
for i in range(-1, hh // d + 1):
s = d * i + st_h
keep[max(min(s, hh), 0):max(min(s + l, hh), 0), :] = 1 # keep horizontal bands
s = d * i + st_w
keep[:, max(min(s, hh), 0):max(min(s + l, hh), 0)] = 1 # keep vertical bands
angle = float(np.random.randint(self.rotate))
keep = TF.rotate(keep[None], angle)[0] # rotate the mask (0 degrees if rotate=1)
top, left = (hh - h) // 2, (hh - w) // 2
mask = keep[top:top + h, left:left + w] # crop the center to the image size
return img * mask # x̃ = x × M. The label is unchanged
grid_mask = GridMask(d_min, d_max, ratio, rotate=rotate, prob=max_prob)
mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4), # usual data augmentation (cropping, horizontal flip)
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std), # normalize to zero mean first (filling with 0 = filling with the mean color)
grid_mask, # apply after normalization
])
test_transform = transforms.Compose([ # GridMask is not used for evaluation
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform)
# num_workers=0: load data in the same process so that the probability changed by set_prob takes effect directly
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1), # [B, 3, 32, 32] -> [B, 32, 32, 32]
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 32, 16, 16]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> [B, 64, 16, 16]
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 64, 8, 8]
nn.Flatten(),
)
self.classifier = nn.Linear(64 * 8 * 8, num_classes)
def forward(self, x):
return self.classifier(self.features(x))
model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training: GridMask is applied during data loading. Labels are used as is
for epoch in range(epochs):
grid_mask.set_prob(epoch, rise_epochs) # raise the application probability every epoch
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
loss = criterion(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Evaluation: check on the original images
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
predicted = model(images).argmax(dim=1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy: {100 * correct / total:.2f}%")
FAQ
Q. How does GridMask differ from Cutout?
A.
Cutout erases one large square, while GridMask erases many small squares in a grid. Depending on position, Cutout may erase the object entirely or not at all, but because GridMask's squares are evenly spaced, it tends to produce images in which only part of the object is erased. For ResNet-50 on ImageNet in the paper, Cutout scored 77.1% and GridMask 77.9%.
Q. What value of r should be tried first?
A.
The paper chose r=0.6 (keep ratio k=1−0.42=0.84) for ImageNet and r=0.4 (k=0.64) for CIFAR-10. Use a larger r to keep more for harder datasets, and a smaller one to erase more for easier ones.
Q. Can it be used for object detection and segmentation?
A.
Yes. In the paper, the mAP of Faster R-CNN (ResNet-50-FPN) on COCO object detection rose from 37.4% to 39.2%, and the mIoU of PSPNet (ResNet-50) on Cityscapes segmentation rose from 77.3% to 78.1%. In both cases, GridMask was added after the usual data augmentation.