Mask patches for a masked autoencoder
Why it matters MAE pretraining encodes only 25% of patches, cutting ViT pretraining compute about 3x.
MAE hides most image patches and only encodes the visible ones.
Write mae_mask(x, mask_ratio, noise). x is (N, L, D) patch tokens, noise is (N, L) random numbers. For each sample, sort patches by noise ascending; keep the first int(L * (1 - mask_ratio)). Return (x_kept, mask, ids_restore): x_kept (N, len_keep, D) in that sorted order, mask (N, L) with 0 for kept and 1 for removed in the ORIGINAL patch order, and ids_restore = argsort of the shuffle order.
def mae_mask(x, mask_ratio, noise)Example
noise [[0.3, 0.1, 0.2]] and ratio 1/3 keep patches 1 and 2, so mask is [[1, 0, 0]].
Understand the idea
A masked autoencoder hides most image patches and asks the model to rebuild them. To pick a random subset per image without a loop, you give every patch a random noise value, sort by noise, and keep the first part. You also need a way to put patches back in their original order later. Worked example: noise [[0.5, 0.1, 0.9, 0.3]], ratio 0.5, so L = 4 and keep int(4 * 0.5) = 2. Sorting noise ascending gives the shuffle order [1, 3, 0, 2], so patches 1 and 3 are kept, in that order. ids_restore = argsort([1, 3, 0, 2]) = [2, 0, 3, 1]. In shuffled order the mask is [0, 0, 1, 1]; gathering it with ids_restore gives [1, 0, 1, 0] in original order, which correctly marks patches 1 and 3 as kept. Rule: ids_shuffle = argsort(noise, axis 1); ids_restore = argsort(ids_shuffle, axis 1); len_keep = int(L * (1 - mask_ratio)); x_kept = gather x along L with ids_shuffle[:, :len_keep]; mask = gather of [0 for kept, 1 for removed] with ids_restore. Return the mask in original order. Used in: MAE pretraining for ViTs.
Shapes and data flow
noise (N, L) -> ids_shuffle (N, L) -> keep first L(1-r) x (N, L, D) -> x_kept (N, keep, D) mask built shuffled -> unshuffle with ids_restore