An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale

一张图像等价于 16×16 个词:面向大规模图像识别的 Transformer —— 中英对照版
Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby  ·  Google Research, Brain Team
ICLR 2021 arXiv:2010.11929v2 左栏 = 英文原文 · 右栏 = 中文翻译

摘要 / Abstract

EN

While the Transformer architecture has become the de-facto standard for natural language processing tasks, its applications to computer vision remain limited. In vision, attention is either applied in conjunction with convolutional networks, or used to replace certain components of convolutional networks while keeping their overall structure in place. We show that this reliance on CNNs is not necessary and a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks. When pre-trained on large amounts of data and transferred to multiple mid-sized or small image recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc.), Vision Transformer (ViT) attains excellent results compared to state-of-the-art convolutional networks while requiring substantially fewer computational resources to train.

尽管 Transformer 架构已成为自然语言处理任务事实上的标准,它在计算机视觉中的应用仍然有限。在视觉领域,注意力机制要么与卷积网络结合使用,要么用来替换卷积网络中的某些组件、但保留其整体结构。我们证明这种对 CNN 的依赖并非必需——将纯 Transformer 直接应用于图像块(patch)序列,就能在图像分类任务上取得非常好的效果。当在海量数据上预训练、再迁移到多个中等规模或小型图像识别基准(ImageNet、CIFAR-100、VTAB 等)时,Vision Transformer(ViT)相比最先进的卷积网络取得了出色的结果,同时训练所需的计算资源大幅减少。

EN

1Fine-tuning code and pre-trained models are available at github.com/google-research/vision_transformer

1 微调代码与预训练模型见 github.com/google-research/vision_transformer。

1 引言 / 1 Introduction

EN

Self-attention-based architectures, in particular Transformers (Vaswani et al., 2017), have become the model of choice in natural language processing (NLP). The dominant approach is to pre-train on a large text corpus and then fine-tune on a smaller task-specific dataset (Devlin et al., 2019). Thanks to Transformers' computational efficiency and scalability, it has become possible to train models of unprecedented size, with over 100B parameters (Brown et al., 2020; Lepikhin et al., 2020). With the models and datasets growing, there is still no sign of saturating performance.

基于自注意力(self-attention)的架构,尤其是 Transformer(Vaswani et al., 2017),已成为自然语言处理(NLP)领域的首选模型。主流做法是先在大规模文本语料上预训练,再在较小的任务专用数据集上微调(Devlin et al., 2019)。得益于 Transformer 的计算效率与可扩展性,训练规模空前的模型成为可能——参数量已超过 1000 亿(Brown et al., 2020; Lepikhin et al., 2020)。而且随着模型和数据集不断增长,性能仍未出现饱和迹象。

EN

In computer vision, however, convolutional architectures remain dominant (LeCun et al., 1989; Krizhevsky et al., 2012; He et al., 2016). Inspired by NLP successes, multiple works try combining CNN-like architectures with self-attention (Wang et al., 2018; Carion et al., 2020), some replacing the convolutions entirely (Ramachandran et al., 2019; Wang et al., 2020a). The latter models, while theoretically efficient, have not yet been scaled effectively on modern hardware accelerators due to the use of specialized attention patterns. Therefore, in large-scale image recognition, classic ResNet-like architectures are still state of the art (Mahajan et al., 2018; Xie et al., 2020; Kolesnikov et al., 2020).

然而在计算机视觉领域,卷积架构依然占据统治地位(LeCun et al., 1989; Krizhevsky et al., 2012; He et al., 2016)。受 NLP 成功的启发,多项工作尝试将类 CNN 架构与自注意力结合(Wang et al., 2018; Carion et al., 2020),也有工作尝试完全取代卷积(Ramachandran et al., 2019; Wang et al., 2020a)。后者虽然在理论上高效,但由于使用了特殊的注意力模式,尚未能在现代硬件加速器上有效扩展。因此在大规模图像识别任务上,经典的 ResNet 类架构仍是当时的最优方案(Mahajan et al., 2018; Xie et al., 2020; Kolesnikov et al., 2020)。

EN

Inspired by the Transformer scaling successes in NLP, we experiment with applying a standard Transformer directly to images, with the fewest possible modifications. To do so, we split an image into patches and provide the sequence of linear embeddings of these patches as an input to a Transformer. Image patches are treated the same way as tokens (words) in an NLP application. We train the model on image classification in supervised fashion.

受 Transformer 在 NLP 中扩展成功的启发,我们尝试以尽可能少的改动,将标准 Transformer 直接应用于图像:把图像切分为小块(patch),将这些 patch 的线性嵌入序列作为 Transformer 的输入。图像 patch 的处理方式与 NLP 中的 token(词)完全相同。我们在图像分类任务上以有监督方式训练该模型。

EN

When trained on mid-sized datasets such as ImageNet without strong regularization, these models yield modest accuracies of a few percentage points below ResNets of comparable size. This seemingly discouraging outcome may be expected: Transformers lack some of the inductive biases inherent to CNNs, such as translation equivariance and locality, and therefore do not generalize well when trained on insufficient amounts of data.

当在 ImageNet 这类中等规模数据集上训练、且不使用强正则化时,这些模型的精度比同等规模的 ResNet 低若干百分点。这个看似令人沮丧的结果其实在意料之中:Transformer 缺少 CNN 固有的某些归纳偏置(inductive bias)——例如平移等变性(translation equivariance)局部性(locality)——因此在数据量不足时泛化能力较差。

EN

However, the picture changes if the models are trained on larger datasets (14M-300M images). We find that large scale training trumps inductive bias. Our Vision Transformer (ViT) attains excellent results when pre-trained at sufficient scale and transferred to tasks with fewer datapoints. When pre-trained on the public ImageNet-21k dataset or the in-house JFT-300M dataset, ViT approaches or beats state of the art on multiple image recognition benchmarks. In particular, the best model reaches the accuracy of 88.55% on ImageNet, 90.72% on ImageNet-ReaL, 94.55% on CIFAR-100, and 77.63% on the VTAB suite of 19 tasks.

但如果在更大数据集(1400 万–3 亿张图像)上训练,情况就完全不同了。我们发现大规模训练胜过归纳偏置。我们的 Vision Transformer(ViT)在足够大的规模上预训练后,迁移到数据点较少的任务时能取得优异结果。在公开的 ImageNet-21k 数据集或内部 JFT-300M 数据集上预训练后,ViT 在多个图像识别基准上逼近或超越了当时的最优水平:最佳模型在 ImageNet 上达到 88.55%、ImageNet-ReaL 上 90.72%、CIFAR-100 上 94.55%、19 个任务的 VTAB 套件上 77.63%。

2 相关工作 / 2 Related Work

EN

Transformers were proposed by Vaswani et al. (2017) for machine translation, and have since become the state of the art method in many NLP tasks. Large Transformer-based models are often pre-trained on large corpora and then fine-tuned for the task at hand: BERT (Devlin et al., 2019) uses a denoising self-supervised pre-training task, while the GPT line of work uses language modeling as its pre-training task (Radford et al., 2018; 2019; Brown et al., 2020).

Transformer 由 Vaswani et al.(2017)为机器翻译提出,此后成为众多 NLP 任务的最优方法。大型 Transformer 模型通常先在大语料上预训练、再针对具体任务微调:BERT(Devlin et al., 2019)使用去噪自监督预训练任务,而 GPT 系列工作以语言建模作为预训练任务(Radford et al., 2018; 2019; Brown et al., 2020)。

EN

Naive application of self-attention to images would require that each pixel attends to every other pixel. With quadratic cost in the number of pixels, this does not scale to realistic input sizes. Thus, to apply Transformers in the context of image processing, several approximations have been tried in the past. Parmar et al. (2018) applied the self-attention only in local neighborhoods for each query pixel instead of globally. Such local multi-head dot-product self attention blocks can completely replace convolutions (Hu et al., 2019; Ramachandran et al., 2019; Zhao et al., 2020). In a different line of work, Sparse Transformers (Child et al., 2019) employ scalable approximations to global self-attention in order to be applicable to images. An alternative way to scale attention is to apply it in blocks of varying sizes (Weissenborn et al., 2019), in the extreme case only along individual axes (Ho et al., 2019; Wang et al., 2020a). Many of these specialized attention architectures demonstrate promising results on computer vision tasks, but require complex engineering to be implemented efficiently on hardware accelerators.

将自注意力朴素地应用于图像,需要每个像素都关注其余所有像素——计算量随像素数呈二次方增长,无法扩展到真实输入尺寸。因此过去已有多种近似方案:Parmar et al.(2018)只对每个查询像素的局部邻域施加自注意力而非全局注意力,这类局部多头点积自注意力块可以完全替代卷积(Hu et al., 2019; Ramachandran et al., 2019; Zhao et al., 2020)。另一条路线是稀疏 Transformer(Sparse Transformer)(Child et al., 2019),使用可扩展的近似来逼近全局自注意力以适用于图像。还有工作按不同大小的块施加注意力(Weissenborn et al., 2019),极端情况下只沿单个轴进行(Ho et al., 2019; Wang et al., 2020a)。这些专用注意力架构在视觉任务上展现出不错的效果,但需要复杂的工程才能在硬件加速器上高效实现。

EN

Most related to ours is the model of Cordonnier et al. (2020), which extracts patches of size 2×2 from the input image and applies full self-attention on top. This model is very similar to ViT, but our work goes further to demonstrate that large scale pre-training makes vanilla transformers competitive with (or even better than) state-of-the-art CNNs. Moreover, Cordonnier et al. (2020) use a small patch size of 2×2 pixels, which makes the model applicable only to small-resolution images, while we handle medium-resolution images as well.

与我们的工作最相关的是 Cordonnier et al.(2020)的模型:它从输入图像中提取 2×2 大小的 patch,再在其上施加完整的自注意力。该模型与 ViT 非常相似,但我们的工作更进一步,证明了大规模预训练能让"原味"Transformer 与最先进 CNN 相竞争(甚至更强)。此外,Cordonnier et al.(2020)使用 2×2 像素的小 patch,只适用于小分辨率图像,而我们的方法同样适用于中等分辨率图像。

EN

There has also been a lot of interest in combining convolutional neural networks (CNNs) with forms of self-attention, e.g. by augmenting feature maps for image classification (Bello et al., 2019) or by further processing the output of a CNN using self-attention, e.g. for object detection (Hu et al., 2018; Carion et al., 2020), video processing (Wang et al., 2018; Sun et al., 2019), image classification (Wu et al., 2020), unsupervised object discovery (Locatello et al., 2020), or unified text-vision tasks (Chen et al., 2020c; Lu et al., 2019; Li et al., 2019).

将卷积神经网络(CNN)与某种形式的自注意力结合的研究也有很多,例如为图像分类增强特征图(Bello et al., 2019),或用自注意力进一步处理 CNN 的输出——用于目标检测(Hu et al., 2018; Carion et al., 2020)、视频处理(Wang et al., 2018; Sun et al., 2019)、图像分类(Wu et al., 2020)、无监督目标发现(Locatello et al., 2020)以及统一的文本-视觉任务(Chen et al., 2020c; Lu et al., 2019; Li et al., 2019)。

EN

Another recent related model is image GPT (iGPT) (Chen et al., 2020a), which applies Transformers to image pixels after reducing image resolution and color space. The model is trained in an unsupervised fashion as a generative model, and the resulting representation can then be fine-tuned or probed linearly for classification performance, achieving a maximal accuracy of 72% on ImageNet.

另一个相关的近期模型是 image GPT(iGPT)(Chen et al., 2020a),它在降低图像分辨率和色彩空间后把 Transformer 应用于图像像素。该模型以无监督方式作为生成模型训练,所得表征可经微调或线性探测用于分类,在 ImageNet 上最高达到 72% 的精度。

EN

Our work adds to the increasing collection of papers that explore image recognition at larger scales than the standard ImageNet dataset. The use of additional data sources allows to achieve state-of-the-art results on standard benchmarks (Mahajan et al., 2018; Touvron et al., 2019; Xie et al., 2020). Moreover, Sun et al. (2017) study how CNN performance scales with dataset size, and Kolesnikov et al. (2020); Djolonga et al. (2020) perform an empirical exploration of CNN transfer learning from large scale datasets such as ImageNet-21k and JFT-300M. We focus on these two latter datasets as well, but train Transformers instead of ResNet-based models used in prior works.

我们的工作也加入了探索比标准 ImageNet 更大规模图像识别的论文行列。利用额外数据源可以在标准基准上取得最优结果(Mahajan et al., 2018; Touvron et al., 2019; Xie et al., 2020)。此外,Sun et al.(2017)研究了 CNN 性能如何随数据集规模扩展,Kolesnikov et al.(2020)与 Djolonga et al.(2020)则实证探索了从 ImageNet-21k、JFT-300M 等大规模数据集出发的 CNN 迁移学习。我们同样关注这两个数据集,但训练的是 Transformer 而非先前工作所用的 ResNet 类模型。

3 方法 / 3 Method

EN

In model design we follow the original Transformer (Vaswani et al., 2017) as closely as possible. An advantage of this intentionally simple setup is that scalable NLP Transformer architectures – and their efficient implementations – can be used almost out of the box.

在模型设计上,我们尽可能贴近原始 Transformer(Vaswani et al., 2017)。这种刻意保持简单的设计有个好处:可扩展的 NLP Transformer 架构及其高效实现几乎可以开箱即用。

fig1_p3.jpg
Figure 1: Model overview. We split an image into fixed-size patches, linearly embed each of them, add position embeddings, and feed the resulting sequence of vectors to a standard Transformer encoder. In order to perform classification, we use the standard approach of adding an extra learnable "classification token" to the sequence. The illustration of the Transformer encoder was inspired by Vaswani et al. (2017).
图 1(模型总览,务必对照原文查看):将图像切分为固定大小的 patch,对每个 patch 做线性嵌入并加上位置嵌入,把得到的向量序列送入标准 Transformer 编码器。为完成分类,在序列最前面加一个可学习的「分类 token」([class])。编码器由「多头注意力 MSA + MLP」层堆叠而成,每层前有 LayerNorm、后有残差连接。最终用分类 token 的输出接 MLP 头预测类别(示例图中预测为 Bird)。

3.1 Vision Transformer(ViT)

EN

An overview of the model is depicted in Figure 1. The standard Transformer receives as input a 1D sequence of token embeddings. To handle 2D images, we reshape the image x ∈ ℝH×W×C into a sequence of flattened 2D patches xp ∈ ℝN×(P²·C), where (H, W) is the resolution of the original image, C is the number of channels, (P, P) is the resolution of each image patch, and N = HW/P² is the resulting number of patches, which also serves as the effective input sequence length for the Transformer. The Transformer uses constant latent vector size D through all of its layers, so we flatten the patches and map to D dimensions with a trainable linear projection (Eq. 1). We refer to the output of this projection as the patch embeddings.

模型总览见图 1。标准 Transformer 接收一维 token 嵌入序列作为输入。为处理二维图像,我们将图像 x ∈ ℝH×W×C 重排为展平的二维 patch 序列 xp ∈ ℝN×(P²·C),其中 (H, W) 是原始图像分辨率,C 是通道数,(P, P) 是每个图像 patch 的分辨率,N = HW/P² 是得到的 patch 数量——它同时也是 Transformer 的有效输入序列长度。由于 Transformer 在其所有层中使用固定的隐向量维度 D,我们先把 patch 展平,再用可训练的线性投影映射到 D 维(式 1)。这一投影的输出称为patch 嵌入(patch embeddings)

EN

Similar to BERT's [class] token, we prepend a learnable embedding to the sequence of embedded patches (z⁰₀ = xclass), whose state at the output of the Transformer encoder (z⁰L) serves as the image representation y (Eq. 4). Both during pre-training and fine-tuning, a classification head is attached to z⁰L. The classification head is implemented by a MLP with one hidden layer at pre-training time and by a single linear layer at fine-tuning time.

类似于 BERT 的 [class] token,我们在嵌入 patch 序列的开头拼上一个可学习嵌入(z⁰₀ = xclass),它在 Transformer 编码器输出端的状态(z⁰L)用作图像表征 y(式 4)。无论预训练还是微调,分类头都接在 z⁰L 上:预训练时分类头由带一个隐藏层的 MLP 实现,微调时则换成单个线性层。

EN

Position embeddings are added to the patch embeddings to retain positional information. We use standard learnable 1D position embeddings, since we have not observed significant performance gains from using more advanced 2D-aware position embeddings (Appendix D.4). The resulting sequence of embedding vectors serves as input to the encoder.

位置嵌入(position embeddings)被加到 patch 嵌入上以保留位置信息。我们使用标准的可学习一维位置嵌入,因为并未观察到更先进的二维感知位置嵌入带来显著收益(附录 D.4)。最终得到的嵌入向量序列作为编码器的输入。

EN

The Transformer encoder (Vaswani et al., 2017) consists of alternating layers of multiheaded self-attention (MSA, see Appendix A) and MLP blocks (Eq. 2, 3). Layernorm (LN) is applied before every block, and residual connections after every block (Wang et al., 2019; Baevski & Auli, 2019). The MLP contains two layers with a GELU non-linearity.

Transformer 编码器(Vaswani et al., 2017)由多头自注意力(MSA)层与 MLP 块交替构成(式 2、3)。每个块之前应用层归一化(LayerNorm, LN),每个块之后使用残差连接(Wang et al., 2019; Baevski & Auli, 2019)。MLP 包含两个层,使用 GELU 非线性。

z₀ = [xclass; x¹pE; x²pE; …; xNpE] + Epos,  E ∈ ℝ(P²·C)×D,Epos ∈ ℝ(N+1)×D (1)
z′ = MSA(LN(zℓ−1)) + zℓ−1,  ℓ = 1…L (2)
z = MLP(LN(z′)) + z′,  ℓ = 1…L (3)
y = LN(z⁰L) (4)

归纳偏置 / Inductive bias

EN

We note that Vision Transformer has much less image-specific inductive bias than CNNs. In CNNs, locality, two-dimensional neighborhood structure, and translation equivariance are baked into each layer throughout the whole model. In ViT, only MLP layers are local and translationally equivariant, while the self-attention layers are global. The two-dimensional neighborhood structure is used very sparingly: in the beginning of the model by cutting the image into patches and at fine-tuning time for adjusting the position embeddings for images of different resolution (as described below). Other than that, the position embeddings at initialization time carry no information about the 2D positions of the patches and all spatial relations between the patches have to be learned from scratch.

我们指出,Vision Transformer 的图像专用归纳偏置远少于 CNN。在 CNN 中,局部性、二维邻域结构和平移等变性被"烘焙"进贯穿整个模型的每一层里;而在 ViT 中,只有 MLP 层是局部且平移等变的,自注意力层则是全局的。二维邻域结构信息只在两处以极简方式使用:模型开始时把图像切成 patch,以及微调时针对不同分辨率图像调整位置嵌入(见下文)。除此之外,位置嵌入在初始化时不携带任何关于 patch 二维位置的信息,patch 之间的所有空间关系都必须从头学起。

混合架构 / Hybrid Architecture

EN

As an alternative to raw image patches, the input sequence can be formed from feature maps of a CNN (LeCun et al., 1989). In this hybrid model, the patch embedding projection E (Eq. 1) is applied to patches extracted from a CNN feature map. As a special case, the patches can have spatial size 1x1, which means that the input sequence is obtained by simply flattening the spatial dimensions of the feature map and projecting to the Transformer dimension. The classification input embedding and position embeddings are added as described above.

作为原始图像 patch 的替代方案,输入序列也可以由 CNN 的特征图(LeCun et al., 1989)构成。在这种混合模型中,patch 嵌入投影 E(式 1)被应用于从 CNN 特征图中提取的 patch。特例:patch 空间尺寸可以是 1×1,即直接把特征图的空间维度展平并投影到 Transformer 维度上得到输入序列。分类输入嵌入与位置嵌入的添加方式与上述相同。

3.2 微调与更高分辨率 / Fine-tuning and Higher Resolution

EN

Typically, we pre-train ViT on large datasets, and fine-tune to (smaller) downstream tasks. For this, we remove the pre-trained prediction head and attach a zero-initialized D×K feedforward layer, where K is the number of downstream classes. It is often beneficial to fine-tune at higher resolution than pre-training (Touvron et al., 2019; Kolesnikov et al., 2020). When feeding images of higher resolution, we keep the patch size the same, which results in a larger effective sequence length. The Vision Transformer can handle arbitrary sequence lengths (up to memory constraints), however, the pre-trained position embeddings may no longer be meaningful. We therefore perform 2D interpolation of the pre-trained position embeddings, according to their location in the original image. Note that this resolution adjustment and patch extraction are the only points at which an inductive bias about the 2D structure of the images is manually injected into the Vision Transformer.

通常我们先在大数据集上预训练 ViT,再微调到(较小的)下游任务。做法是:移除预训练的预测头,接上一个零初始化的 D×K 前馈层,K 为下游任务类别数。以高于预训练的分辨率进行微调往往是有益的(Touvron et al., 2019; Kolesnikov et al., 2020)。喂入更高分辨率的图像时,我们保持 patch 大小不变,于是有效序列长度变长。Vision Transformer 可以处理任意序列长度(受内存限制),但预训练得到的位置嵌入可能不再有意义。因此我们根据预训练位置嵌入在原始图像中的位置,对它们做二维插值。注意:这一分辨率调整与 patch 提取,是仅有的两处人工向 Vision Transformer 注入图像二维结构先验的地方。

4 实验 / 4 Experiments

EN

We evaluate the representation learning capabilities of ResNet, Vision Transformer (ViT), and the hybrid. To understand the data requirements of each model, we pre-train on datasets of varying size and evaluate many benchmark tasks. When considering the computational cost of pre-training the model, ViT performs very favourably, attaining state of the art on most recognition benchmarks at a lower pre-training cost. Lastly, we perform a small experiment using self-supervision, and show that self-supervised ViT holds promise for the future.

我们评估了 ResNet、Vision Transformer(ViT)以及混合模型的表征学习能力。为理解各模型的数据需求,我们在不同规模的数据集上预训练,并在大量基准任务上评估。若把预训练的计算成本考虑在内,ViT 表现非常有竞争力:以更低的预训练成本在大多数识别基准上达到最优。最后,我们做了一个小规模自监督实验,展示自监督 ViT 的未来潜力。

4.1 实验设置 / Setup

EN

Datasets. To explore model scalability, we use the ILSVRC-2012 ImageNet dataset with 1k classes and 1.3M images (we refer to it as ImageNet in what follows), its superset ImageNet-21k with 21k classes and 14M images (Deng et al., 2009), and JFT (Sun et al., 2017) with 18k classes and 303M high-resolution images. We de-duplicate the pre-training datasets w.r.t. the test sets of the downstream tasks following Kolesnikov et al. (2020). We transfer the models trained on these dataset to several benchmark tasks: ImageNet on the original validation labels and the cleaned-up ReaL labels (Beyer et al., 2020), CIFAR-10/100 (Krizhevsky, 2009), Oxford-IIIT Pets (Parkhi et al., 2012), and Oxford Flowers-102 (Nilsback & Zisserman, 2008). For these datasets, pre-processing follows Kolesnikov et al. (2020).

数据集。为探索模型可扩展性,我们使用了三个规模递增的数据集预训练:ILSVRC-2012 ImageNet(1k 类、130 万张图,下文简称 ImageNet)、它的超集 ImageNet-21k(21k 类、1400 万张图,Deng et al., 2009),以及 JFT(Sun et al., 2017,18k 类、3.03 亿张高分辨率图)。按照 Kolesnikov et al.(2020)的做法,我们针对下游任务测试集对预训练数据做了去重。随后把这些模型迁移到多个基准:ImageNet(原始验证标签与清洗后的 ReaL 标签,Beyer et al., 2020)、CIFAR-10/100(Krizhevsky, 2009)、Oxford-IIIT Pets(Parkhi et al., 2012)、Oxford Flowers-102(Nilsback & Zisserman, 2008)。预处理遵循 Kolesnikov et al.(2020)。

EN

We also evaluate on the 19-task VTAB classification suite (Zhai et al., 2019b). VTAB evaluates low-data transfer to diverse tasks, using 1 000 training examples per task. The tasks are divided into three groups: Natural – tasks like the above, Pets, CIFAR, etc. Specialized – medical and satellite imagery, and Structured – tasks that require geometric understanding like localization.

我们还在 19 任务的 VTAB 分类套件上评估(Zhai et al., 2019b):每个任务只用 1000 个训练样本,考察低数据迁移能力。任务分为三组——Natural(自然图像,如上述 Pets、CIFAR 等)、Specialized(医学与卫星图像)、Structured(需要几何理解的任务,如定位)。

EN

Model Variants. We base ViT configurations on those used for BERT (Devlin et al., 2019), as summarized in Table 1. The "Base" and "Large" models are directly adopted from BERT and we add the larger "Huge" model. In what follows we use brief notation to indicate the model size and the input patch size: for instance, ViT-L/16 means the "Large" variant with 16×16 input patch size. Note that the Transformer's sequence length is inversely proportional to the square of the patch size, thus models with smaller patch size are computationally more expensive.

模型变体。ViT 的配置沿用 BERT(Devlin et al., 2019)的设定,见表 1。"Base"与"Large"直接取自 BERT,另加了更大的"Huge"。下文用简写同时标明模型规模与输入 patch 大小:例如 ViT-L/16 表示 "Large" 变体、16×16 输入 patch。注意序列长度与 patch 大小的平方成反比,因此 patch 越小、计算越昂贵。

Model 模型Layers 层数Hidden size DMLP sizeHeads 头数Params 参数量
ViT-Base1276830721286M
ViT-Large241024409616307M
ViT-Huge321280512016632M

Table 1 / 表 1:Details of Vision Transformer model variants. — Vision Transformer 各变体的详细配置。

EN

For the baseline CNNs, we use ResNet (He et al., 2016), but replace the Batch Normalization layers (Ioffe & Szegedy, 2015) with Group Normalization (Wu & He, 2018), and used standardized convolutions (Qiao et al., 2019). These modifications improve transfer (Kolesnikov et al., 2020), and we denote the modified model "ResNet (BiT)". For the hybrids, we feed the intermediate feature maps into ViT with patch size of one "pixel". To experiment with different sequence lengths, we either (i) take the output of stage 4 of a regular ResNet50 or (ii) remove stage 4, place the same number of layers in stage 3 (keeping the total number of layers), and take the output of this extended stage 3. Option (ii) results in a 4x longer sequence length, and a more expensive ViT model.

基线 CNN。我们使用 ResNet(He et al., 2016),但把批归一化(Batch Normalization)替换为组归一化(Group Normalization)(Wu & He, 2018),并采用标准化卷积(Qiao et al., 2019)。这些修改能改善迁移效果(Kolesnikov et al., 2020),我们把修改后的模型记作 "ResNet (BiT)"。对于混合模型,我们把中间特征图喂给 patch 大小为 1"像素"的 ViT。为试验不同序列长度:① 取常规 ResNet50 第 4 阶段的输出;② 去掉第 4 阶段、把相同数量的层放进第 3 阶段(总层数不变),取加长后第 3 阶段的输出——这样序列长度变为 4 倍,ViT 部分也更昂贵。

EN

Training & Fine-tuning. We train all models, including ResNets, using Adam (Kingma & Ba, 2015) with β₁ = 0.9, β₂ = 0.999, a batch size of 4096 and apply a high weight decay of 0.1, which we found to be useful for transfer of all models (Appendix D.1 shows that, in contrast to common practices, Adam works slightly better than SGD for ResNets in our setting). We use a linear learning rate warmup and decay, see Appendix B.1 for details. For fine-tuning we use SGD with momentum, batch size 512, for all models, see Appendix B.1.1. For ImageNet results in Table 2, we fine-tuned at higher resolution: 512 for ViT-L/16 and 518 for ViT-H/14, and also used Polyak & Juditsky (1992) averaging with a factor of 0.9999 (Ramachandran et al., 2019; Wang et al., 2020b).

训练与微调。所有模型(包括 ResNet)都用 Adam(Kingma & Ba, 2015)训练:β₁=0.9、β₂=0.999,batch size 4096,并施加 0.1 的高权重衰减——我们发现这对所有模型的迁移都有帮助(附录 D.1 表明,与常规做法相反,在我们的设定下 Adam 训练 ResNet 比 SGD 略好)。学习率采用线性 warmup 与衰减,详见附录 B.1。微调时所有模型均使用带动量的 SGD、batch size 512,见附录 B.1.1。表 2 中的 ImageNet 结果在更高分辨率下微调:ViT-L/16 用 512,ViT-H/14 用 518,并使用了 Polyak & Juditsky(1992)平均(系数 0.9999)。

EN

Metrics. We report results on downstream datasets either through few-shot or fine-tuning accuracy. Fine-tuning accuracies capture the performance of each model after fine-tuning it on the respective dataset. Few-shot accuracies are obtained by solving a regularized least-squares regression problem that maps the (frozen) representation of a subset of training images to {−1, 1}K target vectors. This formulation allows us to recover the exact solution in closed form. Though we mainly focus on fine-tuning performance, we sometimes use linear few-shot accuracies for fast on-the-fly evaluation where fine-tuning would be too costly.

评价指标。下游数据集的结果以少样本(few-shot)精度或微调精度报告。微调精度反映模型在该数据集上微调后的表现;少样本精度则通过求解一个正则化最小二乘回归问题得到——把(冻结的)训练图像子集表征映射到 {−1, 1}K 目标向量,该形式允许闭式精确求解。虽然我们主要关注微调性能,但有时会用线性少样本精度做快速的在线评估,因为完整微调太昂贵。

4.2 与最先进方法的对比 / Comparison to State of the Art

EN

We first compare our largest models – ViT-H/14 and ViT-L/16 – to state-of-the-art CNNs from the literature. The first comparison point is Big Transfer (BiT) (Kolesnikov et al., 2020), which performs supervised transfer learning with large ResNets. The second is Noisy Student (Xie et al., 2020), which is a large EfficientNet trained using semi-supervised learning on ImageNet and JFT-300M with the labels removed. Currently, Noisy Student is the state of the art on ImageNet and BiT-L on the other datasets reported here. All models were trained on TPUv3 hardware, and we report the number of TPUv3-core-days taken to pre-train each of them, that is, the number of TPU v3 cores (2 per chip) used for training multiplied by the training time in days.

我们首先把最大的两个模型——ViT-H/14 与 ViT-L/16——与文献中最先进的 CNN 对比。第一个对手是 Big Transfer(BiT)(Kolesnikov et al., 2020),用大型 ResNet 做有监督迁移学习;第二个是 Noisy Student(Xie et al., 2020),是在 ImageNet 和去掉标签的 JFT-300M 上以半监督方式训练的大型 EfficientNet。当时 Noisy Student 是 ImageNet 上的最优,BiT-L 是本文其他数据集上的最优。所有模型都在 TPUv3 硬件上训练,我们报告各自的预训练消耗(TPUv3-core-days,即所用 TPUv3 核数×训练天数)。

数据集 DatasetViT-H/14
(JFT-300M)
ViT-L/16
(JFT-300M)
ViT-L/16
(ImageNet-21k)
BiT-L
(ResNet152x4)
Noisy Student
(EfficientNet-L2)
ImageNet88.55±0.0487.76±0.0385.30±0.0287.54±0.0288.4/88.5*
ImageNet ReaL90.72±0.0590.54±0.0388.62±0.0590.5490.55
CIFAR-1099.50±0.0699.42±0.0399.15±0.0399.37±0.06
CIFAR-10094.55±0.0493.90±0.0593.25±0.0593.51±0.08
Oxford-IIIT Pets97.56±0.0397.32±0.1194.67±0.1596.62±0.23
Oxford Flowers-10299.68±0.0299.74±0.0099.61±0.0299.63±0.03
VTAB(19 tasks)77.63±0.2376.28±0.4672.72±0.2176.29±1.70
TPUv3-core-days2.5k0.68k0.23k9.9k12.3k

Table 2 / 表 2:Comparison with state of the art on popular image classification benchmarks. We report mean and standard deviation of the accuracies, averaged over three fine-tuning runs. Vision Transformer models pre-trained on the JFT-300M dataset outperform ResNet-based baselines on all datasets, while taking substantially less computational resources to pre-train. ViT pre-trained on the smaller public ImageNet-21k dataset performs well too. *Slightly improved 88.5% result reported in Touvron et al. (2020). —— 在主流图像分类基准上与最先进方法的对比。精度为三次微调运行的均值±标准差。JFT-300M 预训练的 ViT 在所有数据集上超越 ResNet 基线,预训练计算量大为减少;ImageNet-21k 预训练的 ViT 表现也不错。*88.5% 为 Touvron et al. (2020) 报告的改进结果。

EN

Table 2 shows the results. The smaller ViT-L/16 model pre-trained on JFT-300M outperforms BiT-L (which is pre-trained on the same dataset) on all tasks, while requiring substantially less computational resources to train. The larger model, ViT-H/14, further improves the performance, especially on the more challenging datasets – ImageNet, CIFAR-100, and the VTAB suite. Interestingly, this model still took substantially less compute to pre-train than prior state of the art. However, we note that pre-training efficiency may be affected not only by the architecture choice, but also other parameters, such as training schedule, optimizer, weight decay, etc. We provide a controlled study of performance vs. compute for different architectures in Section 4.4. Finally, the ViT-L/16 model pre-trained on the public ImageNet-21k dataset performs well on most datasets too, while taking fewer resources to pre-train: it could be trained using a standard cloud TPUv3 with 8 cores in approximately 30 days.

表 2 显示:在 JFT-300M 上预训练的较小模型 ViT-L/16,在所有任务上都超过了在同一数据集预训练的 BiT-L,而所需计算资源少得多;更大的 ViT-H/14 进一步提升了性能,尤其在更有挑战性的数据集上——ImageNet、CIFAR-100 与 VTAB 套件。有趣的是,它的预训练计算量仍远低于先前的最优方法。不过我们指出,预训练效率不仅受架构选择影响,也受训练日程、优化器、权重衰减等其他因素影响,第 4.4 节给出了受控的性能-算力对比研究。此外,在公开 ImageNet-21k 上预训练的 ViT-L/16 在多数数据集上表现也不错,而预训练资源更省:用一台标准的 8 核云 TPUv3 大约 30 天即可完成训练。

fig2_p6.jpg
Figure 2: Breakdown of VTAB performance in Natural, Specialized, and Structured task groups.
图 2:VTAB 任务按 Natural / Specialized / Structured 三组分解的性能对比,对比对象包括 BiT、VIVI(ResNet 在 ImageNet 与 Youtube 上协同训练,Tschannen et al., 2020)和 S4L(ImageNet 上有监督+半监督学习,Zhai et al., 2019a)。ViT-H/14 在 Natural 和 Structured 任务组上超过 BiT-R152x4 及其他方法;Specialized 组中前两名表现接近。
EN

Figure 2 decomposes the VTAB tasks into their respective groups, and compares to previous SOTA methods on this benchmark: BiT, VIVI – a ResNet co-trained on ImageNet and Youtube (Tschannen et al., 2020), and S4L – supervised plus semi-supervised learning on ImageNet (Zhai et al., 2019a). ViT-H/14 outperforms BiT-R152x4, and other methods, on the Natural and Structured tasks. On the Specialized the performance of the top two models is similar.

图 2 把 VTAB 任务按组分解,并与该基准上先前的最优方法对比:BiT、VIVI(在 ImageNet 与 Youtube 上协同训练的 ResNet,Tschannen et al., 2020)、S4L(ImageNet 上有监督+半监督学习,Zhai et al., 2019a)。ViT-H/14 在 Natural 与 Structured 任务上超过 BiT-R152x4 及其他方法;Specialized 组中前两名表现接近。

4.3 预训练数据需求 / Pre-training Data Requirements

EN

The Vision Transformer performs well when pre-trained on a large JFT-300M dataset. With fewer inductive biases for vision than ResNets, how crucial is the dataset size? We perform two series of experiments. First, we pre-train ViT models on datasets of increasing size: ImageNet, ImageNet-21k, and JFT-300M. To boost the performance on the smaller datasets, we optimize three basic regularization parameters – weight decay, dropout, and label smoothing. Figure 3 shows the results after fine-tuning to ImageNet (results on other datasets are shown in Table 5)2. When pre-trained on the smallest dataset, ImageNet, ViT-Large models underperform compared to ViT-Base models, despite (moderate) regularization. With ImageNet-21k pre-training, their performances are similar. Only with JFT-300M, do we see the full benefit of larger models. Figure 3 also shows the performance region spanned by BiT models of different sizes. The BiT CNNs outperform ViT on ImageNet, but with the larger datasets, ViT overtakes.

Vision Transformer 在大型 JFT-300M 上预训练后表现优异。但它的视觉归纳偏置比 ResNet 少,数据集规模到底有多关键?我们做了两组实验。第一组:在规模递增的数据集(ImageNet → ImageNet-21k → JFT-300M)上预训练 ViT。为提升小数据集上的表现,我们调优了三个基本正则化参数——权重衰减、dropout 与标签平滑。图 3 展示微调到 ImageNet 后的结果(其他数据集见表 5)2。在最小的数据集 ImageNet 上预训练时,ViT-Large 不如 ViT-Base(即便加了适度的正则化);用 ImageNet-21k 预训练时,两者接近;只有用 JFT-300M,大模型的完整优势才显现出来。图 3 还画出了不同规模 BiT 模型的性能区间:在 ImageNet 上 BiT CNN 胜过 ViT,但数据集更大时 ViT 反超。

EN

2Note that the ImageNet pre-trained models are also fine-tuned, but again on ImageNet. This is because the resolution increase during fine-tuning improves the performance.

2 注意 ImageNet 预训练模型也在 ImageNet 上微调——因为微调时提高分辨率能提升性能。

fig3_p7.jpg
Figure 3: Transfer to ImageNet. While large ViT models perform worse than BiT ResNets (shaded area) when pre-trained on small datasets, they shine when pre-trained on larger datasets. Similarly, larger ViT variants overtake smaller ones as the dataset grows.
图 3:迁移到 ImageNet 的精度 vs 预训练数据集规模(ImageNet / ImageNet-21k / JFT-300M)。小数据集预训练时大型 ViT 不如 BiT ResNet(阴影区),大数据集预训练时则大放异彩;同理,随数据集增长,更大的 ViT 变体反超较小的变体。
fig4_p7.jpg
Figure 4: Linear few-shot evaluation on ImageNet versus pre-training size. ResNets perform better with smaller pre-training datasets but plateau sooner than ViT, which performs better with larger pre-training. ViT-b is ViT-B with all hidden dimensions halved.
图 4:ImageNet 线性少样本精度 vs 预训练数据量(9M/30M/90M/300M)。ResNet 在小预训练数据上更好但更早进入平台期;ViT 则在大预训练数据上更强。(ViT-b 是所有隐维度减半的 ViT-B。)
EN

Second, we train our models on random subsets of 9M, 30M, and 90M as well as the full JFT-300M dataset. We do not perform additional regularization on the smaller subsets and use the same hyper-parameters for all settings. This way, we assess the intrinsic model properties, and not the effect of regularization. We do, however, use early-stopping, and report the best validation accuracy achieved during training. To save compute, we report few-shot linear accuracy instead of full fine-tuning accuracy. Figure 4 contains the results. Vision Transformers overfit more than ResNets with comparable computational cost on smaller datasets. For example, ViT-B/32 is slightly faster than ResNet50; it performs much worse on the 9M subset, but better on 90M+ subsets. The same is true for ResNet152x2 and ViT-L/16. This result reinforces the intuition that the convolutional inductive bias is useful for smaller datasets, but for larger ones, learning the relevant patterns directly from data is sufficient, even beneficial. Overall, the few-shot results on ImageNet (Figure 4), as well as the low-data results on VTAB (Table 2) seem promising for very low-data transfer. Further analysis of few-shot properties of ViT is an exciting direction of future work.

第二组:在 JFT-300M 的随机子集(9M、30M、90M)及完整数据集上训练,不对小子集做额外正则化、所有设定使用相同超参数——以此考察模型的内在性质而非正则化的作用。我们使用早停并报告训练中达到的最佳验证精度;为省算力,报告少样本线性精度而非完整微调精度。结果见图 4:在较小数据集上,计算量相当的 Vision Transformer 比 ResNet 更容易过拟合。例如 ViT-B/32 比 ResNet50 略快,它在 9M 子集上表现差很多,但在 90M+ 子集上更好。ResNet152x2 与 ViT-L/16 的对比同样如此。这一结果强化了如下直觉:卷积归纳偏置对小数据集有用,但对大数据集而言,直接从数据中学习相关模式就足够了、甚至更有益。总体而言,ImageNet 上的少样本结果(图 4)与 VTAB 上的低数据结果(表 2)对极低数据迁移来说都很有前景。对 ViT 少样本特性的进一步分析是激动人心的未来方向。

4.4 缩放研究 / Scaling Study

EN

We perform a controlled scaling study of different models by evaluating transfer performance from JFT-300M. In this setting data size does not bottleneck the models' performances, and we assess performance versus pre-training cost of each model. The model set includes: 7 ResNets, R50x1, R50x2 R101x1, R152x1, R152x2, pre-trained for 7 epochs, plus R152x2 and R200x3 pre-trained for 14 epochs; 6 Vision Transformers, ViT-B/32, B/16, L/32, L/16, pre-trained for 7 epochs, plus L/16 and H/14 pre-trained for 14 epochs; and 5 hybrids, R50+ViT-B/32, B/16, L/32, L/16 pre-trained for 7 epochs, plus R50+ViT-L/16 pre-trained for 14 epochs (for hybrids, the number at the end of the model name stands not for the patch size, but for the total dowsampling ratio in the ResNet backbone).

我们通过从 JFT-300M 迁移评估,对不同模型做了受控的缩放研究。此设定下数据规模不会成为瓶颈,可以考察各模型「性能 vs 预训练算力」的关系。模型集合包括:7 个 ResNet(R50x1、R50x2、R101x1、R152x1、R152x2 预训练 7 个 epoch,另有 R152x2、R200x3 预训练 14 个 epoch);6 个 Vision Transformer(ViT-B/32、B/16、L/32、L/16 预训练 7 个 epoch,另有 L/16、H/14 预训练 14 个 epoch);5 个混合模型(R50+ViT-B/32、B/16、L/32、L/16 预训练 7 个 epoch,R50+ViT-L/16 预训练 14 个 epoch;混合模型名称末尾的数字不是 patch 大小,而是 ResNet 主干的总下采样倍率)。

fig5_p7.jpg
Figure 5: Performance versus pre-training compute for different architectures: Vision Transformers, ResNets, and hybrids. Vision Transformers generally outperform ResNets with the same computational budget. Hybrids improve upon pure Transformers for smaller model sizes, but the gap vanishes for larger models.
图 5:不同架构(ViT、ResNet、混合模型)的性能 vs 预训练算力(exaFLOPs)。相同计算预算下 ViT 普遍优于 ResNet;混合模型在小算力时略优于纯 Transformer,但大模型时差距消失。
EN

Figure 5 contains the transfer performance versus total pre-training compute (see Appendix D.5 for details on computational costs). Detailed results per model are provided in Table 6 in the Appendix. A few patterns can be observed. First, Vision Transformers dominate ResNets on the performance/compute trade-off. ViT uses approximately 2−4× less compute to attain the same performance (average over 5 datasets). Second, hybrids slightly outperform ViT at small computational budgets, but the difference vanishes for larger models. This result is somewhat surprising, since one might expect convolutional local feature processing to assist ViT at any size. Third, Vision Transformers appear not to saturate within the range tried, motivating future scaling efforts.

图 5 给出迁移性能与总预训练算力的关系(算力细节见附录 D.5,逐模型结果见附录表 6)。可观察到几个规律:第一,在性能/算力权衡上 Vision Transformer 全面领先 ResNet——达到同样性能,ViT 约省 2–4 倍算力(5 个数据集平均)。第二,混合模型在小算力预算下略胜 ViT,但在大模型时差距消失——这有点出乎意料,因为人们本以为卷积的局部特征处理在任何规模下都对 ViT 有帮助。第三,Vision Transformer 在所尝试的范围内没有饱和,激励着未来进一步的扩展。

4.5 检视 Vision Transformer / Inspecting Vision Transformer

fig6_p8.jpg fig7_p9.jpg
Figure 6: Representative examples of attention from the output token to the input space. See Appendix D.7 for details.  |  Figure 7: Left: Filters of the initial linear embedding of RGB values of ViT-L/32. Center: Similarity of position embeddings of ViT-L/32. Right: Size of attended area by head and network depth. See Appendix D.7 for details.
图 6:输出 token 对输入空间的代表性注意力图示例——模型关注区域与分类语义高度相关(细节见附录 D.7)。
图 7:左:ViT-L/32 初始线性嵌入的 RGB 滤波器(前 28 个主成分),酷似刻画 patch 内精细结构的低维基函数;中:ViT-L/32 位置嵌入相似度——相近的 patch 嵌入更相似,并出现行-列结构与正弦结构;右:各注意力头在各层的平均注意力距离(类比 CNN 感受野)。
EN

To begin to understand how the Vision Transformer processes image data, we analyze its internal representations. The first layer of the Vision Transformer linearly projects the flattened patches into a lower-dimensional space (Eq. 1). Figure 7 (left) shows the top principal components of the learned embedding filters. The components resemble plausible basis functions for a low-dimensional representation of the fine structure within each patch.

为了初步理解 Vision Transformer 如何处理图像数据,我们分析了它的内部表征。第一层把展平的 patch 线性投影到低维空间(式 1)。图 7(左)展示了学到的嵌入滤波器的前几个主成分:它们酷似刻画 patch 内部精细结构的低维表示的合理基函数。

EN

After the projection, a learned position embedding is added to the patch representations. Figure 7 (center) shows that the model learns to encode distance within the image in the similarity of position embeddings, i.e. closer patches tend to have more similar position embeddings. Further, the row-column structure appears; patches in the same row/column have similar embeddings. Finally, a sinusoidal structure is sometimes apparent for larger grids (Appendix D). That the position embeddings learn to represent 2D image topology explains why hand-crafted 2D-aware embedding variants do not yield improvements (Appendix D.4).

投影之后,模型把学到的位置嵌入加到 patch 表征上。图 7(中)显示:模型学会在位置嵌入的相似度中编码图像内的距离——越相近的 patch,位置嵌入越相似;而且出现了行-列结构:同一行/列的 patch 嵌入相近;大网格上有时还能看到正弦结构(附录 D)。位置嵌入自发学出了二维图像拓扑,这解释了为什么手工设计的 2D 感知嵌入变体并不带来收益(附录 D.4)。

EN

Self-attention allows ViT to integrate information across the entire image even in the lowest layers. We investigate to what degree the network makes use of this capability. Specifically, we compute the average distance in image space across which information is integrated, based on the attention weights (Figure 7, right). This "attention distance" is analogous to receptive field size in CNNs. We find that some heads attend to most of the image already in the lowest layers, showing that the ability to integrate information globally is indeed used by the model. Other attention heads have consistently small attention distances in the low layers. This highly localized attention is less pronounced in hybrid models that apply a ResNet before the Transformer (Figure 7, right), suggesting that it may serve a similar function as early convolutional layers in CNNs. Further, the attention distance increases with network depth. Globally, we find that the model attends to image regions that are semantically relevant for classification (Figure 6).

自注意力让 ViT 即使在最底层也能整合整幅图像的信息。我们考察了网络在多大程度上利用了这种能力:基于注意力权重,计算信息整合在图像空间中跨越的平均距离(图 7 右),即"注意力距离"(attention distance)——类比 CNN 的感受野(receptive field)大小。我们发现:一些注意力头在最底层就已关注图像的大部分区域,说明全局信息整合能力确实被模型利用了;另一些头在低层始终具有很小的注意力距离。这种高度局部化的注意力在"ResNet 前置"的混合模型中明显减弱(图 7 右),暗示它可能承担了与 CNN 早期卷积层类似的功能。此外,注意力距离随网络深度增加而增大。总体上,模型关注的图像区域是与分类语义相关的(图 6)。

4.6 自监督 / Self-Supervision

EN

Transformers show impressive performance on NLP tasks. However, much of their success stems not only from their excellent scalability but also from large scale self-supervised pre-training (Devlin et al., 2019; Radford et al., 2018). We also perform a preliminary exploration on masked patch prediction for self-supervision, mimicking the masked language modeling task used in BERT. With self-supervised pre-training, our smaller ViT-B/16 model achieves 79.9% accuracy on ImageNet, a significant improvement of 2% to training from scratch, but still 4% behind supervised pre-training. Appendix B.1.2 contains further details. We leave exploration of contrastive pre-training (Chen et al., 2020b; He et al., 2020; Bachman et al., 2019; Hénaff et al., 2020) to future work.

Transformer 在 NLP 任务上的惊艳表现,不仅源于出色的可扩展性,也源于大规模自监督预训练(Devlin et al., 2019; Radford et al., 2018)。我们也对掩码 patch 预测(masked patch prediction)的自监督方式做了初步探索,模仿 BERT 的掩码语言建模任务。自监督预训练后,我们较小的 ViT-B/16 在 ImageNet 上达到 79.9% 精度,比从头训练显著提升 2%,但仍落后监督预训练 4%。更多细节见附录 B.1.2。对比式预训练(Chen et al., 2020b; He et al., 2020; Bachman et al., 2019; Hénaff et al., 2020)的探索留待未来工作。

5 结论 / 5 Conclusion

EN

We have explored the direct application of Transformers to image recognition. Unlike prior works using self-attention in computer vision, we do not introduce image-specific inductive biases into the architecture apart from the initial patch extraction step. Instead, we interpret an image as a sequence of patches and process it by a standard Transformer encoder as used in NLP. This simple, yet scalable, strategy works surprisingly well when coupled with pre-training on large datasets. Thus, Vision Transformer matches or exceeds the state of the art on many image classification datasets, whilst being relatively cheap to pre-train.

我们探索了将 Transformer 直接应用于图像识别。与先前在计算机视觉中使用自注意力的工作不同,除了最初的 patch 提取步骤,我们没有向架构中引入任何图像专用的归纳偏置,而是把图像解读为 patch 序列,交给 NLP 中使用的标准 Transformer 编码器处理。这一简单而可扩展的策略,配合在大数据集上的预训练,效果出奇地好。Vision Transformer 在许多图像分类数据集上追平或超越了最优水平,同时预训练成本相对低廉。

EN

While these initial results are encouraging, many challenges remain. One is to apply ViT to other computer vision tasks, such as detection and segmentation. Our results, coupled with those in Carion et al. (2020), indicate the promise of this approach. Another challenge is to continue exploring self-supervised pre-training methods. Our initial experiments show improvement from self-supervised pre-training, but there is still large gap between self-supervised and large-scale supervised pre-training. Finally, further scaling of ViT would likely lead to improved performance.

虽然这些初步结果令人鼓舞,仍有许多挑战待解。其一是把 ViT 应用于检测、分割等其他计算机视觉任务——我们的结果与 Carion et al.(2020)的结果共同预示了这条路线的前景。其二是继续探索自监督预训练方法——我们的初步实验显示自监督预训练带来了提升,但与大规模有监督预训练之间仍有较大差距。最后,进一步扩大 ViT 的规模很可能带来性能提升。

EN

Acknowledgements. The work was performed in Berlin, Zürich, and Amsterdam. We thank many colleagues at Google for their help, in particular Andreas Steiner for crucial help with the infrastructure and the open-source release of the code; Joan Puigcerver and Maxim Neumann for help with the large-scale training infrastructure; Dmitry Lepikhin, Aravindh Mahendran, Daniel Keysers, Mario Lučić, Noam Shazeer, Ashish Vaswani, and Colin Raffel for useful discussions.

致谢。本工作在柏林、苏黎世和阿姆斯特丹完成。感谢 Google 众多同事的帮助,特别是 Andreas Steiner(基础设施与开源发布的关键帮助)、Joan Puigcerver 与 Maxim Neumann(大规模训练基础设施),以及 Dmitry Lepikhin、Aravindh Mahendran、Daniel Keysers、Mario Lučić、Noam Shazeer、Ashish Vaswani 和 Colin Raffel 的有益讨论。

说明:原文第 9–12 页为参考文献列表(References),无翻译价值,本对照版略去;正文引用格式(作者+年份)均保留原文,需要时可按原 PDF 检索。

附录 A 多头自注意力 / Appendix A: Multihead Self-Attention

EN

Standard qkv self-attention (SA, Vaswani et al. (2017)) is a popular building block for neural architectures. For each element in an input sequence z ∈ ℝN×D, we compute a weighted sum over all values v in the sequence. The attention weights Aij are based on the pairwise similarity between two elements of the sequence and their respective query qi and key kj representations.

标准 qkv 自注意力(SA,Vaswani et al., 2017)是神经网络架构的常用构件。对输入序列 z ∈ ℝN×D 中的每个元素,我们计算序列中所有 value v 的加权和。注意力权重 Aij 基于序列中两个元素各自的 query qi 与 key kj 表征之间的成对相似度。

[q, k, v] = zUqkv,  Uqkv ∈ ℝD×3Dh (5)
A = softmax( qk / √Dh ),  A ∈ ℝN×N (6)
SA(z) = Av (7)
EN

Multihead self-attention (MSA) is an extension of SA in which we run k self-attention operations, called "heads", in parallel, and project their concatenated outputs. To keep compute and number of parameters constant when changing k, Dh (Eq. 5) is typically set to D/k.

多头自注意力(MSA)是 SA 的扩展:并行运行 k 个自注意力运算(称为"头"),再把它们的输出拼接后投影。为使改变 k 时的计算量与参数量保持不变,Dh(式 5)通常取 D/k。

MSA(z) = [SA₁(z); SA₂(z); … ; SAk(z)] Umsa,  Umsa ∈ ℝk·Dh×D (8)

附录 B 实验细节 / Appendix B: Experiment Details

B.1 训练 / Training

EN

Table 3 summarizes our training setups for our different models. We found strong regularization to be key when training models from scratch on ImageNet. Dropout, when used, is applied after every dense layer except for the the qkv-projections and directly after adding positional- to patch embeddings. Hybrid models are trained with the exact setup as their ViT counterparts. Finally, all training is done on resolution 224.

表 3 汇总了各模型的训练配置。我们发现:在 ImageNet 上从头训练时,强正则化是关键。Dropout(使用时)施加于除 qkv 投影之外的每个全连接层之后,以及位置嵌入与 patch 嵌入相加之后。混合模型的训练配置与其对应的纯 ViT 完全一致。所有训练均在 224 分辨率下进行。

Model 模型Dataset 数据集EpochsBase LRLR decayWeight decayDropout
ViT-B/{16,32}JFT-300M78·10⁻⁴linear0.10.0
ViT-L/32JFT-300M76·10⁻⁴linear0.10.0
ViT-L/16JFT-300M7/144·10⁻⁴linear0.10.0
ViT-H/14JFT-300M143·10⁻⁴linear0.10.0
R50x{1,2}JFT-300M710⁻³linear0.10.0
R101x1JFT-300M78·10⁻⁴linear0.10.0
R152x{1,2}JFT-300M76·10⁻⁴linear0.10.0
R50+ViT-B/{16,32}JFT-300M78·10⁻⁴linear0.10.0
R50+ViT-L/32JFT-300M72·10⁻⁴linear0.10.0
R50+ViT-L/16JFT-300M7/144·10⁻⁴linear0.10.0
ViT-B/{16,32}ImageNet-21k9010⁻³linear0.030.1
ViT-L/{16,32}ImageNet-21k30/9010⁻³linear0.030.1
ViT-*ImageNet3003·10⁻³cosine0.30.1

Table 3 / 表 3:Hyperparameters for training. All models are trained with a batch size of 4096 and learning rate warmup of 10k steps. For ImageNet we found it beneficial to additionally apply gradient clipping at global norm 1. Training resolution is 224. —— 训练超参数。所有模型 batch size 均为 4096,学习率 warmup 10000 步。对 ImageNet 额外施加全局范数 1 的梯度裁剪有益。训练分辨率为 224。

B.1.1 微调 / Fine-tuning

EN

We fine-tune all ViT models using SGD with a momentum of 0.9. We run a small grid search over learning rates, see learning rate ranges in Table 4. To do so, we use small sub-splits from the training set (10% for Pets and Flowers, 2% for CIFAR, 1% ImageNet) as development set and train on the remaining data. For final results we train on the entire training set and evaluate on the respective test data. For fine-tuning ResNets and hybrid models we use the exact same setup, with the only exception of ImageNet where we add another value 0.06 to the learning rate sweep. Additionally, for ResNets we also run the setup of Kolesnikov et al. (2020) and select the best results across this run and our sweep. Finally, if not mentioned otherwise, all fine-tuning experiments run at 384 resolution (running fine-tuning at different resolution than training is common practice (Kolesnikov et al., 2020)).

所有 ViT 模型都用带动量 0.9 的 SGD 微调。我们对学习率做了小规模网格搜索(学习率范围见表 4):从训练集中划出小子集作为开发集(Pets 和 Flowers 取 10%,CIFAR 取 2%,ImageNet 取 1%),在其余数据上训练;最终结果则在完整训练集上训练、在各自测试数据上评估。ResNet 与混合模型的微调配置完全相同,唯一例外是 ImageNet 上学习率扫描额外加入了 0.06。此外对 ResNet 我们还运行了 Kolesnikov et al.(2020)的配置,在两轮结果中选最优。若无特别说明,所有微调实验均在 384 分辨率下进行(以不同于训练的分辨率微调是常见做法,Kolesnikov et al., 2020)。

EN

When transferring ViT models to another dataset, we remove the whole head (two linear layers) and replace it by a single, zero-initialized linear layer outputting the number of classes required by the target dataset. We found this to be a little more robust than simply re-initializing the very last layer. For VTAB we follow the protocol in Kolesnikov et al. (2020), and use the same hyperparameter setting for all tasks. We use a learning rate of 0.01 and train for 2500 steps (Tab. 4). We chose this setting by running a small sweep over two learning rates and two schedules, and selecting the setting with the highest VTAB score on the 200-example validation sets. We follow the pre-processing used in Kolesnikov et al. (2020), except that we do not use task-specific input resolutions. Instead we find that Vision Transformer benefits most from a high resolution (384×384) for all tasks.

将 ViT 模型迁移到另一数据集时,我们移除整个预测头(两个线性层),替换为单个零初始化线性层,输出目标数据集所需的类别数。我们发现这比只重新初始化最后一层更稳健。VTAB 遵循 Kolesnikov et al.(2020)的协议,所有任务使用同一组超参数:学习率 0.01、训练 2500 步(表 4)。该设置通过对两个学习率、两种日程的小扫描,在 200 样本验证集上选 VTAB 得分最高者确定。预处理沿用 Kolesnikov et al.(2020),但不使用任务专用输入分辨率——我们发现 Vision Transformer 在所有任务上均从高分辨率(384×384)获益最大。

Dataset 数据集Steps 步数Base LR 基础学习率
ImageNet20 000{0.003, 0.01, 0.03, 0.06}
CIFAR-10010 000{0.001, 0.003, 0.01, 0.03}
CIFAR-1010 000{0.001, 0.003, 0.01, 0.03}
Oxford-IIIT Pets500{0.001, 0.003, 0.01, 0.03}
Oxford Flowers-102500{0.001, 0.003, 0.01, 0.03}
VTAB(19 tasks)2 5000.01

Table 4 / 表 4:Hyperparameters for fine-tuning. All models are fine-tuned with cosine learning rate decay, a batch size of 512, no weight decay, and grad clipping at global norm 1. If not mentioned otherwise, fine-tuning resolution is 384. —— 微调超参数。所有模型均以余弦学习率衰减、batch size 512、无权重衰减、全局范数 1 梯度裁剪微调。未注明者微调分辨率为 384。

B.1.2 自监督 / Self-Supervision

EN

We employ the masked patch prediction objective for preliminary self-supervision experiments. To do so we corrupt 50% of patch embeddings by either replacing their embeddings with a learnable [mask] embedding (80%), a random other patch embedding (10%) or just keeping them as is (10%). This setup is very similar to the one used for language by Devlin et al. (2019). Finally, we predict the 3-bit, mean color (i.e., 512 colors in total) of every corrupted patch using their respective patch representations.

自监督初步实验采用掩码 patch 预测目标。做法:把 50% 的 patch 嵌入破坏掉——其中 80% 替换为可学习的 [mask] 嵌入,10% 替换为随机的其他 patch 嵌入,10% 保持原样。这与 BERT(Devlin et al., 2019)用于语言的设置非常相似。最后用各 patch 的表征预测被破坏 patch 的 3-bit 均值颜色(共 512 色)。

EN

We trained our self-supervised model for 1M steps (ca. 14 epochs) with batch size 4096 on JFT. We use Adam, with a base learning rate of 2·10⁻⁴, warmup of 10k steps and cosine learning rate decay. As prediction targets for pretraining we tried the following settings: 1) predicting only the mean, 3bit color (i.e., 1 prediction of 512 colors), 2) predicting a 4×4 downsized version of the 16×16 patch with 3bit colors in parallel (i.e., 16 predictions of 512 colors), 3) regression on the full patch using L2 (i.e., 256 regressions on the 3 RGB channels). Surprisingly, we found that all worked quite well, though L2 was slightly worse. We report final results only for option 1) because it has shown best few-shot performance. We also experimented with 15% corruption rate as used by Devlin et al. (2019) but results were also slightly worse on our few-shot metrics.

自监督模型在 JFT 上以 batch size 4096 训练 100 万步(约 14 个 epoch)。优化器 Adam,基础学习率 2·10⁻⁴,warmup 10000 步,余弦学习率衰减。预训练预测目标尝试了三种设置:1)只预测 3-bit 均值颜色(512 色中预测 1 个);2)并行预测 16×16 patch 的 4×4 缩小版、每格 3-bit 颜色(16 个 512 色预测);3)对完整 patch 的 3 个 RGB 通道做 L2 回归(256 个回归)。出人意料,三种都效果不错,L2 略差。因少样本表现最佳,最终只报告方案 1)。我们也试过 BERT 式 15% 破坏率,但在少样本指标上略差。

EN

Lastly, we would like to remark that our instantiation of masked patch prediction doesn't require such an enormous amount of pretraining nor a large dataset such as JFT in order to lead to similar performance gains on ImageNet classification. That is, we observed diminishing returns on downstream performance after 100k pretraining steps, and see similar gains when pretraining on ImageNet.

最后值得一提:我们的掩码 patch 预测实现并不需要如此巨大的预训练量或 JFT 这样的海量数据集,就能在 ImageNet 分类上取得类似收益——预训练 100k 步后下游收益即开始递减,且在 ImageNet 上预训练也能看到类似提升。

附录 C 补充结果 / Appendix C: Additional Results

EN

We report detailed results corresponding to the figures presented in the paper. Table 5 corresponds to Figure 3 from the paper and shows transfer performance of different ViT models pre-trained on datasets of increasing size: ImageNet, ImageNet-21k, and JFT-300M. Table 6 corresponds to Figure 5 from the paper and shows the transfer performance of ViT, ResNet, and hybrid models of varying size, as well as the estimated computational cost of their pre-training.

这里报告与正文各图对应的详细结果。表 5 对应正文图 3:在不同规模数据集(ImageNet / ImageNet-21k / JFT-300M)上预训练的各 ViT 模型的迁移性能。表 6 对应正文图 5:不同规模 ViT / ResNet / 混合模型的迁移精度与预训练算力(exaFLOPs)。

预训练集 Pre-training数据集ViT-B/16ViT-B/32ViT-L/16ViT-L/32ViT-H/14
ImageNetCIFAR-1098.1397.7797.8697.94
CIFAR-10087.1386.3186.3587.07
ImageNet77.9173.3876.5371.16
ImageNet ReaL83.5779.5682.1977.83
Flowers-10289.4985.4389.6686.36
Pets93.8192.0493.6491.35
ImageNet-21kCIFAR-1098.9598.7999.1699.1399.27
CIFAR-10091.6791.9793.4493.0493.82
ImageNet83.9781.2885.1580.9985.13
ImageNet ReaL88.3586.6388.4085.6588.70
Flowers-10299.3899.1199.6199.1999.51
Pets94.4393.0294.7393.0994.82
JFT-300MCIFAR-1099.0098.6199.3899.1999.50
CIFAR-10091.8790.4994.0492.5294.55
ImageNet84.1580.7387.1284.3788.04
ImageNet ReaL88.8586.2789.9988.2890.33
Flowers-10299.5699.2799.5699.4599.68
Pets95.8093.4097.1195.8397.56

Table 5 / 表 5:Top1 accuracy (in %) of Vision Transformer on various datasets when pre-trained on ImageNet, ImageNet-21k or JFT300M. These values correspond to Figure 3 in the main text. Models are fine-tuned at 384 resolution. Note that the ImageNet results are computed without additional techniques (Polyak averaging and 512 resolution images) used to achieve results in Table 2. —— ViT 在三个规模递增数据集上预训练后于各数据集的 Top-1 精度(%),对应正文图 3,384 分辨率微调。注意 ImageNet 一行未使用表 2 所用的额外技术(Polyak 平均与 512 分辨率)。

模型 nameEpochsImageNetImageNet ReaLCIFAR-10CIFAR-100PetsFlowersexaFLOPs
ViT-B/32780.7386.2798.6190.4993.4099.2755
ViT-B/16784.1588.8599.0091.8795.8099.56224
ViT-L/32784.3788.2899.1992.5295.8399.45196
ViT-L/16786.3089.4399.3893.4696.8199.66783
ViT-L/161487.1289.9999.3894.0497.1199.561567
ViT-H/141488.0890.3699.5094.7197.1199.714262
ResNet50x1777.5484.5697.6786.0791.1194.2650
ResNet50x2782.1287.9498.2989.2093.4397.02199
ResNet101x1780.6787.0798.4889.1794.0895.9596
ResNet152x1781.8887.9698.8290.2294.1796.94141
ResNet152x2784.9789.6999.0692.0595.3798.62563
ResNet152x21485.5689.8999.2491.9295.7598.751126
ResNet200x31487.2290.1599.3493.5396.3299.043306
R50x1+ViT-B/32784.9089.1599.0192.2495.7599.46106
R50x1+ViT-B/16785.5889.6599.1492.6396.6599.40274
R50x1+ViT-L/32785.6889.0499.2492.9396.9799.43246
R50x1+ViT-L/16786.6089.7299.1893.6497.0399.40859
R50x1+ViT-L/161487.1289.7699.3193.8997.3699.111668

Table 6 / 表 6:Detailed results of model scaling experiments. These correspond to Figure 5 in the main paper. We show transfer accuracy on several datasets, as well as the pre-training compute (in exaFLOPs). —— 模型缩放实验的详细结果,对应正文图 5。展示若干数据集上的迁移精度及预训练算力(exaFLOPs)。

附录 D 补充分析 / Appendix D: Additional Analyses

D.1 ResNet 用 SGD 还是 Adam / SGD vs. Adam for ResNets

EN

ResNets are typically trained with SGD and our use of Adam as optimizer is quite unconventional. Here we show the experiments that motivated this choice. Namely, we compare the fine-tuning performance of two ResNets – 50x1 and 152x2 – pre-trained on JFT with SGD and Adam. For SGD, we use the hyperparameters recommended by Kolesnikov et al. (2020). Results are presented in Table 7. Adam pre-training outperforms SGD pre-training on most datasets and on average. This justifies the choice of Adam as the optimizer used to pre-train ResNets on JFT. Note that the absolute numbers are lower than those reported by Kolesnikov et al. (2020), since we pre-train only for 7 epochs, not 30.

ResNet 通常用 SGD 训练,我们使用 Adam 相当反常规。为此我们在 JFT 上分别用 SGD 和 Adam 预训练两个 ResNet(50x1 与 152x2),再比较微调性能(SGD 超参沿用 Kolesnikov et al., 2020 的推荐值)。表 7 显示:Adam 预训练在大多数数据集上及平均值上优于 SGD,这为"用 Adam 预训练 JFT 上的 ResNet"提供了依据。注意绝对数值低于 Kolesnikov et al.(2020)的报告,因为这里只预训练 7 个 epoch 而非 30 个。

数据集 DatasetR50 · AdamR50 · SGDR152x2 · AdamR152x2 · SGD
ImageNet77.5478.2484.9784.37
CIFAR-1097.6797.4699.0699.07
CIFAR-10086.0785.1792.0591.06
Oxford-IIIT Pets91.1191.0095.3794.79
Oxford Flowers-10294.2692.0698.6299.32
平均 Average89.3388.7994.0193.72

Table 7 / 表 7:Fine-tuning ResNet models pre-trained with Adam and SGD. —— Adam 与 SGD 预训练的 ResNet 模型微调结果。

D.2 Transformer 形状 / Transformer Shape

EN

We ran ablations on scaling different dimensions of the Transformer architecture to find out which are best suited for scaling to very large models. Figure 8 shows 5-shot performance on ImageNet for different configurations. All configurations are based on a ViT model with 8 layers, D = 1024, DMLP = 2048 and a patch size of 32, the intersection of all lines. We can see that scaling the depth results in the biggest improvements which are clearly visible up until 64 layers. However, diminishing returns are already visible after 16 layers. Interestingly, scaling the width of the network seems to result in the smallest changes. Decreasing the patch size and thus increasing the effective sequence length shows surprisingly robust improvements without introducing parameters. These findings suggest that compute might be a better predictor of performance than the number of parameters, and that scaling should emphasize depth over width if any. Overall, we find that scaling all dimensions proportionally results in robust improvements.

我们对 Transformer 架构不同维度的缩放做了消融,找出最适合扩展到超大模型的维度。图 8 展示不同配置在 ImageNet 上的 5-shot 性能。所有配置基于同一个 8 层、D=1024、DMLP=2048、patch=32 的 ViT(各曲线的交点)。可以看到:加深(depth)带来的提升最大,直到 64 层仍清晰可见,但 16 层之后已开始收益递减;有趣的是,加宽(width)带来的变化最小;减小 patch(等效增加序列长度)在不引入参数的情况下带来出人意料的稳健提升。这些发现表明:相比参数量,算力可能是性能更好的预测指标;若要侧重,缩放深度胜过宽度。总体上,按比例缩放所有维度能带来稳健的提升。

D.3 头类型与 class token / Head Type and Class Token

EN

In order to stay as close as possible to the original Transformer model, we made use of an additional [class] token, which is taken as image representation. The output of this token is then transformed into a class prediction via a small multi-layer perceptron (MLP) with tanh as non-linearity in the single hidden layer.

为尽可能贴近原始 Transformer 模型,我们使用了额外的 [class] token 作为图像表征,其输出经一个小 MLP(单一隐藏层、tanh 非线性)变换为类别预测。

EN

This design is inherited from the Transformer model for text, and we use it throughout the main paper. An initial attempt at using only image-patch embeddings, globally average-pooling (GAP) them, followed by a linear classifier—just like ResNet's final feature map—performed very poorly. However, we found that this is neither due to the extra token, nor to the GAP operation. Instead, the difference in performance is fully explained by the requirement for a different learning-rate, see Figure 9.

这一设计继承自文本 Transformer,正文通篇使用。最初尝试只用图像 patch 嵌入做全局平均池化(GAP)再接线性分类器(就像 ResNet 的最终特征图那样),表现很差。但我们发现这既不是因为额外的 token,也不是 GAP 的锅——性能差异完全可以用「需要不同的学习率」解释(图 9):CLS-token 用 lr=8e-4,GAP 用更低的 lr=3e-4 时两者效果相当。

fig9_p17.jpg
Figure 9: Comparison of class-token and global average pooling classifiers. Both work similarly well, but require different learning-rates.
图 9:class-token 与全局平均池化(GAP)分类器对比:两者效果相当,但需要不同的学习率。

D.4 位置嵌入 / Positional Embedding

EN

We ran ablations on different ways of encoding spatial information using positional embedding. We tried the following cases: • Providing no positional information: Considering the inputs as a bag of patches. • 1-dimensional positional embedding: Considering the inputs as a sequence of patches in the raster order (default across all other experiments in this paper). • 2-dimensional positional embedding: Considering the inputs as a grid of patches in two dimensions. In this case, two sets of embeddings are learned, each for one of the axes, X-embedding, and Y-embedding, each with size D/2. Then, based on the coordinate on the path in the input, we concatenate the X and Y embedding to get the final positional embedding for that patch. • Relative positional embeddings: Considering the relative distance between patches to encode the spatial information as instead of their absolute position. To do so, we use 1-dimensional Relative Attention, in which we define the relative distance all possible pairs of patches. Thus, for every given pair (one as query, and the other as key/value in the attention mechanism), we have an offset pq−pk, where each offset is associated with an embedding. Then, we simply run extra attention, where we use the original query (the content of query), but use relative positional embeddings as keys. We then use the logits from the relative attention as a bias term and add it to the logits of the main attention (content-based attention) before applying the softmax.

我们消融了用位置嵌入编码空间信息的不同方式:① 不提供位置信息——把输入当作 patch 的无序集合;② 一维位置嵌入——按光栅顺序的 patch 序列(本文默认);③ 二维位置嵌入——二维网格,学习 X/Y 两组嵌入(各 D/2 维),按 patch 坐标拼接;④ 相对位置嵌入——编码 patch 间相对距离而非绝对位置:为所有 patch 对定义相对偏移 pq−pk(每个偏移关联一个嵌入),用原始 query(内容)与相对位置嵌入作为 key 做额外注意力,把相对注意力的 logits 作为偏置项加到主注意力(基于内容的注意力)的 logits 上再过 softmax。

EN

In addition to different ways of encoding spatial information, we also tried different ways of incorporating this information in our model. For the 1-dimensional and 2-dimensional positional embeddings, we tried three different cases: (1) add positional embeddings to the inputs right after the stem of them model and before feeding the inputs to the Transformer encoder (default across all other experiments in this paper); (2) learn and add positional embeddings to the inputs at the beginning of each layer; (3) add a learned positional embeddings to the inputs at the beginning of each layer (shared between layers).

除编码方式外,我们还尝试了把位置信息注入模型的不同方式:① 在模型主干(stem)之后、送入编码器之前加位置嵌入(默认);② 每层开头都学习并加入位置嵌入;③ 每层开头加入位置嵌入但层间共享。

EN

Table 8 summarizes the results from this ablation study on a ViT-B/16 model. As we can see, while there is a large gap between the performances of the model with no positional embedding and models with positional embedding, there is little to no difference between different ways of encoding positional information. We speculate that since our Transformer encoder operates on patch-level inputs, as opposed to pixel-level, the differences in how to encode spatial information is less important. More precisely, in patch-level inputs, the spatial dimensions are much smaller than the original pixel-level inputs, e.g., 14×14 as opposed to 224×224, and learning to represent the spatial relations in this resolution is equally easy for these different positional encoding strategies. Even so, the specific pattern of position embedding similarity learned by the network depends on the training hyperparameters (Figure 10).

表 8 汇总了 ViT-B/16 上的消融结果(ImageNet 5-shot 线性评估):无位置嵌入的模型与有位置嵌入的模型之间存在巨大差距,而不同位置编码方式之间几乎没有差别。我们推测:由于 Transformer 编码器处理的是 patch 级而非像素级输入,空间维度远小于原始像素输入(如 14×14 对 224×224),在这种分辨率下学习空间关系对各种编码策略都同样容易。即便如此,网络学到的位置嵌入相似度的具体模式仍依赖于训练超参数(图 10)。

fig10_p18.jpg
Figure 10: Position embeddings of models trained with different hyperparameters.
图 10:用不同训练超参数训练的模型所学的位置嵌入。
Pos. Emb. 位置嵌入 / 注入方式Default/StemEvery Layer 每层Every Layer-Shared 每层共享
No Pos. Emb. 无位置嵌入0.61382N/AN/A
1-D Pos. Emb. 一维0.642060.639640.64292
2-D Pos. Emb. 二维0.640010.640460.64022
Rel. Pos. Emb. 相对0.64032N/AN/A

Table 8 / 表 8:Results of the ablation study on positional embeddings with ViT-B/16 model evaluated on ImageNet 5-shot linear. —— 位置嵌入消融研究,ViT-B/16 模型、ImageNet 5-shot 线性评估。

D.5 实际计算成本 / Empirical Computational Costs

EN

We are also interested in real-world speed of the architectures on our hardware, which is not always well predicted by theoretical FLOPs due to details like lane widths and cache sizes. For this purpose, we perform timing of inference speed for the main models of interest, on a TPUv3 accelerator; the difference between inference and backprop speed is a constant model-independent factor. Figure 12 (left) shows how many images one core can handle per second, across various input sizes. Every single point refers to the peak performance measured across a wide range of batch-sizes. As can be seen, the theoretical bi-quadratic scaling of ViT with image size only barely starts happening for the largest models at the largest resolutions. Another quantity of interest is the largest batch-size each model can fit onto a core, larger being better for scaling to large datasets. Figure 12 (right) shows this quantity for the same set of models. This shows that large ViT models have a clear advantage in terms of memory-efficiency over ResNet models.

我们还关心架构在真实硬件上的实际速度——受通道宽度、缓存大小等细节影响,理论 FLOPs 并不总能很好预测。为此我们在 TPUv3 上对主要模型测量了推理速度(推理与反向传播速度之差是与模型无关的常数因子)。图 12(左)展示单个核在各种输入尺寸下每秒能处理的图像数(每点为跨多种 batch size 的峰值性能):ViT 随图像尺寸的理论双二次增长,只在最大模型、最大分辨率时才刚刚显现。另一个受关注的量是每个核能装下的最大 batch size(越大越利于大数据扩展),见图 12(右):大型 ViT 模型在内存效率上明显优于 ResNet。

fig12_p19.jpg
Figure 12: Left: Real wall-clock timings of various architectures across input sizes. ViT models have speed comparable to similar ResNets. Right: Largest per-core batch-size fitting on device with various architectures across input sizes. ViT models are clearly more memory-efficient.
图 12:左:各架构在不同输入尺寸下的真实推理速度(ViT 与同规模 ResNet 相当);右:各架构单核能装下的最大 batch size(ViT 的内存效率明显更优)。

D.6 轴向注意力 / Axial Attention

EN

Axial Attention (Huang et al., 2020; Ho et al., 2019) is a simple, yet effective technique to run self-attention on large inputs that are organized as multidimensional tensors. The general idea of axial attention is to perform multiple attention operations, each along a single axis of the input tensor, instead of applying 1-dimensional attention to the flattened version of the input. In axial attention, each attention mixes information along a particular axis, while keeping information along the other axes independent. Along this line, Wang et al. (2020b) proposed the AxialResNet model in which all the convolutions with kernel size 3×3 in a ResNet50 are replaced by axial self-attention, i.e. a row and column attention, augmented by relative positional encoding. We have implemented AxialResNet as a baseline model. Moreover, we have modified ViT to process inputs in the 2-dimensional shape, instead of a 1-dimensional sequence of patches, and incorporate Axial Transformer blocks, in which instead of a self-attention followed by an MLP, we have a row-self-attention plus an MLP followed by a column-self-attention plus an MLP.

轴向注意力(Huang et al., 2020; Ho et al., 2019)是在多维张量形式的大输入上运行自注意力的一种简单而有效的技术:把展平输入上的一维注意力改为多次注意力操作、每次沿输入张量的单个轴进行——每次注意力沿特定轴混合信息,其他轴保持独立。Wang et al.(2020b)据此提出 AxialResNet:把 ResNet50 中所有 3×3 卷积替换为带相对位置编码的行/列自注意力。我们实现了 AxialResNet 作为基线3。此外,我们修改 ViT 以二维形状处理输入,并纳入 Axial Transformer 块——每个块由「行自注意力+MLP+列自注意力+MLP」构成,而非「自注意力+MLP」。

EN

Figure 13, present the performance of Axial ResNet, Axial-ViT-B/32 and Axial-ViT-B/16 on ImageNet 5shot linear, when pretrained on JFT dataset, verses the pretraining compute, both in terms of number of FLOPs and inference time (example per seconds). As we can see, both Axial-ViT-B/32 and Axial-ViT-B/16 do better than their ViT-B counterpart in terms of performance, but it comes at the cost of more compute. This is because in Axial-ViT models, each Transformer block with global self-attention is replaced by two Axial Transformer blocks, one with row and one with column self-attention and although the sequence length that self-attention operates on is smaller in axial case, there is a extra MLP per Axial-ViT block. For the AxialResNet, although it looks reasonable in terms of accuracy/compute trade-off (Figure 13, left), the naive implementation is extremely slow on TPUs (Figure 13, right).

图 13 给出 Axial ResNet、Axial-ViT-B/32 与 Axial-ViT-B/16 在 JFT 预训练后 ImageNet 5-shot 线性的性能对比(分别按 FLOPs 与推理速度)。两个 Axial-ViT 精度都优于对应的 ViT-B,但计算量更大——因为 Axial-ViT 的每个 Transformer 块被两个 Axial 块(行 + 列)替代,虽然自注意力序列长度更短,但每个块多出一个 MLP。AxialResNet 看似精度/算力权衡合理(图 13 左),但朴素实现在 TPU 上极慢(图 13 右)。

EN

3Our implementation is based on the open-sourced PyTorch implementation in github.com/csrhddlam/axial-deeplab. In our experiments, we reproduced the scores reported in (Wang et al., 2020b) in terms of accuracy, however, our implementation, similar to the open-source implementation, is very slow on TPUs. Therefore, we were not able to use it for extensive large-scale experiments. These may be unlocked by a carefully optimized implementation.

3 实现基于开源 PyTorch 实现 github.com/csrhddlam/axial-deeplab。我们复现了 Wang et al. (2020b) 报告的精度,但该实现(与开源版类似)在 TPU 上非常慢,因此无法用于大规模实验;精心优化的实现可能解锁这一潜力。

fig13_p20.jpg
Figure 13: Performance of Axial-Attention based models, in terms of top-1 accuracy on ImageNet 5-shot linear, versus their speed in terms of number of FLOPs (left) and inference time (right).
图 13:轴向注意力模型在 ImageNet 5-shot 线性上的 Top-1 精度,对比其 FLOPs(左)与推理时间(右)。

D.7 注意力距离 / Attention Distance

EN

To understand how ViT uses self-attention to integrate information across the image, we analyzed the average distance spanned by attention weights at different layers (Figure 11). This "attention distance" is analogous to receptive field size in CNNs. Average attention distance is highly variable across heads in lower layers, with some heads attending to much of the image, while others attend to small regions at or near the query location. As depth increases, attention distance increases for all heads. In the second half of the network, most heads attend widely across tokens.

为理解 ViT 如何用自注意力整合整幅图像的信息,我们分析了不同层注意力权重覆盖的平均距离(图 11)。这种"注意力距离"类比 CNN 的感受野大小。低层中各头的平均注意力距离差异很大:一些头关注图像的很大部分,另一些只关注查询位置附近的小区域。随深度增加,所有头的注意力距离都增大;在网络后半段,大多数头的注意力已广泛跨越所有 token。

fig11_p18.jpg
Figure 11: Size of attended area by head and network depth. Attention distance was computed for 128 example images by averaging the distance between the query pixel and all other pixels, weighted by the attention weight. Each dot shows the mean attention distance across images for one of 16 heads at one layer. Image width is 224 pixels.
图 11:各头各层的注意力覆盖区域大小(注意力距离)。对 128 张示例图计算:以注意力权重加权平均查询像素与所有其他像素的距离。每点为一个头在一层上对图像集的平均值。图像宽度 224 像素。

D.8 注意力图 / Attention Maps

EN

To compute maps of the attention from the output token to the input space (Figures 6 and 14), we used Attention Rollout (Abnar & Zuidema, 2020). Briefly, we averaged attention weights of ViT-L/16 across all heads and then recursively multiplied the weight matrices of all layers. This accounts for the mixing of attention across tokens through all layers.

计算输出 token 对输入空间的注意力图(图 6 与图 14)时,我们使用了 Attention Rollout(Abnar & Zuidema, 2020):简言之,把 ViT-L/16 所有头的注意力权重取平均,然后递归相乘各层的权重矩阵——以此把各层之间跨 token 的注意力混合考虑在内。

D.9 ObjectNet 结果 / ObjectNet Results

EN

We also evaluate our flagship ViT-H/14 model on the ObjectNet benchmark following the evaluation setup in Kolesnikov et al. (2020), resulting in 82.1% top-5 accuracy and 61.7% top-1 accuracy.

我们按 Kolesnikov et al.(2020)的评估设置,在 ObjectNet 基准上评估旗舰模型 ViT-H/14:Top-5 精度 82.1%,Top-1 精度 61.7%。

D.10 VTAB 分项 / VTAB Breakdown

EN

Table 9 shows the scores attained on each of the VTAB-1k tasks: ViT-H/14 (JFT) mean 77.6, ViT-L/16 (JFT) mean 76.3, ViT-L/16 (I21k) mean 72.7, over 19 tasks including Caltech101, CIFAR-100, DTD, Flowers102, Pets, Sun397, SVHN, Camelyon, EuroSAT, Resisc45, Retinopathy, Clevr-Count, Clevr-Dist, DMLab, dSpr-Loc, dSpr-Ori, KITTI-Dist, sNORB-Azim, sNORB-Elev.

表 9 展示 VTAB-1k 各任务的得分(19 个任务:Caltech101、CIFAR-100、DTD、Flowers102、Pets、Sun397、SVHN、Camelyon、EuroSAT、Resisc45、Retinopathy、Clevr-Count、Clevr-Dist、DMLab、dSpr-Loc、dSpr-Ori、KITTI-Dist、sNORB-Azim、sNORB-Elev):ViT-H/14 (JFT) 均值 77.6,ViT-L/16 (JFT) 76.3,ViT-L/16 (I21k) 72.7;逐格数值见原文表 9。

中英对照版 · 基于 arXiv:2010.11929v2(ICLR 2021)· 左栏英文原文摘自用户提供之 PDF,右栏为中文翻译 · 仅供学习研究使用,原文版权归作者所有