AI Logic

Architectures

BEiT

Updated:

BEiT pre-training. On the left, the image is split into patches, blocks of patches are masked and replaced with [M], and the result passes through the BEiT encoder and the MIM head; in parallel, the same image is converted into visual tokens by the tokenizer, and the two paths meet in a cross-entropy loss at the masked positions. On the right, block-wise masking on a 14×14 patch grid (about 40%) and the positions used as targets

Background and Overview

BEiT (BERT Pre-Training of Image Transformers) is a BERT-style self-supervised pre-training method for ViT: part of an image's patches are masked, and the model predicts the "visual tokens" (the image expressed as a sequence of discrete symbols) at the masked positions, in the same spirit as BERT. It was published in 2021 by Bao et al. at Microsoft Research and Harbin Institute of Technology and accepted at ICLR 2022. The paper names this task "masked image modeling (MIM)."

ViT needs more labeled data than CNNs. Pre-training on unlabeled images can ease this problem. In language, BERT had been highly successful with pre-training that masks some words in a sentence and predicts them, but transferring this directly to images faced two obstacles.

  • Image patches have no vocabulary: for words, a softmax can predict "which entry in the dictionary" a word is, but image patches have no fixed list of candidates.
  • Predicting raw pixels wastes capacity on details: when masked patches are restored by regressing their pixels, the model spends its capacity on short-range pixel dependencies and fine textures (high-frequency components), and is less inclined to capture the semantics of objects.

BEiT uses a pre-trained image tokenizer (the discrete VAE from DALL-E) to convert each image into 14×14 visual tokens (codes from 8,192 classes), and uses these as targets in place of the "masked words." The input remains pixel patches; the output is a classification over visual token codes.

A ViT-B pre-trained on ImageNet-1K without labels reaches 83.2% after fine-tuning (84.6% at 384×384), outperforming DeiT-B trained from scratch (81.8%) as well as contemporary self-supervised methods DINO and MoCo v3. After BEiT, MAE, which reconstructs the pixels of masked patches directly, was proposed, and masked image modeling became one of the main approaches to pre-training image Transformers.

Theory: Masked Image Modeling

In BEiT pre-training, each image is represented in two ways. The input is image patches (pixels); the target is visual tokens (codes). The left side of the figure at the top of this article shows the training flow, and the right side shows how masking is applied on the 14×14 patch grid.

Creating visual tokens (once, before pre-training)

The tokenizer qϕ(z∣x)q_\phi(z \mid x) converts an image xx into a sequence of codes z=[z1,…,zN]z = [z_1, \dots, z_N] from the vocabulary V={1,…,8192}\mathcal{V} = \{1, \dots, 8192\}. The paired decoder pψ(x∣z)p_\psi(x \mid z) reconstructs the image from the code sequence. BEiT does not train these two itself; it reuses the discrete VAE (dVAE) released with DALL-E as is. A 224×224 image becomes 14×14 = 196 visual tokens, the same as the number of patches.

Pre-training procedure

  1. Split into patches: the image is split into N=196N = 196 patches of 16×16. The same image is also passed through the tokenizer to obtain 196 visual tokens ziz_i.
  2. Mask in blocks: about 40% of the patches (at most 75) are selected to form the set of masked positions M\mathcal{M}. The selection procedure is described below.
  3. Replace the masked patches: the patches are embedded with a linear layer, and the masked positions are replaced with a learnable vector e[M]e_{[\mathrm{M}]}. A special token [S] is prepended, and learnable position embeddings are added.
  4. Pass through the encoder: the sequence passes through LL layers of a Transformer encoder identical to ViT's, giving the output hiLh_i^L at each patch position.
  5. Predict the visual tokens at masked positions: for each masked position i∈Mi \in \mathcal{M}, a linear layer and softmax predict which of the 8,192 codes it is, and the cross-entropy with the target ziz_i is minimized. Predictions at unmasked positions are not included in the loss.

The prediction and the objective are as follows (Section 2.3 and Eq. (1) of the paper). xMx^{\mathcal{M}} is the masked image, and Wc∈R∣V∣×DW_c \in \mathbb{R}^{|\mathcal{V}| \times D} and bc∈R∣V∣b_c \in \mathbb{R}^{|\mathcal{V}|} are the weights of the MIM head.

pMIM(z′∣xM)=softmaxz′(WchiL+bc),max⁡∑x∈DEM[∑i∈Mlog⁡pMIM(zi∣xM)]p_{\mathrm{MIM}}(z' \mid x^{\mathcal{M}}) = \mathrm{softmax}_{z'}\bigl(W_c h_i^L + b_c\bigr), \qquad \max \sum_{x \in \mathcal{D}} \mathbb{E}_{\mathcal{M}} \Bigl[ \sum_{i \in \mathcal{M}} \log p_{\mathrm{MIM}}(z_i \mid x^{\mathcal{M}}) \Bigr]

Block-wise masking (Algorithm 1 of the paper)

Instead of choosing patches one at a time at random, BEiT selects contiguous rectangular regions.

  1. Choose the size: the number of patches ss in a block is chosen at random between 16 and "the number still needed."
  2. Choose the aspect ratio: a ratio rr is chosen at random between 0.30.3 and 1/0.31/0.3, and the block's height and width are set to a=s⋅ra = \sqrt{s \cdot r} and b=s/rb = \sqrt{s / r}.
  3. Choose the location: the block is placed at a random position in the image, and its patches are added to M\mathcal{M}.
  4. Repeat: steps 1–3 are repeated until more than 40% of the patches are masked.

With scattered masking, a masked patch can easily be inferred from its visible neighbors. Masking contiguous regions forces the model to infer from the surrounding context, which makes the task harder. This is the same idea as the BERT-family technique of masking spans of consecutive words rather than individual words.

The VAE perspective

The paper explains BEiT pre-training as training a variational autoencoder. The lower bound on the log-likelihood of reconstructing the original image xx from the masked image x~\tilde{x} is as follows (Eq. (2) of the paper).

∑(xi,x~i)∈Dlog⁡p(xi∣x~i) ≥∑(xi,x~i)∈D(Ezi∼qϕ(z∣xi)[log⁡pψ(xi∣zi)]−DKL[qϕ(z∣xi), pθ(z∣x~i)])\sum_{(x_i, \tilde{x}_i) \in \mathcal{D}} \log p(x_i \mid \tilde{x}_i) \ \ge \sum_{(x_i, \tilde{x}_i) \in \mathcal{D}} \Bigl( \mathbb{E}_{z_i \sim q_\phi(z \mid x_i)} \bigl[\log p_\psi(x_i \mid z_i)\bigr] - D_{\mathrm{KL}}\bigl[q_\phi(z \mid x_i),\ p_\theta(z \mid \tilde{x}_i)\bigr] \Bigr)

This is trained in two stages. Stage 1 trains the tokenizer and decoder (the reconstruction in the first term); stage 2 freezes them and trains pθp_\theta, which predicts visual tokens from the masked image. If qϕq_\phi is treated as a distribution concentrated on the most probable token z^i=arg⁡max⁡zqϕ(z∣xi)\hat{z}_i = \arg\max_z q_\phi(z \mid x_i), the second term becomes log⁡pθ(z^i∣x~i)\log p_\theta(\hat{z}_i \mid \tilde{x}_i), which is exactly BEiT's pre-training objective (Eq. (3)).

Visual tokens round off fine pixel differences and summarize a region as an abstract symbol meaning "this area looks like this." As an analogy, instead of redrawing the masked part of a picture in full detail, the model is asked to answer with words like "sky," "grass," or "fur." The paper argues that pixel reconstruction spends capacity on short-range dependencies and details, whereas predicting visual tokens leads the model to learn higher-level information.

Architecture and Training

Encoder

The encoder has the same shape as ViT, so that results can be compared directly with prior work (Sections 2.2 and 2.5 and Appendix G of the paper).

ItemBEiT-BBEiT-L
Layers1224
Hidden dimension DD7681024
MLP inner dimension30724096
Heads1216
Patch size16×1616×16

For initialization, all weights are first initialized within the small range [−0.02,0.02][-0.02, 0.02], and then the weights of the last linear layer in the self-attention and MLP of layer ll are scaled by 1/2l1/\sqrt{2l}. The paper notes that this is important for stabilizing Transformers in large-scale pre-training.

Pre-training settings (Section 2.5 and Appendix G of the paper)

ItemSetting
DataImageNet-1K training set (about 1.2 million images, labels not used)
Data augmentationRandom resized cropping, horizontal flipping, color jittering
LengthAbout 500k steps (800 epochs), batch size 2048
OptimizerAdam (β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999; cites the AdamW paper on decoupled weight decay), weight decay 0.05
Learning ratePeak 1.5e-3, 10 epochs of warmup followed by cosine decay
RegularizationStochastic Depth 0.1, no Dropout
ComputeAbout 5 days on 16 V100 (32GB) GPUs

Fine-tuning

After pre-training, as with BERT, task-specific layers are added on top of the encoder and the whole model is trained again.

  • Image classification: the outputs of all patches are averaged, and a linear layer with softmax predicts the class. The hyperparameters mostly follow DeiT, with layer-wise learning rate decay (larger for upper layers, smaller for lower layers; a factor of 0.65 per layer for BEiT-B on ImageNet).
  • Semantic segmentation: BEiT is used as the backbone, with deconvolution layers added as the decoder (the same form as SETR-PUP).
  • Intermediate fine-tuning: after self-supervised pre-training, the model is fine-tuned once on labeled ImageNet before moving to the target task. This is a common procedure for BERT, and it further improves accuracy for BEiT as well.

The appendix also tests an improved version (BEiT+) that adds LayerScale and relative position bias, which is slightly better on both ImageNet and ADE20K.

Experimental Results

Image classification (ImageNet-1K fine-tuning, top-1 accuracy %; Table 1 of the paper)

Pre-trainingModelResolutionAccuracy
None (trained from scratch)ViT-B38477.9
None (trained from scratch)DeiT-B22481.8
None (trained from scratch)DeiT-B38483.1
Supervised (ImageNet-22K)ViT-B38484.0
Supervised (ImageNet-22K)ViT-L38485.2
Self-supervised (ImageNet-1K)DINO-B22482.8
Self-supervised (ImageNet-1K)MoCo v3-B22483.2
Self-supervised (ImageNet-1K)MoCo v3-L22484.1
Self-supervised (ImageNet-1K)BEiT-B22483.2
Self-supervised (ImageNet-1K)BEiT-B38484.6
Self-supervised (ImageNet-1K)BEiT-L22485.2
Self-supervised (ImageNet-1K)BEiT-L38486.3

BEiT-B (384), pre-trained only on unlabeled ImageNet-1K, outperforms ViT-B (384, 84.0%) pre-trained on labeled ImageNet-22K (about 14 million images). Also, when trained from scratch, ViT-L (76.5%) scores lower than ViT-B (77.9%), whereas with BEiT, scaling from B to L gains 2.0 points. The paper takes this as evidence that BEiT is more beneficial for larger models.

Semantic segmentation (ADE20K mIoU %, SETR-PUP; Table 3 of the paper)

Pre-trainingmIoU
Supervised (ImageNet)45.3
DINO44.1
BEiT45.6
BEiT + intermediate fine-tuning47.7

What matters (300 epochs of pre-training; ImageNet is accuracy %, ADE20K is mIoU %; Table 4 of the paper)

SettingImageNetADE20K
BEiT (default)82.8644.65
Without block-wise masking (random masking)82.7742.93
Reconstruct pixels instead of visual tokens81.0441.38
Reconstruct pixels with random masking80.5037.09
Predict all visual tokens, including unmasked positions82.5940.93
Predict all visual tokens without masking81.6736.73
Longer pre-training (800 epochs)83.1945.58

Reconstructing pixels instead of visual tokens drops ImageNet by 1.8 points and ADE20K by 3.3 points, falling even below DeiT-B trained from scratch (81.8%). The paper concludes that predicting visual tokens is the key to BEiT. Block-wise masking helps especially for segmentation.

Linear probing (the encoder is frozen and only a linear layer is trained on the averaged outputs of an intermediate layer; Table 9 of the paper): BEiT-B reaches 56.7% and BEiT-L 73.5%. These are lower than DINO-B (78.2%) and MoCo v3-B (76.7%); BEiT's features are better suited to fine-tuning than to direct use with a linear classifier.

Pre-training on larger data (Table 6 of the paper, BEiT+): BEiT-L+ with pre-training and intermediate fine-tuning on ImageNet-22K reaches 88.4% at 384×384, on par with ViT-L (88.5%) trained on JFT-3B, a labeled dataset of 3 billion images.

Practical Considerations

Keep the following points in mind when using BEiT.

  • Pre-training requires a separate tokenizer: a pre-trained tokenizer, such as DALL-E's discrete VAE, is needed to produce visual tokens. The paper uses a publicly released one, which was trained on a large set of images separate from ImageNet. According to the paper's appendix, a tokenizer retrained only on ImageNet-1K gives almost the same accuracy (82.70% vs. 82.86%).
  • Use it with fine-tuning: under linear probing it scores lower than DINO and MoCo v3. It is better suited to retraining the whole model for each task than to using frozen features.
  • Decay the learning rate layer by layer: fine-tuning uses smaller learning rates for lower layers (a factor of 0.65 per layer for BEiT-B on ImageNet). With an ordinary uniform learning rate, the paper's accuracy may not be reproduced.
  • Where to get it in PyTorch: Hugging Face transformers provides BeitModel, BeitForImageClassification, and BeitForMaskedImageModeling, and pre-trained weights such as microsoft/beit-base-patch16-224 can be loaded. The official implementation is in the beit directory of the microsoft/unilm repository.

BEiT pre-training costs extra compute for the tokenizer, and the quality of the targets depends on how good the tokenizer is. The later MAE reconstructs pixels (normalized per patch) without a tokenizer and feeds only the visible patches to the encoder, which makes it faster than BEiT and more accurate. When pre-training from scratch, compare BEiT with MAE and other successors before choosing.

Comparison with Other Methods

BEiT is one of the starting points of the "mask and predict" family of self-supervised learning for images. Side by side from the same perspective:

MethodTraining taskTarget at masked positionsEncoder inputBest suited for
Preliminary experiment in ViTPredict masked patchesMean color of the patch (3 bits)All patches—
BEiTPredict visual tokens of masked patchesTokenizer codes (8,192 classes)All patches (masked ones as [M])Fine-tuning
MAEReconstruct pixels of masked patchesPatch pixelsVisible patches only (75% masked)Fine-tuning, fast training of large models
DINO, MoCo v3Match or discriminate outputs of two viewsNone (the other view)All patchesLinear probing, nearest-neighbor retrieval

The differences between BEiT and MAE lie in the targets and efficiency. BEiT uses visual tokens as targets so that the model does not have to predict pixel details. MAE showed that even with raw pixels as targets, a high masking ratio of 75% makes the task hard enough, eliminating the need for a tokenizer. MAE also feeds only the visible patches to the encoder, which makes pre-training cheaper.

Rough guidelines for choosing:

  • Pre-train a ViT without labels and fine-tune it for classification or segmentation: the BEiT/MAE family fits. For new pre-training, MAE, which needs no tokenizer, is easier.
  • Use published BEiT weights: weights trained on ImageNet can be loaded from Hugging Face and elsewhere and fine-tuned directly.
  • Use frozen features with a linear classifier or nearest-neighbor retrieval: methods that compare two views, such as DINO, achieve higher accuracy under linear probing.

PyTorch example

Show code
python
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A small implementation of BEiT's masked image modeling (Section 2.3, Eq. (1), and Algorithm 1 of the paper).
The visual tokens z are precomputed with a pre-trained tokenizer (e.g., DALL-E's dVAE) and passed in.
The encoder is substituted with PyTorch's nn.TransformerEncoder (Pre-LN, GELU, 4x MLP)
"""


def blockwise_mask(h=14, w=14, ratio=0.4, min_block=16):
  """Algorithm 1: mask contiguous rectangles until more than ratio of all patches are masked. Returns a [h*w] bool"""
  mask = torch.zeros(h, w, dtype=torch.bool)
  target = int(ratio * h * w)
  while mask.sum() <= target:
    s = random.uniform(min_block, max(min_block, target - mask.sum().item()))  # number of patches in the block
    r = random.uniform(0.3, 1 / 0.3)                                            # aspect ratio
    a, b = int(round(math.sqrt(s * r))), int(round(math.sqrt(s / r)))
    a, b = min(max(a, 1), h), min(max(b, 1), w)
    t, l = random.randint(0, h - a), random.randint(0, w - b)
    mask[t:t + a, l:l + b] = True
  return mask.flatten()


class BEiTPretrain(nn.Module):
  def __init__(self, img_size=224, patch=16, dim=768, depth=12, heads=12, vocab=8192):
    super().__init__()
    n = (img_size // patch) ** 2                                   # 196
    self.patch_embed = nn.Conv2d(3, dim, kernel_size=patch, stride=patch)
    self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))          # [S]
    self.mask_token = nn.Parameter(torch.zeros(1, 1, dim))         # e_[M]
    self.pos_embed = nn.Parameter(torch.zeros(1, n + 1, dim))      # learnable position embeddings
    for p in (self.cls_token, self.mask_token, self.pos_embed):
      nn.init.trunc_normal_(p, std=0.02)
    layer = nn.TransformerEncoderLayer(dim, heads, 4 * dim, dropout=0.0, activation="gelu",
                                       batch_first=True, norm_first=True)
    self.encoder = nn.TransformerEncoder(layer, depth)
    self.norm = nn.LayerNorm(dim)
    self.mim_head = nn.Linear(dim, vocab)                         # W_c, b_c: classification over 8192 codes

  def forward(self, img, mask, visual_tokens):
    """img: [B, 3, 224, 224], mask: [B, 196] (True = masked), visual_tokens: [B, 196] codes"""
    x = self.patch_embed(img).flatten(2).transpose(1, 2)           # [B, 196, D]
    B, N, D = x.shape
    m = mask.unsqueeze(-1).type_as(x)
    x = x * (1 - m) + self.mask_token.expand(B, N, D) * m          # replace masked positions with [M]
    x = torch.cat([self.cls_token.expand(B, -1, -1), x], dim=1) + self.pos_embed
    h = self.norm(self.encoder(x))[:, 1:]                          # output h_i^L for each patch
    logits = self.mim_head(h[mask])                                # predict only the masked positions
    return F.cross_entropy(logits, visual_tokens[mask])            # maximizes the log-likelihood of Eq. (1)


model = BEiTPretrain()
model.train()                                                     # pre-training (Stochastic Depth etc. are active in train mode)
img = torch.randn(2, 3, 224, 224)
mask = torch.stack([blockwise_mask() for _ in range(2)])          # mask about 40%
visual_tokens = torch.randint(0, 8192, (2, 196))                  # in practice, the tokenizer's output
loss = model(img, mask, visual_tokens)
loss.backward()

# Fine-tuning from pre-trained weights (Hugging Face transformers)
# from transformers import BeitForImageClassification
# clf = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224")

FAQ

Q. What is the difference between BEiT and MAE?
A.

Both are self-supervised methods that mask image patches and predict them, but they differ in the targets and in the encoder input. BEiT uses visual tokens (codes from 8,192 classes) produced by a separately trained tokenizer as targets, and feeds the masked patches to the encoder as well, replaced with [M]. MAE uses the raw pixels of the masked patches as targets and feeds only the visible patches to the encoder. MAE needs no tokenizer, and its pre-training is cheaper.

Q. Why predict visual tokens instead of pixels?
A.

Because reconstructing raw pixels makes the model spend its capacity on short-range pixel dependencies and fine textures. In the paper's comparison, reconstructing pixels instead of visual tokens lowers ImageNet accuracy from 82.86% to 81.04% and ADE20K mIoU from 44.65 to 41.38. Visual tokens are abstract symbols with details rounded off, so learning is steered toward capturing the semantics of objects.

Q. Why are patches masked in blocks?
A.

Because with scattered masking, a masked patch can easily be inferred from its immediately visible neighbors. Masking contiguous regions requires inference from a wider context, which makes the task harder. In the paper's comparison, dropping block-wise masking lowers ADE20K mIoU from 44.65 to 42.93.

References

  1. Bao, H., Dong, L., Piao, S., & Wei, F. (2022). BEiT: BERT Pre-Training of Image Transformers. ICLR 2022. arXiv:2106.08254.
  2. beit in microsoft/unilm (official implementation and pre-trained weights).
  3. Ramesh, A., et al. (2021). Zero-Shot Text-to-Image Generation (DALL-E; the tokenizer used by BEiT). arXiv:2102.12092.
  4. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv:1810.04805.
  5. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.