# BEiT: BERT Pre-Training of Image Transformers

BEiT pretrains vision Transformers by predicting masked image patches as visual tokens

Hangbo Bao, Li Dong, Songhao Piao, Furu Wei · arXiv · 2021-6-15

- **Problem** BERT-style masked prediction has no direct counterpart for image patches. Patches have no fixed vocabulary, and regressing raw pixels spends capacity on local detail.
- **Method** BEiT masks about 40% of image patches in blocks and feeds the corrupted sequence to a Transformer encoder. It is trained to predict discrete visual tokens from a pretrained image tokenizer.
- **Results** BEiT reaches 83.2% top-1 accuracy on ImageNet-1K at base size. It reaches 45.6 mIoU on ADE20K with single-scale inference.

## Why BERT's recipe does not carry over to image patches

Vision Transformers perform well on image tasks, but they need more training data than convolutional networks do. Self-supervised pretraining on large image collections is a natural way to supply that data, and contrastive learning and self-distillation are the two strands the introduction names.

BERT hides some tokens of a text and recovers them from the Transformer encoding of the corrupted text. Image patches have no vocabulary comparable to words or BPE subwords, so a softmax over a fixed set of candidates for each masked patch is not available.

Regressing the raw pixels of masked patches avoids the vocabulary problem, but the authors argue it spends modeling capacity on short-range dependencies and high-frequency detail. The goal is to solve both problems, the missing vocabulary and the pixel-level target, within one pretraining task.

## Masked image modeling with visual tokens

Each image is handled in two views: its patches form the encoder input, and its discrete visual tokens form the prediction target. A 224× 224 image is split into a 14× 14 grid of patches, each 16× 16. For an image of size H by W with patches of size P by P, the number of patches is \\(N = HW/P^2\\). The patches are flattened and linearly projected, much like word embeddings in BERT, and the raw pixel values remain in these input features.

A special token \[S\] is prepended, learnable 1D position embeddings are added, and the layers of Transformer blocks produce one output vector per patch.

The image tokenizer is a discrete variational autoencoder: its encoder maps pixels to indices in a visual codebook, and its decoder reconstructs the image from those indices. Because the discrete codes block gradients, training uses the Gumbel-softmax relaxation, and a uniform prior is placed on the tokenizer during this training. The vocabulary has 8192 entries, and the tokenizer gives one token per patch, so each image becomes a 14× 14 grid of visual tokens.

The main results use a publicly available tokenizer, and a re-implemented tokenizer is compared in an appendix.

During pretraining, about 40% of the patches are chosen as masked positions, and each masked patch is replaced by one shared learnable embedding. The Transformer encodes this corrupted sequence, and a softmax classifier on the final vectors at the masked positions predicts the visual token at each one. The objective maximizes the log-likelihood of the correct visual tokens over masked positions, averaged over masking draws and summed over the training corpus: \\\[ \\max \\sum\_{x \\in D} \\mathbb{E}\_M \\Big\[ \\sum\_{i \\in M} \\log p\_{MIM}(z\_i \\mid x^M) \\Big\] \\\] Here D is the training corpus, M is the random set of masked positions, and x^M is the corrupted image.

Masked positions are not drawn independently. Blocks are added one at a time, each with a random size of at least 16 patches and a random aspect ratio, until the masked set reaches 0.4N. The authors motivate this with the n-gram or span masking already used in BERT-like models.

The authors argue that predicting discrete tokens, rather than pixels, pushes the model toward higher-level content, because the tokens summarize local details. The ablation studies later test this choice directly against pixel recovery.

## Reading the objective as a variational autoencoder

The authors also read the objective through the evidence lower bound of a variational autoencoder, where the original image is x and its masked version is \\(\\tilde{x}\\). The bound contains a reconstruction term over visual tokens z drawn from the tokenizer, minus a KL term between the tokenizer distribution and a predictor conditioned on the masked image.

On this reading, the masked prediction task is the predictor \\(p\_\\theta(z\|\\tilde{x})\\), which recovers visual tokens from the corrupted image.

Training follows two stages: the tokenizer is first learned as a discrete variational autoencoder with a uniform prior, and then the predictor is learned while the tokenizer and decoder stay fixed. To simplify, the tokenizer distribution is replaced by a point mass on its most likely tokens, which makes the bound a sum of a reconstruction term and a log-predictor term.

The second term is the BEIT pretraining objective, so the pretraining step is the second stage of this view.

This interpretation explains the form of the objective, but the experiments, not the bound, are what test whether it yields better representations.

## Pretraining and fine-tuning configuration

The backbone follows the ViT-Base shape: 12 layers, hidden size 768, 12 attention heads, and feed-forward size 3072, with 16× 16 input patches. Pretraining uses the ImageNet-1K training set, about 1.2M images, and no labels are used for self-supervised learning. Augmentation consists of random resized cropping, horizontal flipping and color jittering.

The pretraining run covers 800 epochs, about 500k steps, with a batch size of 2k. Optimization uses Adam with beta1 of 0.9 and beta2 of 0.999, a learning rate of 1.5e-3 with 10 warmup epochs and cosine decay, and a weight decay of 0.05. Stochastic depth at rate 0.1 is used and dropout is disabled. On 16 Nvidia Tesla V100 32GB cards, the 500k steps take about five days.

Parameters start from a small uniform range, from -0.02 to 0.02, and the output projections of each sub-layer are then rescaled according to the layer index. The authors describe this initialization as important for stabilizing Transformer training at large scale.

After pretraining, a task layer is attached to the encoder and the whole network is fine-tuned on labeled data. For classification, average pooling over the patch vectors feeds a linear softmax classifier, and the parameters of BEIT and the classifier are updated together. For segmentation, the model follows the SETR-PUP design, with deconvolution layers as the decoder, and it is fine-tuned end to end.

Intermediate fine-tuning first trains on ImageNet-1K with labels and then trains on the target dataset, a practice the authors take from BERT fine-tuning in NLP.

## ImageNet classification results

Classification experiments use ILSVRC-2012 ImageNet, with 1k classes and about 1.3M images, and are scored by top-1 accuracy. Table 1 groups the baselines into random initialization, supervised pretraining and self-supervised methods, and all are base size except iGPT-1.36B.

BEIT-B's 83.2 is above the 82.8 of DINO-B and equal to the 83.2 of MoCo v3-B, so in this table it does not exceed MoCo v3-B.

The authors treat iGPT-1.36B and ViT-JFT300M as the closest methods, because both use auto-encoding for vision Transformers. iGPT uses clustered image tokens as both input and output, whereas BEIT feeds image patches as input and uses visual tokens only as the prediction target. ViT-JFT300M instead predicts the mean 3-bit color of masked patches, and it is pretrained on Google's in-house 300M images rather than ImageNet.

Fine-tuning at 384× 384 for 10 more epochs keeps the patch size fixed, so the sequence is longer, and this raised BEIT results by more than 1 point on ImageNet. BEIT384-B reaches 84.6, above the 84.0 of ViT384-B pretrained on ImageNet-22K at the same input resolution.

Training ViT from scratch gets worse from base to large: ViT384-B reaches 77.9 and ViT384-L reaches 76.5.

## Fine-tuning convergence speed

The convergence comparison plots top-1 accuracy over epochs, with DeiT trained from scratch on one side and BEIT fine-tuned from pretraining on the other, on ImageNet-1K. Fine-tuning BEIT reaches higher accuracy and converges much faster than training DeiT from scratch. The authors add that fine-tuned BEIT reaches reasonable accuracy within very few epochs.

The main text gives no per-epoch values, so the speed difference is read from the curves.

## ADE20K segmentation results

ADE20K segmentation uses 25K images and 150 semantic categories, and the score is mean Intersection over Union averaged over all categories. The SETR-PUP task layer and most of its hyperparameters are kept, with Adam at learning rate 1e-3, layer-wise decay, 160K steps and batch size 16. Results use single-scale inference.

Under this setup BEIT reaches 45.6 mIoU, above the 45.3 of supervised pretraining on ImageNet and the 44.1 of DINO. The authors note that BEIT needs no manual annotation for pretraining, while the supervised baseline uses ImageNet labels.

Running intermediate fine-tuning on ImageNet-1K before ADE20K raises BEIT to 47.7 mIoU. This is the highest segmentation score in the main text.

## Which pretraining choices matter

The ablations pretrain for 300 epochs, which the authors put at 37.5% of the steps used in the main experiments, and they evaluate on ImageNet-1K and ADE20K. The default variant reaches 82.86 top-1 and 44.65 mIoU in this setting.

Replacing blockwise masking with randomly sampled masked positions gives 82.77 top-1 and 42.93 mIoU. The ImageNet change is small, while the ADE20K drop is larger, which matches the authors' reading that blockwise masking helps most on segmentation.

Predicting the raw pixels of masked patches in place of visual tokens gives 81.04 top-1 and 41.38 mIoU. The authors state that predicting visual tokens is the key ingredient of BEIT. The authors also say the pixel variant is worse than training a vision Transformer from scratch on both tasks, but the from-scratch rows in Table 1 use different schedules, so this is an indirect reading.

Removing both visual tokens and blockwise masking gives 80.50 top-1 and 37.09 mIoU, the lowest ImageNet score in the ablation table. Predicting all visual tokens instead of only those at masked positions gives 82.59 top-1 and 40.93 mIoU, and the authors state that recovering all visual tokens harms downstream performance. Dropping masking while recovering all visual tokens gives 81.67 top-1 and 36.73 mIoU.

Pretraining for 800 epochs raises the ablation default to 83.19 top-1 and 45.58 mIoU. The 800-epoch run is the schedule of the main model, so the 300-epoch rows are a shorter analogue of it.

## What the self-attention heads attend to

To inspect what BEIT learns without labels, the authors plot self-attention maps for chosen reference patches in MS COCO images, which are not part of the pretraining data. The maps use attention scores from query-key products in the last layer, with the reference patch as the query and the map showing which patches it attends to.

Figure 2 shows attention concentrating on the object or region that contains the reference point, and the authors say the heads separate objects without any annotation. The authors read this as evidence that BEIT acquires semantic region structure, which may partly explain the downstream gains, especially on small datasets. The evidence is a set of selected examples, and no quantitative boundary or segmentation score is reported for them.

## Position among self-supervised vision methods

Earlier self-supervised vision work relied on pretext tasks such as predicting patch orderings, colorization and rotation angles. A related line masks patches and classifies each masked position as real or fake, which the authors compare with the masked version of jigsaw pretraining. Contrastive methods pull augmented views of an image together and push other images apart, and they usually need large memory banks or large batches for negatives.

Clustering-based methods group image examples instead.

Among pretraining methods for vision Transformers, iGPT builds a 9-bit color palette with k-means and uses the clustered tokens, while BEIT keeps raw patches as input. The authors describe ViT's masked patch prediction as a preliminary exploration, and they note that ViT also found pixel-level auto-encoding to perform worse. BEIT's visual tokens come from a discrete VAE rather than clustering, which the authors say makes the objective better motivated theoretically, and they claim several times higher pretraining throughput and lower memory use than contrastive and self-distillation methods, with throughput details placed in an appendix.

## Limitations

The ablations use 300 pretraining epochs while the main model uses 800, so ablation numbers are not the main-result numbers. Each ablation changes one design choice on ImageNet-1K and ADE20K and is read against the default variant of the same table.

The convergence speed gain is read from curves, and the main text gives no per-epoch values. Intermediate fine-tuning is described as adding accuracy on ImageNet, but the main text gives no number for that gain.

BEIT-B and MoCo v3-B tie at 83.2 in Table 1, so an advantage over other base-size self-supervised methods is not shown on ImageNet. The attention analysis uses selected examples without a quantitative measure. Pretraining in the main experiments uses only ImageNet-1K, and segmentation uses one task layer, SETR-PUP.

## Paper info

- **Authors**: Hangbo Bao, Li Dong, Songhao Piao, Furu Wei
- **Venue**: arXiv · Preprint
- **First published**: 2021-6-15
- **Added**: 2026-11-12
- **Updated**: 2022-9-3
- **Version**: v2
- **arXiv**: 2106.08254
- **Category**: cs.CV · cs.LG
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/2106.08254v2) · [PDF ↗](https://arxiv.org/pdf/2106.08254v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Hangbo Bao, Li Dong, Songhao Piao, Furu Wei (2021). BEiT: BERT Pre-Training of Image Transformers. arXiv:2106.08254v2. https://arxiv.org/abs/2106.08254v2

**BibTeX**

```
@misc{bao2021beit,
  title = {{BEiT: BERT Pre-Training of Image Transformers}},
  author = {Hangbo Bao and Li Dong and Songhao Piao and Furu Wei},
  year = {2021},
  eprint = {2106.08254},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2106.08254v2}
}
```

## Other paper commentary

- [Training Region-based Object Detectors with Online Hard Example Mining](https://refivu.com/en/papers/3c16d5fe-9eb6-4481-9b4d-f4eefd0171ee-training-region-based-object-detectors-with-online-hard.md)
- [Unsupervised Learning of Visual Features by Contrasting Cluster Assignments](https://refivu.com/en/papers/8f949bbf-9733-4844-b3ee-a88f5313c480-unsupervised-learning-of-visual-features-by-contrasting.md)
- [PWC-Net: CNNs for Optical Flow Using Pyramid, Warping, and Cost Volume](https://refivu.com/en/papers/ad6f8625-4b03-4079-ad4e-a2126c614f62-pwc-net-cnns-for-optical-flow-using-pyramid.md)
- [VMamba: Visual State Space Model](https://refivu.com/en/papers/4032560e-3e65-4a0f-b564-34cb12bd1c92-vmamba-visual-state-space-model.md)
- [Speed/accuracy trade-offs for modern convolutional object detectors](https://refivu.com/en/papers/d59f0ced-71a6-4425-a177-e2e9ad7b8370-speed-accuracy-trade-offs-for-modern-convolutional-object.md)
- [Building Machines That Learn and Think Like People](https://refivu.com/en/papers/1c62e17f-b645-4165-8400-ffcbcd4abc96-building-machines-that-learn-and-think-like-people.md)
- [European Union regulations on algorithmic decision-making and a "right to explanation"](https://refivu.com/en/papers/8d7d2fe1-f155-44ca-8f0a-551e154b6b3a-european-union-regulations-on-algorithmic-decision-making.md)
- [Don't Stop Pretraining: Adapt Language Models to Domains and Tasks](https://refivu.com/en/papers/0864e409-68d0-4d61-98fd-5ab02360285a-don-t-stop-pretraining-adapt-language-models-to.md)
- [Adversarial Autoencoders](https://refivu.com/en/papers/8e20edb4-f017-4781-86f9-478c6059260f-adversarial-autoencoders.md)
- [Abstractive Text Summarization Using Sequence-to-Sequence RNNs and Beyond](https://refivu.com/en/papers/7a55aaf9-654e-4a97-8efc-d0b4a9fccb7a-abstractive-text-summarization-using-sequence-to-sequence.md)
- [A Comprehensive Overview of Large Language Models](https://refivu.com/en/papers/4e2425c0-8669-49f7-80be-dd35ce0a70b2-a-comprehensive-overview-of-large-language-models.md)

## Terms in this paper

- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [Semantic segmentation](https://refivu.com/en/terms/00dfce7ec404-semantic-segmentation)
- [Top-1 accuracy](https://refivu.com/en/terms/653c0b9eaa58-top-1-accuracy)
- [BERT](https://refivu.com/en/terms/45b639a1d317-bert)
- [Image classification](https://refivu.com/en/terms/e15c43f3bb32-image-classification)
- [ADE20K](https://refivu.com/en/terms/5adea765479c-ade20k)
- [ImageNet-1K](https://refivu.com/en/terms/d8d6444bd460-imagenet-1k)
- [masked language modeling](https://refivu.com/en/terms/5df1a60d4f18-masked-language-modeling)
- [DeiT](https://refivu.com/en/terms/24b9f164881b-deit)
- [ViT](https://refivu.com/en/terms/c041b72c53b8-vit)
- [DINO](https://refivu.com/en/terms/1dfe38658e15-dino)
- [ImageNet-22K](https://refivu.com/en/terms/8baf67d92a09-imagenet-22k)
- [BEIT](https://refivu.com/en/terms/2a58ca75614c-beit)
- [MoCo v3](https://refivu.com/en/terms/b81d8ecb4cf2-moco-v3)
- [SETR-PUP](https://refivu.com/en/terms/5f8fc9ec8c79-setr-pup)
- [visual tokens](https://refivu.com/en/terms/25cccc1b82d2-visual-tokens)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/de9cda9f-90f4-48cc-9bb3-e6f03f9683c7-beit-bert-pre-training-of-image-transformers)
