Combined Scaling for Zero-shot Transfer Learning

Hieu Pham, Zihang Dai, Golnaz Ghiasi, Kenji Kawaguchi, Hanxiao Liu, Adams Wei Yu, Jiahui Yu, Yi-Ting Chen, Minh-Thang Luong, Yonghui Wu, Mingxing Tan, Quoc V. Le

Introduction

The recent advances in multimodal training approaches such as CLIP (Radford et al., 2021) and ALIGN (Jia et al., 2021) have the potential to eliminate the need for collecting labeled training data for every new application. Using natural language as a weak supervision signal, CLIP and ALIGN achieve the impressive top-1 accuracy of 76.2% and 76.4% on ImageNet ILSVRC-2012 without learning from any labeled ImageNet data. In addition to the promising accuracy on ImageNet, the so-called “zero-shot” models in CLIP and ALIGN demonstrate two important properties. First, these models are versatile, as they can be directly deployed on many downstream tasks without task-specific data for finetuning. Second, CLIP and ALIGN models are more robust than traditional classifiers. Robustness evaluations on benchmarks with natural distribution shifts (Hendrycks et al., 2021b, a; Recht et al., 2019; Barbu et al., 2019; Wang et al., 2019) show that the accuracy of models like CLIP and ALIGN typically drops less than 10%, while the accuracy of supervised and semi-supervised models might drop as much as 40% (Taori et al., 2020; Szegedy et al., 2013).

Despite their versatility and robustness, the best models from CLIP and ALIGN are still not as competitive as supervised and semi-supervised models when enough labeled data is available, which can limit their potential applications. For example, the best CLIP and ALIGN models have an accuracy around 76% on ImageNet, which is only comparable with a supervised ResNet-50 (He et al., 2015), and significantly worse than the state-of-the-art supervised training on ImageNet (without extra data: 87.1% (Yuan et al., 2021), and with extra data: 90.88% (Dai et al., 2021)). Therefore, narrowing the gap from these models to supervised and semi-supervised models would make the image-text contrastive learning approach in CLIP and ALIGN a viable alternative for image classification.

In this paper, we develop significantly better image classifiers that leverage the image-text contrastive learning approaches like CLIP and ALIGN at a much larger scale. In particular, we scale up the contrastive learning framework of CLIP (Radford et al., 2021) and ALIGN (Jia et al., 2021) in 3 dimensions: dataset size, model size, and batch size. For the data, we expand the ALIGN dataset (Jia et al., 2021) from 1.7B noisy image-text pairs to 6.6B pairs, i.e., almost 4x larger. For the models, we choose CoAtNet, an architecture with higher learning capacity (Dai et al., 2021), and scale it to 3B parameters, i.e., 3.75x more weights and 8x more FLOPs than the largest models in CLIP and ALIGN. For the batch size, we use 65536 contrastive learning examples per minibatch, i.e., 2x more than CLIP and 4x more than ALIGN.

The fundamental bottleneck of training large models at larger batch sizes is the limited memory of deep learning accelerators such as GPUs and TPUs. We propose two approaches that allow practitioners to overcome such memory limits.

Our first approach (Section 4) makes use of micro-batch pipelining (Huang et al., 2019) and gradient accumulation (GradAccum) (Ott et al., 2018; Zhai et al., 2021). Our second approach (Section 5) utilizes the model parallelism scheme of Single-Program Multi-Data (SPMD) (Lepikhin et al., 2020; Xu et al., 2021) to distribute the weights of certain layers in our networks onto different devices. While our SPMD approach is faster than our pipelining approach, and can deliver exact computations, the SPMD approach requires more manual designs to scale to arbitrarily large contrastive batch sizes, and hence, is less general than the pipelining approach.

Both our pipelining approach and our SPMD approach make use of gradient checkpointing (Chen et al., 2016), which is also called rematerialization in certain literature (Kumar et al., 2019; Jain et al., 2020). The idea behind rematerialization is to discard certain intermediate values in the forward pass of a neural network to save memory, and then recompute – i.e., rematerialize – these values only when they are needed for gradient computation in the network’s backward pass.

While the benefits of large datasets and large models for deep learning models have become established knowledge, the benefits of large batch size are less well-understood in the context of relatively new image-text contrastive models. To understand such benefits, we develop a theoretical analysis of the image-text contrastive learning framework of CLIP and ALIGN. Our analysis establishes that using a larger contrastive batch size in CLIP and ALIGN’s framework leads to a smaller generalization gap of the resulting models.

Our proposed method, called BASIC, for Batch, Data and Model SIze Combined Scaling, achieves drastic improvements over CLIP and ALIGN models. For instance, on ImageNet, the largest BASIC model achieves 85.7% top-1 accuracy, without learning from any labeled example in the ImageNet training set. This result surpasses similar models in CLIP and ALIGN 9.3%. This BASIC model also shows significant improvements on robustness benchmarks. For instance, on 5 test sets with natural distribution shifts such as ImageNet-{A,R,V2,Sketch} and ObjectNet, the model achieves an average of 83.7% top-1 accuracy, only a small drop from its original ImageNet accuracy (see Table 1). When tested against CLIP on the other 17 image classification benchmarks, e.g., CIFAR, Caltech101, Flowers, etc. BASIC outperforms CLIP on 13 out of these 17 benchmarks.

Related Work

As computer vision models grow in their size and capacity, many weakly-supervised and self-supervised pretraining methods have been proposed to learn good visual representations. On one hand, pretraining with a classification loss on large weakly-labeled datasets such as Instagram hashtags or JFT can produce significant gains on downstream tasks such as ImageNet (Joulin et al., 2016; Mahajan et al., 2018; Kolesnikov et al., 2020; Dosovitskiy et al., 2021; Sun et al., 2017; Zhai et al., 2021). On the other hand, self-supervised methods which leverage existing structures in unlabeled data to train models have been developed. A promising development in self-supervised learning is the contrastive loss, with representative works like CPC (van den Oord et al., 2018), SimCLR (Chen et al., 2020a, b) and MoCo (He et al., 2020; Chen et al., 2020c). In this paper, we scale up the contrastive learning framework, which we will revisit in detail in Section 3.

Unlike the single-modal contrastive approaches mentioned in the previous paragraph, our work leverages data from two modalities: image and text. Using images with accompanying text is related to the literature on image-captioning models, such as (Vinyals et al., 2015; Karpathy and Fei-Fei, 2015; Xu et al., 2015; Joulin et al., 2016; Li et al., 2017; Sariyildiz et al., 2020; Zhang et al., 2020; Desai and Johnson, 2021). While learning to generate captions from images can induce good visual representations, it is not the goal of this paper. Instead, this paper focuses on establishing the ability of models to classify images based on textual descriptions. This focus makes our work closely related to the recent work of image-text models such as CLIP (Radford et al., 2021) and ALIGN (Jia et al., 2021). Similar to CLIP and ALIGN, our work also learns the mapping between images and texts, which is related to many previous works, such as (Hironobu et al., 1999; Weston et al., 2010; Socher and Fei-Fei, 2010; Socher et al., 2013; Hodosh et al., 2013; Frome et al., 2013; Norouzi et al., 2013; Kiros et al., 2014; Socher et al., 2014; Akata et al., 2015b, a; Nam et al., 2017; Faghri et al., 2017; Li et al., 2019; Liu et al., 2019; Lu et al., 2019; Messina et al., 2020; Chen et al., 2020d; Huang et al., 2020; Chen et al., 2021).

Early works on zero-shot vision models date back to the 2000s, e.g., (Larochelle et al., 2008; Zhang et al., 2017; Xian et al., 2016, 2017; Schönfeld et al., 2019). In these works, the term “zero-shot” refers to the ability of models to “generalize to classes or tasks for which no training data are available and only a description of the classes or tasks are provided”. Under such definition, BASIC models – as well as the recent work that BASIC is based on such as CLIP (Radford et al., 2021) and ALIGN (Jia et al., 2021) – are not “zero-shot learned” models. This is because the data curating procedures of BASIC, CLIP, and ALIGN can exposes certain class names to their models, albeit not intentionally. For instance, when an image of a golden retriever dog is crawled from the internet, the image could come from a file named my_golden_retriever.jpg which was uploaded by a user. If a model in BASIC, CLIP, or ALIGN learns to associate the content of such an image with the text sequence “my golden retriever” as parsed from the image’s file name, and then the model uses the knowledge from such association at test time, then the model is not zero-shot. Despite being not zero-shot, models from BASIC, CLIP, and ALIGN retain their claimed benefits on versatility and robustness.

Instead of zero-shot learning, CLIP and ALIGN are known to conduct zero-shot transfer learning (Radford et al., 2021; Jia et al., 2021; Zhai et al., 2022). Zero-shot transfer learning differs significantly from zero-shot learning. Unlike zero-shot learning, it permits relevant supervised information during pretraining, while it allows no supervised examples during the transfer protocol; i.e., zero-shot transfer learning skips the finetuning stage completely and performs the downstream task based only on a text description of the target classes. For example, see (Radford et al., 2021; Jia et al., 2021; Zhai et al., 2022) for more details on this terminology.

Scaling has proven to be a powerful tool to boost the efficacy of vision model pretraining. There are three dimensions one can scale on. The simplest dimension is data. Indeed, recent efforts have shown that the more data we train on, the better the models become (Joulin et al., 2016; Mahajan et al., 2018; Kolesnikov et al., 2020; Dosovitskiy et al., 2021; Sun et al., 2017). The second dimension is the model size, with representative works such as EfficientNet, VITs and related works (Tan and Le, 2019, 2021; Tan et al., 2020; Dosovitskiy et al., 2021; Zhai et al., 2021; Bello et al., 2021). Lastly, scaling up batch sizes is also the key for improving the model effectiveness (Goyal et al., 2017), especially for the contrastive loss (Chen et al., 2020a; Tian et al., 2020; Jia et al., 2021; Radford et al., 2021). Our work is inspired by the power of scaling, and pushes the limits in all the dimensions.

Background on Image-text Contrastive Learning and Zero-shot Transfer Learning

In this section, we revisit the contrastive training framework for parallel image-text data, as introduced by CLIP (Radford et al., 2021) and ALIGN (Jia et al., 2021). In doing so, we define the notations that will be used throughout the remaining of this paper.

Minimizing ContrastiveLossB\text{ContrastiveLoss}_{B} encourages the entries on the diagonal of A{\bm{A}} to be large while the entries elsewhere to be small. Equivalently, images and text sequences from the same pair in the minibatch, i.e. xix_{i} and yi{\bm{y}}_{i}, will be embedded into nearby points, while those from different pairs, i.e. xix_{i} and yj≠i{\bm{y}}_{j\neq i}, will be embedded into distant points. The resulting encoders FF and GG thus achieve the desiderata of the contrastive learning framework.

Batch Size Scaling with Pipelining and Gradient Accumulation

We start this section by discussing the memory bottleneck in the contrastive training framework as described in Section 3. We focus on memory because it is the most crucial bottleneck which hinders two out of three dimensions that we want to scale, i.e., model size and batch size. We further show that the vanilla pipelining algorithm (Huang et al., 2019) with gradient accumulation (GradAccum) (Ott et al., 2018; Zhai et al., 2021) is not directly applicable to contrastive learning. We then describe our modifications to make GradAccum work for constrastive learning.

The consensus among representative work in contrastive learning (Chen et al., 2020b, c; He et al., 2020; Chen et al., 2020a) is that the larger the networks trained with a larger contrastive batch size performs better. This observation is further explained by our theoretical analysis in Section 6, and is confirmed by empirical results in Section 10. Therefore, we want to enlarge the networks FF, GG, and the batch size BB. However, this will create a memory bottleneck. Three well-known techniques to relieve memory burden are gradient accumulation (GradAccum) (Ott et al., 2018; Zhai et al., 2021), re-materialization (or gradient checkpointing) (Griewank and Walther, 2000; Chen et al., 2016) and model parallelism (Shazeer et al., 2018; Huang et al., 2019; Lepikhin et al., 2020). Note that all three techniques are orthogonal and complementary to each other. Next in section 4.2, we present an approach based on pipelining model parallelism and gradient accumulation.

Consider training a model weight vector θ\theta to minimize a loss function L\mathcal{L}. For a batch of BB examples {e1,e2,...,eB}\{{\mathbf{e}}_{1},{\mathbf{e}}_{2},...,{\mathbf{e}}_{B}\}, let gig_{i} be the gradient of L\mathcal{L} with respect to θ\theta computed on example ei{\mathbf{e}}_{i}, i.e., gi=∇θL(θ;ei)g_{i}=\nabla_{\theta}\mathcal{L}(\theta;{\mathbf{e}}_{i}). In the standard minibatch setting, we update θ\theta with the average batch gradient \bar{g}=\big{(}\sum_{i=1}^{B}g_{i}\big{)}/B. When our accelerator memory can only hold M≪BM\ll B examples, GradAccum splits the batch of BB examples into smaller batches with at most MM examples, called microbatches, then computes the gradients of the microbatches, and averages them.

We now analyze the steps of GradAccum. For simplicity, assume that MM evenly divides BB, and that microbatch ii-th consists of examples ej{\mathbf{e}}_{j}’s with (i−1)M+1≤j≤iM(i-1)M+1\leq j\leq iM. With this assumption, the GradAccum procedure first initializes a zero vector gˉ\bar{g} of the same size with θ\theta. Then, sequentially for each microbatch ii-th, the microbatch gradient c_{i}=\big{(}\sum\nolimits_{j=(i-1)M+1}^{iM}g_{j}\big{)}/M is added to gˉ\bar{g}. In the end, gˉ\bar{g} holds the correct minibatch gradient, up to a normalization constant K=B/MK=B/M.

There are two properties that make GradAccum not applicable to contrastive learning. First, in order to evaluate the loss ContrastiveLossB\text{ContrastiveLoss}_{B} in Equation 3, we need all entries of the similarity matrix A{\bm{A}}. Hence, we cannot rely only on examples in every microbatch ii-th to compute the microbatch gradients cic_{i}’s. Second, GradAccum must allocate memory for the cumulative gradient gˉ\bar{g}.It is worth noting that this is a common issue with GradAccum and is not specific to contrastive learning. As gˉ\bar{g} has as many elements as θ\theta, its memory grows as we scale up the networks FF and GG. This growth becomes a more pronounced issue as we scale up our models. For reference, our largest model has 3B weights, occupying roughly 11GB of accelerator memory. Spending another 11GB on gˉ\bar{g}, while possible, defeats the purpose of saving memory in GradAccum. In the remaining of this subsection, we discuss how to modify GradAccum so that we can use it to scale up contrastive learning.

2 Modifying Pipelining and GradAccum for the Contrastive Loss

To enable proper GradAccum, a key observation is that while we need the entire similarity matrix A{\bm{A}} to compute ContrastiveLossB\text{ContrastiveLoss}_{B} in Equation 3, we do not need to store all the intermediate results leading to the matrix in memory. This observation immediately connects to re-materialization, which trades computation for memory by dropping some intermediate hidden states during the forward pass and re-computing them during back-propagation. Following this insight, we propose to combine re-materialization with gradient accumulation by microbatching the contrastive loss and re-materializing each microbatch.

Specifically, we first run a forward pass on the networks FF, GG to compute the entire similarity matrix A{\bm{A}} while discarding all intermediate hidden states. Then, we use A{\bm{A}} to compute ContrastiveLossB\text{ContrastiveLoss}_{B} and the gradient ∇AContrastiveLossB\nabla_{{\bm{A}}}\text{ContrastiveLoss}_{B} and microbatch this gradient along the batch axis. Finally, for each microbatch, we re-materialize the hidden states, i.e., rerun the forward computation, and back-prop and accumulate the corresponding gradient microbatch of ∇ALc\nabla_{{\bm{A}}}\mathcal{L}_{\text{c}} into the weights of the networks FF, GG.

Algorithm 1 presents this procedure in detail and provides the memory analysis for each step. As shown, our algorithm can compute the exact microbatch gradients from an entire batch of BB examples, with the peak memory usage of Θ(M⋅max⁡{Mem(F),Mem(G)})\Theta(M\cdot\max{\{\text{Mem}(F),\text{Mem}(G)\}}), instead of Θ(B⋅(Mem(F)+Mem(G)))\Theta(B\cdot(\text{Mem}(F)+\text{Mem}(G))). We note that our algorithm can be flexibly modified to work different microbatch-sizes, i.e., MM, for the image network FF and the text network GG. This flexibility allows for more efficient computations, e.g., when one network is smaller than another and thus, can operate with larger microbatches.

Algorithm 1 yields a stream of microbatch gradients c1,...,cB/Mc_{1},...,c_{B/M}, which need to be accumulated, i.e., averaged, into gˉ\bar{g} to perform the batch weight update. As discussed, we want to avoid allocating extra memory for gˉ\bar{g}. To do this, we need two assumptions about our training implementation. Our first assumption is that we use an optimizer which involves gradient moments (Nesterov, 1983; Tieleman and Hinton, 2012; Kingma and Ba, 2015; Loshchilov and Hutter, 2019; Shazeer and Stern, 2018). This assumption motivates our idea to avoid allocating gˉ\bar{g}: since the optimizer already allocates the memory for gradient moments, typically called slots, we will directly accumulate the microbatch gradients cic_{i}’s into these slots.

We illustrate this idea with Adam (Kingma and Ba, 2015), a popular optimizer that involves two gradient moments. At training step tt, Adam receives the averaged minibatch gradient gˉ\bar{g} and makes the following updates to its gradient moments v1v_{1} and v2v_{2}:

Accumulating the microbatch gradients cic_{i}’s to v1v_{1} is straightforward. We can simply modify v1v_{1}’s single update with gˉ\bar{g} into K=B/MK=B/M updates as follows:

Unfortunately, the same approach is not applicable for v2v_{2}, as the square of the sum is generally different from the sum of the squares, i.e. (∑ci)2≠∑ci2(\sum c_{i})^{2}\neq\sum c_{i}^{2}. However, the difference between these two quantities turns out to be:

which we can estimate. Indeed, since each cic_{i}’s is the mean of MM per-example gradients gjg_{j}’s in the ii-th microbatch, we can treat cic_{i}’s as the population mean of MM observed examples drawn from a random variable g∼Uniform{g1,...,gB}{\mathbf{g}}\sim\text{Uniform}\{g_{1},...,g_{B}\}. This treatment allows us to use the familiar identity:

Therefore, to estimate Var[ci]\mathbf{Var}\mathopen{}\left[c_{i}\mathopen{}\right], we only need to estimate Var[g]\mathbf{Var}\mathopen{}\left[{\mathbf{g}}\mathopen{}\right]. For this, we make the second assumption about our training: that we use a data parallelism setting with RR replicas. Under this assumption, each microbatch gradient cic_{i} is obtained from an all-reduce operation on RR replicas, each of which processes M/RM/R examples. Once again, treating these per-device gradients d1,...,dRd_{1},...,d_{R} as the population mean of M/RM/R observed examples for g{\mathbf{g}}, we can apply Identity 4 to obtain: Var[d]=Var[g]/(M/R)\mathbf{Var}\mathopen{}\left[d\mathopen{}\right]=\mathbf{Var}\mathopen{}\left[{\mathbf{g}}\mathopen{}\right]/(M/R). This treatment allows us to perform GradAccum while avoiding to allocate gˉ\bar{g}.

Batch Size Scaling with the Single-Program Multiple-Data (SPMD) Scheme

In Section 4, we have seen that one circumvent the memory bottleneck of large models and large batch sizes for image-text contrastive learning by: (1) “chunk” a large batch of BB image-text pairs into arbitrarily smaller microbatches, (2) compute the gradient for each microbatch, and (3) accumulate them. While such an approach is generic and can work for any global contrastive batch size BB and any microbatch size MM, there are two steps in the approach that makes the resulting gradient inexact. The first inexact computation comes from the approximations when accumulating the microbatch gradients. This is a necessary tradeoff to avoid allocating the memory to accumulate the microbatch gradients. The second inexact computation is more subtle, and is specific to our modeling choice, and has also been noted by Huang et al. (2019). Specifically, when our networks FF and GG depend on the batch, e.g., via the batch normalization layers in our image encoder FF, then the outputs of the networks for multiple microbatches are generally different from those for one entire global batch. When the microbatch size MM is too small compared to BB, the discrepancies become very large and can cause the covariate shift in the image encoder FF which was the original motivation for batch normalization. More recent image encoders can overcome such inexact computations because they avoid batch normalization by replacing it with layer normalization like Vision Transformer (Dosovitskiy et al., 2021), or just do not use any normalization at all like NFNet (Brock et al., 2021). However, the inexact gradient accumulation remains even for such models.

To overcome these inexact computations, in this section, we discuss an alternate approach to circumvent the memory bottleneck. This approach is based on the SPMD programming scheme. We find that not only does our SPMD method provide exact computations which lead to better results than pipelining and GradAccum, but our SPMD method also has a better latency per training step. However, as we shall see in Section 5.1 and Section 5.2, our SPMD method requires several manual designs, which make it less generic than pipelining and GradAccum.

As model sizes grow, model weights occupy a significant part of accelerator memory. In modern optimizers for deep learning models, such as Adam (Kingma and Ba, 2015), RMSprop (Tieleman and Hinton, 2012), and AdamW (Loshchilov and Hutter, 2019), every weight tensor is additionally accompanied by the first and second gradient moments, hence tripling its memory footprint. Furthermore, in the vanilla data parallelism training, all these weights are replicated to all accelerators. In our experiments with a relatively large model size, roughly 4GB of accelerator memory is occupied by these weights and their gradient moments, which is significant for the typical 16GB memory in an accelerator in 2022, such as a Google TPU core or an Nvidia RTX 3080 GPU.

Here, we split the weight tensors in our encoder networks, i.e. FF and GG in Section 3, into multiple accelerator cores, and only combine these tensors together when the whole tensor is needed to perform certain computations. Note that upon splitting a weight tensor to multiple cores, we also split its first and second gradient moments in the similar way. Figure 1 illustrates our weight sharding strategy on the 2D convolution operation which is prevalent in image encoder models.

Our approach is based on the Single-Program Multiple-Data (SPMD) technique, which has been successfully applied to train large language models in previous works such as in Xu et al. (2021); Lepikhin et al. (2020). In the SPMD technique, we define a computational graph which represents our entire training program. This computational graph is compiled once, and then is replicated identically to all computational cores to run the training program. While all of our computational cores run an identical program, they are allowed to receive different inputs and hence can produce different outputs. These inputs and outputs can be organized in certain ways to define arbitrarily complex model parallelism strategies. Next, we describe how we apply the SPMD technique on our model weights only.

Our training program runs typically on a cluster of 2048 TPUv3 cores. We partition these 2048 cores into RR replicas, each of which uses 2048/R2048/R cores. The value of RR governs how the weights of our image encoder FF and our text encoder GG are stored in the memory of our 2048 cores. In particular, all weight tensors in the networks FF and GG are split into RR equal parts, each lives in one of the RR cores in a replica. Note that since we have 2048/R2048/R replicas, the weights of our image and text encoders are still replicated for 2048/R2048/R times. For instance, our cores 1st1^{\text{st}}, 2nd2^{\text{nd}}, … RthR^{\text{th}} can each store 1/R1/R of the weight tensors, and then the cores R+1stR+1^{\text{st}}, R+2ndR+2^{\text{nd}}, …, 2Rth2R^{\text{th}} store an identical copy of these tensors. Thus, using fewer replicas and more cores per replica leads to a better memory utilization, at a higher overhead for cross-cores communications. We empirically find that using 512 replicas and 4 cores per replica offers a good balance.

It is important to note that we only apply SPMD on our model weights, and not on any other steps of our computations. This means that if our training program receives an input batch of BB examples, then these BB examples are distributed equally to all our 2048 cores. In other words, each of our 2048 cores processes B/2048B/2048 examples, regardless of the value of RR. We find that this design choice disentangles our weight sharding strategy from the rematerialization strategy, as described next in Section 5.2.

2 Rematerialization

The technique of rematerialization, also widely known as gradient checkpointing (Chen et al., 2016), preserves the accelerator memory while training neural networks. It works by not saving certain values from a network’s forward pass, and recompute them in the backward pass only when their values are needed for a particular calculation. For instance, if our image encoder FF, as discussed in Section 3 has 100 layers, a rematerialization program can decide that after the forward pass, only the values of layers 10th10^{\text{th}}, 20th20^{\text{th}}, …, 90th90^{\text{th}} are kept in an accelerator’s memory, while the values of other layers are removed. If all layers of FF consumes similar memory, this rematerialization program has reduced the memory cost by 10 times, at the trade off that the values of the unsaved layers in the forward pass, such as layer 21st21^{\text{st}} or layer 72nd72^{\text{nd}}, have to be recomputed in the backward pass.

We select which layer to rematerialize in our image encoder FF and our text encoder GG based on a simple heuristic. Ideally, we want to rematerialize the layers that are fast to recompute but consumes the more memory. Since we utilize weight sharding, as described in Section 5.1, the computations that involve weights are slower than normal because of their overhead time for cross-core communications. As such, we keep almost all layers that involve weights, such as convolution, attention, and dense feed-forwards, in our accelerator’s memory. In contrast, layers that do not involve weights, such as activation functions, batch normalization, and layer normalization, are all rematerialized. Figure 2 illustrates our rematerialization strategy for all three block types in our image and text encoders: the mobile-inverse convolutional block (Tan and Le, 2019; Dai et al., 2021), the attention block, and the feed-forward blocks (Vaswani et al., 2017).

We find this design choice beneficial, because in modern encoder architectures, every layer that involves weights is typically followed by a normalization layer or an activation layer. As such, our design allows more than half of the encoder’s activation values to be removed from the accelerator’s memory after each forward pass, while leaving only the light computational steps to be repeated in each backward pass. We empirically find that weight sharding and rematerialization, each of our forward-backward pass is 1.4 times slower than the vanilla implementation of the same batch size.

Certain parts of our encoders do not follow these general heuristics, as we find that doing so saves a certain amount of time at the cost of using a little extra memory. Here, we describe these exceptions:

All weights in batch normalization and layer normalization in our models, including the β\beta’s and γ\gamma’s and the moving average statistics of batch normalization, are not sharded. Instead, these weights are replicated to all computational cores to avoid cross-cores communications, because they are one dimensional vectors which do not occupy much memory.

All computations the Squeeze-and-Excitation blocks (SE; (Hu et al., 2018)) of our models are rematerialized, including the convolutions. This is because these SE blocks only involve 1x1 convolution with reduced internal channels, making them less costly to recompute. In addition, all the weights of these 1x1 convolutions are replicated to all of our cores, because they have a small memory footprint but are reused in the backward pass for rematerialization.

3 Comparison with Pipelining and Gradient Accumulation

We measure and compare the step time and peak memory usage of our SPMD approach and our Pipelining and GradAccum approach from Section 4. We measure these pieces of information as the contrastive batch size BB becomes larger. In particular, we start with B=216B=2^{16} and double BB until we reach B=220B=2^{20}. When BB increases, but our model can still fit into the our memory only with vanilla data parallelism, we measure the step time and the peak memory using this setting. These measures serve as the reference to quantify how much overhead is introduced by pipelining, SPMD, or rematerialization as a whole. When BB grows and our models can no longer train with merely data parallelism, we experiment with the Pipelining and GradAccum, and compare the resulting programs with the SPMD programs of the same model and batch size. Note that for the pipelining approach, we set the microbatch size to the largest size that vanilla data parallelism can fit in our accelerator’s memory.

For all settings, we profile a model in 15 seconds. Our profiling tool tracks the time and memory usage of our models during their forward and backward passes in each step. Note that our backward pass time includes the time our models spend on their rematerialized computations (as discussed in Section 5.2), as these computations happen while the models compute their gradients. Note that other than these forward and backward passes, every step of our models has some extra overheads for miscellaneous computations that are not recorded by our profiling tool, e.g., gradient clippings and updating model parameters.

All of our measurements are reported in Table 2. From the table, it can be seen that our model parallelism strategy leads to a faster overall step time, compared to the pipelining approach in the same setting. Breaking down these step times, it can be seen that the run time of our strategy’s model forward pass is very close to the run time of pipelining’s forward pass, but our backward time is often a lot faster. For instance, in our largest setting, with the medium-sized model and the contrastive batch size B=220B=2^{20}, our backward time is more than 1.2 seconds faster than that of the pipelining approach, amounting to about 10% of the total step time. Additionally, our strategy also has a faster total step time, perhaps because do not need to spend extra time to accumulate the microbatch gradients like the pipelining approach.

Finally, we note that as BB grows larger, the SPMD approach typically occupies more accelerator memory than does the pipelining approach. This is because in the pipelining approach, increasing the contrastive batch size BB only leads to more microbatches, but does not change the micro batch size, and so the accelerator’s memory remains constant. As such, the pipelining approach is still applicable if BB grows larger than 2202^{20}, but the SPMD strategy has to be redesigned, e.g. by deciding to rematerialize a larger portion of our image and text encoder.

Theoretical Insight on the Role of Contrastive Batch Size

In this section, we provide a theoretical insight that increasing the contrastive batch size tends to improve the performance of the final model, which motivates and partially justifies the design of our new algorithm in the previous section. Let y^1,…,y^B\hat{y}_{1},\dots,\hat{y}_{B} be the sequence of the text sentence inputs used in training. Similarly, let yˉ1,…,yˉM\bar{y}_{1},\dots,\bar{y}_{M} be the sequence of the text sentence inputs used in testing. We then define the normalized training loss by

Then, the prediction at testing time for a new input xx is given by

where ωl(q)=Wlq\omega_{l}(q)=W_{l}q represents the linear transformation and σl\sigma_{l} is an element-wise nonlinear activation function. Similarly, ωl′(q)=Wl′q\omega_{l}^{\prime}(q)=W_{l}^{\prime}q and σl′\sigma_{l}^{\prime} is an element-wise activation function.

The following theorem provides an insight on the role of the contrastive batch size to close the accuracy gap from contrastive models to their supervised counterparts:

Suppose that the activation functions σ\sigma and σl′\sigma_{l}^{\prime} are 1-Lipschitz and positive homogeneous for all l∈[L−1]l\in[L-1]. Let G={y↦G(y):(∀l∈[L−1])[∥Wl∥F≤Ml]∧∥(WL)k∥F≤ML,k}\mathcal{G}=\{y\mapsto G(y):(\forall l\in[L-1])[\|W_{l}\|_{F}\leq M_{l}]\wedge\|(W_{L})_{k}\|_{F}\leq M_{L,k}\} and F={x↦F(x):(∀l∈[L′−1])[∥Wl′∥F≤Ml′]∧∥(WL′′)k∥F≤ML′,k′}\mathcal{F}=\{x\mapsto F(x):(\forall l\in[L^{\prime}-1])[\|W_{l}^{\prime}\|_{F}\leq M_{l}^{\prime}]\wedge\|(W_{L^{\prime}}^{\prime})_{k}\|_{F}\leq M_{L^{\prime},k}^{\prime}\} where (Wl)k(W_{l})_{k} is the kk-th row of WlW_{l}. Then, for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

For general models beyond the standard deep neural networks, the following theorem provides a similar insight on the importance of the contrastive batch size:

Let F\mathcal{F} be a set of maps x↦F(x)x\mapsto F(x) and G\mathcal{G} be a set of maps y↦G(y)y\mapsto G(y). Then, for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

Data and Model Scaling

Starting from the ALIGN dataset, which contains 1.7B weakly-aligned image-text pairs (Jia et al., 2021), we collect 5B more image-text pairs, hence expanding the dataset size by roughly 4 times. We acquire these 5B image-text pairs from the JFT dataset. In the JFT dataset, each image is associated with one or multiple classes. We convert these classes into a text sequence: “{class_1} and {class_2} and … and {class_k}”. We combine the instances from JFT into ALIGN, forming our extended dataset, which we denote by ALIGN+JFT.

To tokenize the texts from ALIGN+JFT, we randomly sample 200M sentences and use them to train a sentence piece model (Kudo and Richardson, 2018) with a vocabulary size of 32K pieces. Using this tokenizer, we filter and discard the text sequences which are longer than 64 tokens. In our preliminary experiments, we find that using a tokenizer directly learned from ALIGN+JFT and adapting this filtering step can boost our top-1 accuracy on ImageNet ILSVRC-2012 by more than 1%.

2 Larger Model Architectures

We find that for the same computational budget, it is more beneficial to invest in scaling up the image encoder, rather than the text encoder. Thus, for our image encoder, we use the largest CoatNet architecture (Dai et al., 2021) due to its proven large learning capacity. This network has convolution layers followed by attention layers. For our text encoder, we use a simple transformer (Vaswani et al., 2017). Unlike ALIGN (Jia et al., 2021) which extracts the final text representations using a [CLS] token similar to BERT (Devlin et al., 2018), we average the representations across all steps at the top layer of our transformer.

By experimenting with the scaling benefits for small models and generalizing these findings to larger models, we choose three model sizes, termed BASIC-{S,M,L} for Small, Medium, and Large. In Appendix A, we report our architectures and their computational costs and provide a small-scale study on the effects of scaling model sizes.

Pretraining and Finetuning

To further speed up the training of our networks, we make use of pretraining. In our experiments, we first pretrain the image encoder on a large labeled dataset using the standard softmax classification loss. After pretraining the image encoder, we fix all of its weights and just train the text encoder using contrastive learning. Compared to contrastive learning with GradAccum, the pretraining-finetuning procedure is much more efficient in terms of peak memory usage. This is because we never have to compute the gradients of both the image encoder and the text encoder, which allows automated compiler optimizations to free up unused memory on-the-fly.

Despite its reduced memory usage, we find that this pretraining-finetuning scheme has a weakness: it never exposes the image encoder to noisy image-text data, which makes the image encoder fail on certain tasks. For instance, while some pretrained-and-finetuned models achieve similar accuracy to their contrastive counterparts on ImageNet or CIFAR, they completely fail on an easier task – MNIST. This is because our pretraining labeled dataset, which mostly consists of natural images, has very few digit images. Meanwhile, our noisy image-text dataset has plenty instances that can teach a model certain optical character recognition skills.

As will be shown in Section 9, our best experimental results are achieved using a hybrid procedure. First, we pretrain the image encoder on a large labeled dataset, then fix its weights and train the text encoder using the contrastive loss on our image-text dataset. Finally, we finetune both image and text encoders, using our GradAccum technique when needed. In Section 10, we present ablation studies to analyze the effects of pretraining, finetuning, and other alternative training procedures.

Experiments

For pretraining (Section 8), we use the JFT dataset. This dataset has been used in previous publications (Zhai et al., 2021; Dosovitskiy et al., 2021; Kolesnikov et al., 2020), but it has been constantly expanded. The JFT version used in our experiments has 5B images, each of which can be associated to one or multiple labels out of 29K possible classes.

A problem with training on large auto-curated datasets like ALIGN and JFT is that these datasets might unintentionally contain examples from our test sets. To avoid such contaminations, we filter all instances in our training data that has a structural similarity index (SSIM (Wang et al., 2004)) of at least 0.5 with any image from our evaluation benchmarks.

We train our models with our own optimizer called AdaFactorW, adapted from two existing ones: AdaFactor (Shazeer and Stern, 2018) and AdamW (Loshchilov and Hutter, 2019). Specifically, we factorize our second gradient moments like AdaFactor, and decouple the weight decay from all moments like AdamW. To further save memory, we follow Zhai et al. (2021) and store the first gradient moments in bfloat16. We observe, however, that while we can store these moments in bfloat16, we need to convert them into float32 prior to computing our weight updates to avoid numerical instability.

For all experiments, we train and evaluate with the image resolution of 224x224. While we can increase this resolution to gain performance (Tan and Le, 2019, 2021; Touvron et al., 2019; Radford et al., 2021; Jia et al., 2021), we choose not to do this and instead, reserve our computational resources for scaling up our model and our batch size. All of our other hyper-parameters can be found in Appendix B.

2 Results on Image Classification Benchmarks

We first present the zero-shot transfer performance of our BASIC models. We compare our models BASIC-{S,M,L} to CLIP models with similar computational budgets (Radford et al., 2021) on 17 natural image classification datasets. Details about these datasets can be found in Appendix C.

Zero-shot transfer models require textual prompts, which we take from CLIP (Radford et al., 2021) for consistent comparison. We suspect that using prompts which are tuned for our models can further improve our results as shown in (Lester et al., 2021), because the text sequences in our training data have a different distribution from the text sequences in CLIP.

Table 3 shows the comparison. From the table, it can be seen that BASIC models conclusively outperform CLIP models of the same computational budgets. Specifically, BASIC models demonstrate higher accuracy than CLIP models on 13 out of 17 datasets. On the Oxford IIIT Pets dataset, BASIC-L achieves 97.9% mean per-class recall which sets a new state-of-the-art, despite having never seen any training images from the dataset. On ther other hand, BASIC models have low accuracy on EuroSAT, MNIST, and PCam. MNIST is where BASIC models perform worst, where the highest accuracy is only 40.3%. We discuss these failure cases further in Section 11.

3 Results on Robustness Benchmarks

Despite the convincing accuracy of modern deep learning models on ImageNet, concerns have been raised about their robustness (Szegedy et al., 2013). These concerns arise from a common failure mode of ImageNet-trained models: subtle changes to their input images, which are imperceptible to humans, can wildly alter their predictions with high confidence, e.g., from “golden retriever” into “goldfish”.

In CLIP, Radford et al. (2021) have studied certain aspects of this failure mode. They have not drawn a definitive conclusion whether to attribute such failures to deep learning, ImageNet, or a combination of them. Instead, they cautioned against generalizing “too far from [their] initial findings”.

Here we advance CLIP’s study on the robustness of zero-shot models in two aspects. First, we analyze our BASIC models presented previously in Section 9.2 and reaffirm that zero-shot models are indeed more robust than their ImageNet-trained counterparts. Second, we perform an experiment which suggests that ImageNet’s labeled training examples might be responsible for making ImageNet-trained models less robust. Similar to CLIP’s authors, we caution readers that our experiment presents a correlation, not a causal analysis. In other words, we do not attribute the lack of robustness in ImageNet-trained models to the dataset.

We evaluate BASIC-{S,M,L} models from Section 9.2 on 5 robustness benchmarks derived from ImageNet: ImageNet-A (Hendrycks et al., 2021b), ImageNet-R (Hendrycks et al., 2021a), ImageNet-V2 (Recht et al., 2019), ImageNet-Sketch (Wang et al., 2019), and ObjectNet (Barbu et al., 2019). These benchmarks have images in all or a subset of the 1000 ImageNet classes, but their inputs are selected from certain natural distribution shifts, which can cause ImageNet-trained models to make many more mistakes. Our numerical results are highlighted in Table 1 from Section 1. To visualize the data trend, in Figure 3, we plot the accuracy of zero-shot models – BASIC, CLIP (Radford et al., 2021), and ALIGN (Jia et al., 2021) – and of 200 ImageNet-trained models collected by Taori et al. (2020).

The data points from our BASIC models extend the prediction from CLIP: zero-shot transfer models have a higher effective robustness (Radford et al., 2021; Taori et al., 2020), i.e. they have higher robustness than ImageNet-trained models with the same ImageNet accuracy. To extrapolate from this trend, we fit a logistic curve (red dashes) to the zero-shot accuracy and robustness of zero-shot transfer models. The plot shows that this line meets the ideal robustness line at about 91% on the x-coordinate. In other words, our plot predicts that a model which achieves about 91% zero-shot accuracy on ImageNet, i.e., just slightly better than the state-of-the-art ImageNet-trained model (Dai et al., 2021), will also achieve the ideal robustness.

We now study the effect of ImageNet’s labeled data on our models. We take the converged BASIC-{S,M,L} checkpoints from Section 9.2 and continue to train them on 1%, 10%, 20%, and 50% of ImageNet’s labeled examples. Note that we continue training these checkpoints using the contrastive loss, where the names of ImageNet classes are utilized as text sequences accompanying their images. This is different from CLIP’s linear probing approach, which we do not perform to avoid potential confounding factors from our study, e.g. linear classifiers might behave differently from our zero-shot transfer classifiers. We then compare the accuracy of these finetuned models on ImageNet and on the 5 robustness benchmarks. The results are visualized in Figure 4.

The figure shows a clear trend: as our model learns from more labeled ImageNet data, they become more accurate on ImageNet, but these gains do not carry over to the robustness benchmarks. Specifically, with the exception of ImageNet-V2, for which the accuracy of finetuned models stay the same (for BASIC-L) or slightly increase (for BASIC-M), for all other robustness benchmarks, the finetuned models suffer from significant performance drops. In the extreme case, 3% accuracy gain on ImageNet leads to 8.3% accuracy drop for ImageNet-R.

What makes our finetuned models less robust? A quick glance at our results might lead to the superficial conclusion that our models have overfit, as our finetuning sets are a lot smaller than ALIGN and JFT. However, this overfitting theory does not explain the trend observed in Figure 4: training on more labeled ImageNet data makes our models less robust. We hope our observation invites further causal analysis on the effects of ImageNet’s labeled data.

Ablation Study

To demonstrate the role of large batch sizes, we conduct several controlled experiments for BASIC-S and BASIC-M on ALIGN. For both BASIC-S and BASIC-M, we fix all hyperparameters as shown in Table 6, but vary the batch size and the number of training steps. Models that are trained with larger batch sizes are trained with fewer steps to guarantee that they “see” the same number of examples. Table 4 presents the ImageNet top-1 zero-shot accuracy of all models at the end of their training, and Figure 5 visualizes their entire validation accuracy curves.

Table 4 and Figure 5 both suggest that training for more steps cannot equalize the benefit of large batch sizes. This phenomenon is consistent with the observation from SimCLR (Chen et al., 2020a, b): large batch sizes help contrastive learning. SimCLR observes that the benefit of large batch sizes saturate at 8192. In contrast, our results in Table 4 and Figure 5 show that lager batch sizes continue to benefit our models until 32768, and even until 65536 as in Section 9.2. We suspect that the benefits for large batch sizes do not saturate because our dataset size and model size are both larger than those of SimCLR, e.g. ALIGN with 1.7B examples compared to ImageNet with 1M examples, and BASIC-{S, M} compared to ResNet-{50,101,152}. This comparison suggests the benefits of our method – combined scaling.

2 Data Scaling, Model Scaling, and Pretraining

We now study the benefits of other scaling dimensions, data and model scaling, on the quality of our models. We also study pretraining as an alternate training procedure to contrastive learning. We train BASIC-{S,M} models in 6 different settings and plot their final top-1 ImageNet accuracy in Figure 6. Below, we compare and analyze the settings.

First, BASIC-S and BASIC-M respectively gain 5.3% and 5.8% accuracy when we expand the contrastive training dataset from ALIGN to ALIGN+JFT. These gains, albeit large, are smaller than the gain by enlarging the model size, e.g., 11.7% when going from BASIC-S to BASIC-M.

Next, we study the effects of pretraining image encoders on JFT. As can be seen from Figure 6, models whose image encoders are pretrained on JFT and whose text encoders are subsequently trained on ALIGN, i.e., the red bars, have similar performances with models trained from scratch on ALIGN+JFT, i.e., the blue bars. Their similar accuracy suggest that the training losses – softmax cross-entropy or contrastive – have a much smaller effect than the datasets. In other words, when given the same dataset, the image encoders in BASIC models learn to become equally good, regardless of their loss functions.

To our surprise, training the text encoders for JFT-pretrained image encoders on ALIGN+JFT gains 1% for BASIC-S and 1.8% for BASIC-L, compared to training these text encoders on ALIGN. We suspect that these gains come from better representations for the textual prompts, since the models trained on ALIGN+JFT also sees the textual prompts which consist of clean JFT class names. However, this speculation needs a more thorough study to understand.

Finally, we find that if we take a converged model whose image encoder is pretrained on JFT and whose text encoder is trained on ALIGN+JFT, then we continue to train both its image encoders and text encoders at a small learning rate. This extra training phase gains us 1.4% ImageNet accuracy for BASIC-S, 0.6% for BASIC-M, and 0.4% for BASIC-L (not shown in this section).

Limitations

Despite the strong results of our zero-shot transfer classifier, especially on natural image classification tasks, they inevitably have their shortcomings. In this section, we discuss the problems that we find with our BASIC models.

We emphasize the failures of BASIC on two test sets where BASIC models are much worse than CLIP models: EuroSAT, MNIST, PatchCamelyon (PCam) (see Table 3 from Section 9.2). Here, we summarize that BASIC models fail on MNIST and PCam because our training datasets ALIGN and JFT have relatively few images of handwritten digits and of lymph nodes, which are the domain of these datasets. Compared to MNIST and PCam, BASIC models do better on EuroSAT which consist of satellite land images, but their accuracy is lower than that of CLIP models. This is because the class names for these satellite images are not very descriptive to BASIC models. More analysis for these failures are in Appendix G.

In this paper, we use the prompts from CLIP (Radford et al., 2021) to make our results comparable to previous works. In Appendix G, we present examples which show that prompts that are badly chosen or adversarially chosen can hurt the accuracy of zero-shot transfer models by flipping their predictions. These examples suggest that prompt engineering is an important research topic to make zero-shot transfer models robust and reliable, but the topic is of out of the scope of this paper.

As reported in Appendix E, the hardware and training time for our models are not small. Despite the training cost, we can use the models in this paper without any finetuning, and hence avoid the finetuning cost. We hope that future research can reduce our models’ training expense, e.g., larger accelerator memory can save the extra re-materialization steps.

Conclusion

Zero-shot transfer learning represents a new paradigm where pretrained models can be used directly for downstream applications without collecting any application-specific data. However, in order to become practical for real-world applications, zero-shot transfer models need to bridge the accuracy gap to supervised and semi-supervised models.

In this paper, we presented combined scaling techniques that significantly boost the performance of zero-shot transfer models. We show that scaling in the data size, the model size, and the batch size all improves the final model’s accuracy and robustness. To overcome the memory limit arising from combined scaling, we devise a simple gradient accumulation method based on re-materialization.

References

Appendix A Model sizes

In our preliminary experiments, we experimented with different model sizes. Table 5 presents the final, most compute-to-performance efficient model sizes, which we use throughout the paper.

Appendix B Hyperparameters and other implementation details

Our training and evaluation code will eventually be released. Here, we summarize a few important details. All of our hyper-parameters are in Table 6.

Other than the decoupled weight decay in AdaFactorW, we do not use any other regularization technique. In fact, we find that with BASIC-S and BASIC-M, if we add other forms of regularization such as stochastic depth (Huang et al., 2017) or dropout (Srivastava et al., 2014), our ImageNet top-1 accuracy drops substantially. This suggests that our datasets are very large and perhaps in such situation, regularization techniques do more harm than good by causing optimization difficulty to our models.

Another important effect of not using regularization in our training framework is to make the re-materialization steps in Section 4.2 consistent. If we apply random perturbations to our forward passes, e.g. by skipping layers like in stochastic depth or by setting random values to zeros, then two forward passes for re-materialization (see Lines 2-5 and 11-14 in Algorithm 1) will compute two different passes. While we could treat such difference as a form of regularization noise, our early experiment show that with dropout-like regularizations, our training loss stays relatively large throughout the course of training. This observation suggests that the noise causes some optimization difficulty to our models, so we opt not to use any dropout-like regularization.

Appendix C Evaluation Datasets Details

Here, we present the details of the datasets which we use to evaluate our BASIC models in Section 9.2. It is worth noting that not all these datasets use the accuracy as the performance metric. This is because these datasets have a certain level of imbalance between their classes, as well as other properties that make them accuracy not the best suitable metric for them. For instance, the dataset Caltech-101 has a class called “Background” which refers to any image that does not belong to its predefined 101 classes. One certainly cannot come up with a textual description that describes this “class”. As such, Caltech-101 is evaluated using mean per-class recall. Details about other datasets are in Table 7.

Appendix D Further Discussion on Robustness

In Section 9.3, we present a surprising result: finetuning converged BASIC checkpoints on more ImageNet labeled data leads to worse robustness results. The metric for robustness in Section 9.3 is the average top-1 accuracy of the finetuned models on 5 robustness benchmarks derived from ImageNet (Hendrycks et al., 2021b, a; Recht et al., 2019; Barbu et al., 2019; Wang et al., 2019). It turns out that each of these benchmarks can demonstrate slightly different results for the finetuned models. Here, we discuss such benchmarks.

This dataset is collected in a process that closely follows the process to collect and annotate the images in the standard ILSVRC-2012 validation set, which is typically referred to as “ImageNet” in the literature (and our paper as well). As such, gains observed on ImageNet often transfer to ImageNet-V2. Recent works such as EfficientNets (Tan and Le, 2019, 2021) or ViT (Dosovitskiy et al., 2021) also demonstrate the similar trend. For our experiment in Section 9.3, BASIC-M’s robustness accuracy improves along with its ImageNet accuracy, following this trend. However, BASIC-L’s robustness does not. We suspect this trend is because BASIC-L’s learning capacity is larger than that of BASIC-M, so BASIC-L picks up more “spurious” patterns from ImageNet, making it less robust than BASIC-M.

ImageNet-R is a special robustness dataset in our study. Not only of our BASIC models but also other zero-shot models – CLIP and ALIGN – are more accurate on ImageNet-R than they are on ImageNet (see Table 1). These data points alone would suggest that ImageNet-R is somewhat easier than ImageNet, until we look at the significant accuracy drops for other methods on ImageNet-R. For instance, Noisy Student (Xie et al., 2020) and Meta Pseudo Labels (Pham et al., 2021) respectively achieve only 74.9% and 72.7% accuracy on ImageNet-R, despite their accuracy of 88.4% and 90.2% on ImageNet ILSVRC-2012. The real reason for such discrepancy in ImageNet-R is that ImageNet-R is collected by selecting the ImageNet classes from visual art pieces, such as paintings, cartoons, graffiti, origami, and sculptures. These art pieces are often displayed in a clean environment, free of noises such as multiple classes per image, making the images easier to recognize. As such, BASIC, CLIP, and ALIGN, all perform better on ImageNet-R. However, ImageNet-R images have a drastically different distribution compared to ImageNet labeled training images, as they are respectively art images and natural images. This is why ImageNet-trained models display a much lower accuracy on ImageNet, compared to zero-shot models.

From Table 1, it can be seen that BASIC model’s improvement over ALIGN and CLIP on Object is significantly lower than others on other benchmarks, i.e., 6.6% compared to more than 8% (except for ImageNet-R, for which the accuracy of all models are saturated at over 90%). We find out the reason is that, even though ObjectNet has images from the same classes with ImageNet, these objects turn out to have their own more descriptive names, e.g. the class name “chairs” in ImageNet could be “chairs by [viewpoint]” or “chairs with [background]”. As we later show in Section G, using different class names and prompts can affect our results. This effect has also been observed in CLIP (Radford et al., 2021). Here, we take the same class names and prompts for ImageNet and use them for ObjectNet. We suspect that using ObjectNet-specific class names and prompts can improve our result.

Appendix E Computational Cost

All of our models are implemented in TensorFlow (Abadi et al., 2016) and trained on Tensor Processing Units (TPUs (Jouppi et al., 2017)). Our BASIC-S and BASIC-M models are all trained on TPUv3 chips, while our BASIC-L models are trained on TPUv4 chips. These TPUv4 chips in their MegaCore mode can offer 32GB of memory, out of which our BASIC-L models use 30.1GB, which means that our model essentially saturates the TPU’s memory. We note that oftentimes, a small portion of TPU memory needs to be reserved for their low-level infra systems. Therefore, our BASIC-L models essentially saturate the accelerators with the largest memory currently available. Given this memory usage, we use Algorithm 1 with the microbatch size M=8192M=8192 and the batch size N=65536N=65536 to train this model. Table 8 summarizes the training cost for each phase of our models BASIC-{S,M,L} as in Section 9.2.

Appendix F Qualitative Analysis: Successful Classification Examples

Zero-shot transfer models open the door to versatile applications. This section is dedicated to demonstrating their versatility. In Figure 7, we visualize some predictions of our best model, BASIC-L, on instances that are less expected on traditional image classification benchmarks. We come up with the text sequences and demonstrate that the model can indeed align images to the most appropriate sequence.

Appendix G Failure Analysis

Most machine learning models fail in certain tests. It is important to identify such failure cases, to understand the failing causes, and if possible, to come up with fixes. Here, we first look at the test benchmarks in Table 3 from Section 9.2 where BASIC models perform worse than CLIP models. We identify the cause of failures for BASIC models and recommend certain fixes that can improve their performance. Then, in Section G.2, we present some erroneous behaviors of BASIC models via selected examples. These examples reveal some weaknesses of zero-shot transfer models, and invite future research to improve them.

From Section 9.2, we see that BASIC models have particularly low performance on EuroSat (Helber et al., 2018), MNIST (LeCun et al., 2010), and Patch Camelyon (Veeling et al., 2018). The accuracy of BASIC-L on these datasets are 51.0%, 40.3%, and 59.6% respectively. For what it’s worth, BASIC-L’s accuracy are better than those of our smaller models, i.e., BASIC-S and BASIC-M, so our central message in this paper – scaling helps – is not altered. Here, we focus on analyzing the failures of BASIC-L.

PCam is perhaps the most sensitive dataset among the three benchmarks where BASIC-L performs poorly. This dataset consists of images extracted from histopathologic scans of lymph node sections, and models are asked to make the binary prediction – whether an input image has a cancerous lymph node or note. For such an important task, the top-1 accuracy of both BASIC-L (59.6%) and CLIP (63.0%) are far below the bars for practical deployments. We remark that PCam is a binary classification task, so the accuracy of BASIC-L and CLIP are just slightly above random guessing. Their poor performance, however, are quite understandable: classifying lymph nodes requires much more specific training, compared to classifying common natural images. As our training data are weakly crawled and automatically curated from the internet, without any emphasis on medical images, our BASIC-L model cannot learn enough to perform well on PCam. We suspect the same speculation also holds for CLIP, as their data collection and curation process is comparable to ours. Finally, the low accuracy of CLIP and BASIC models on PCam is an assertion that despite the benefits of zero-shot transfer models, they are not ready to be deployed to tasks that require in-domain expertise, e.g. medical knowledge.

This dataset consists of satellite images taken for certain types of lands. Models are asked to classify input images into one out of 10 given types of lands. The land types can be seen in Figure 8. The failure of BASIC-L on EuroSAT is an example for the importance of prompt engineering in zero-shot transfer learning for image-text models. In Figure 8, we show that by changing the dataset’s class names and the model’s set of prompts, into words and phrases that essentially have the same meaning to humans, we can improve the accuracy of BASIC-L from 51.0% to 55.7%. We do not further explore the changes in class names and prompts to improve BASIC-L’s performance on EuroSAT, as they belong to a different topic from the focus of this paper – combined scaling. However, our findings on this EuroSAT dataset suggests that contrastive image-text models do not really “understand” texts. This is perhaps because of the low quality of the texts in our training data, unlike the millions of words from books and articles like the training data of NLP models such as BERT (Devlin et al., 2018).

MNIST is a classical dataset in computer vision for handwritten digit classification. Simple models can achieve more than 99.5% accuracy, and yet BASIC-L achieves the humble 40.3% accuracy. Unlike the case of PCam, i.e. there is not enough training data in our training dataset, for MNIST, we find that the ALIGN dataset has a fair amount of images that contain digits, either handwritten or printed. This means that the image encoder of BASIC-L has seen digit figures, and suggests that the failures might be more attributable to the text encoder, similar to the case of EuroSAT. In Figure 9, we show the confusion matrices of BASIC-L models with three sets of class names: using the digits such as {‘0’, ‘1’, …}, using the the texts such as {‘one’, ‘two‘’, …}, and using both such as {‘0 or zero’, ‘1 or one’, …}. Unfortunately, we cannot improve BASIC-L’s accuracy on MNIST, like we did for EuroSAT: BASIC-L’s accuracy is low in all three cases, but the confusion matrices are visibly different: BASIC-L models ‘thinks’ that many digits look like ‘3’ for the digit-only class names, but many digits look like ‘1 or one’ in the digit-and-text class names. Again, humans who understand languages will not make these mistakes. We think these mistakes constitute a new type or robustness failures, which we hope will invite further research.

G.2 Example failure cases

From the confusion matrices of BASIC-L on two benchmarks, EuroSAT (Helber et al., 2018) and MNIST (LeCun et al., 2010), we observe that the prompts and class names are crucial for the performance of zero-shot transfor models. Here, we select and present a few examples to demonstrate the failures of BASIC-L. Figure 10 visualizes these examples.

Appendix H Proofs

In this appendix, we complete the proof of Theorem 1 and Theorem 2 by gradually analyzing the gap from the general case to the special case.

Let F\mathcal{F} be a set of maps x↦F(x)x\mapsto F(x) and G\mathcal{G} be a set of maps y↦G(y)y\mapsto G(y). Then, for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

Proof We first decompose the difference as follows:

For the inside of the expectation in the first term, we can write it as

Using Lemma 4 (see below) with the assumption that y^1,y^2,…,y^B∼iidpy\hat{y}_{1},\hat{y}_{2},\dots,\hat{y}_{B}\stackrel{{\scriptstyle iid}}{{\sim}}p_{y} and exp⁡(F(x)⊤G(y))≤c1\exp(F(x)^{\top}G(y))\leq c_{1} with probability one, we have that for any δ>0\delta>0 and x∈Xx\in\mathcal{X}, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

Thus, by setting r=2c8Br=\frac{2c_{8}}{\sqrt{B}},

Here, using equation 12 with union bounds, we have that for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

Therefore, for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

Combining equations equation 11 and equation 13 with union bound, we have that for any δ>0\delta>0, with probability at least 1−δ1-\delta,

we have that for any δ>0\delta>0, with probability at least 1−δ1-\delta,

The proof of Lemma 3 partially builds up on Lemma 4 below. Lemma 4 is a direct application of previous results (Bartlett and Mendelson, 2002; Mohri et al., 2012; Shalev-Shwartz and Ben-David, 2014) to our problem. We provide a proof of Lemma 4 by slightly modifying the proof of a previous work (Mohri et al., 2012, Theorem 3.1) for the completeness (the proof utilizes the nonnegativity of hh to have a slightly tighter bound than Theorem 26.5 of Shalev-Shwartz and Ben-David, 2014):

Let H\mathcal{H} be a set of maps z↦h(z)z\mapsto h(z) such that h(z)∈[0,λ]h(z)\in[0,\lambda] for all zz in its domain. Then, for any δ>0\delta>0, with probability at least 1−δ1-\delta over an i.i.d. draw of mm i.i.d. samples (zi)i=1m(z_{i})_{i=1}^{m}, the following holds for all maps h∈Hh\in\mathcal{H}:

Proof Let S=(zi)i=1mS=(z_{i})_{i=1}^{m} and S′=(zi′)i=1mS^{\prime}=(z_{i}^{\prime})_{i=1}^{m}. Define

To apply McDiarmid’s inequality to φ(S)\varphi(S), we compute an upper bound on ∣φ(S)−φ(S′)∣|\varphi(S)-\varphi(S^{\prime})| where SS and S′S^{\prime} be two test datasets differing by exactly one point of an arbitrary index i0i_{0}; i.e., Si=Si′S_{i}=S^{\prime}_{i} for all i≠i0i\neq i_{0} and Si0≠Si0′S_{i_{0}}\neq S^{\prime}_{i_{0}}. Then,

Thus, by McDiarmid’s inequality, for any δ>0\delta>0, with probability at least 1−δ1-\delta,

where the fist line follows the definitions of each term, the second line uses the Jensen’s inequality and the convexity of the supremum, and the third line follows that for each ξi∈{−1,+1}\xi_{i}\in\{-1,+1\}, the distribution of each term ξi(h(zi′)−h(zi))\xi_{i}(h(z_{i}^{\prime})-h(z_{i})) is the distribution of (h(zi′)−h(zi))(h(z_{i}^{\prime})-h(z_{i})) since SS and S′S^{\prime} are drawn iid with the same distribution. The forth line uses the subadditivity of supremum.

Let F\mathcal{F} be a set of maps x↦F(x)x\mapsto F(x) and G\mathcal{G} be a set of maps y↦G(y)y\mapsto G(y). Then,

Proof Since the derivative of exponential function exp⁡(q)\exp(q) is exp⁡(q)\exp(q) and we assume exp⁡(F(x)⊤G(y))≤c1\exp(F(x)^{\top}G(y))\leq c_{1}, the exponential function in the bounded domain of exp⁡(F(x)⊤G(y))≤c1\exp(F(x)^{\top}G(y))\leq c_{1} has Lipschitz constant of c1c_{1}. Therefore,

Let F\mathcal{F} be a set of maps x↦F(x)x\mapsto F(x) and G\mathcal{G} be a set of maps y↦G(y)y\mapsto G(y). Then,

where Fk={x↦F(x)k:F∈F}\mathcal{F}_{k}=\{x\mapsto F(x)_{k}:F\in\mathcal{F}\} and Gk={y↦G(y)k:G∈G}\mathcal{G}_{k}=\{y\mapsto G(y)_{k}:G\in\mathcal{G}\}.

Using a vector-contraction inequality, i.e., Corollary 4 of (Maurer, 2016) with the additional expectation of both sides of the inequality, we have that

H.1.2 Combining all together for the general case

We now combine the above lemmas to complete the proof of Theorem 2:

Proof [Proof of Theorem 2] From Lemma 3, we have that for any for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

where ωl(q)=Wlq\omega_{l}(q)=W_{l}q and σl\sigma_{l} is an element-wise activation function. Similarly, ωl′(q)=Wl′q\omega_{l}^{\prime}(q)=W_{l}^{\prime}q and σl′\sigma_{l}^{\prime} is an element-wise activation function.

Suppose that the function σl\sigma_{l} is 1-Lipschitz and positive homogeneous for all l∈[L−1]l\in[L-1] and ∥y∥2≤c7\|y\|_{2}\leq c_{7} for all y∈Yy\in\mathcal{Y}. Let G={y↦G(y):(∀l∈[L])[∥Wl∥F≤Ml]}\mathcal{G}=\{y\mapsto G(y):(\forall l\in[L])[\|W_{l}\|_{F}\leq M_{l}]\}. Then,

Suppose that the function σl′\sigma_{l}^{\prime} is 1-Lipschitz and positive homogeneous for all l∈[L−1]l\in[L-1] and ∥x∥≤c8\|x\|\leq c_{8} for all x∈Xx\in\mathcal{X}. Let F={x↦F(x):(∀l∈[L′−1])[∥Wl′∥F≤Ml′]∧∥(Wl′)k∥F≤ML′,k′}\mathcal{F}=\{x\mapsto F(x):(\forall l\in[L^{\prime}-1])[\|W_{l}^{\prime}\|_{F}\leq M_{l}^{\prime}]\wedge\|(W_{l}^{\prime})_{k}\|_{F}\leq M_{L^{\prime},k}^{\prime}\} where (Wl′)k(W_{l}^{\prime})_{k} is the kk-th row of Wl′W_{l}^{\prime}. Suppose that the function σl\sigma_{l} is 1-Lipschitz and positive homogeneous for all l∈[L−1]l\in[L-1] and ∥y∥≤c7\|y\|\leq c_{7} for all y∈Yy\in\mathcal{Y}. Let G={y↦G(y):(∀l∈[L−1])[∥Wl∥F≤Ml]∧∥(WL)k∥F≤ML,k}\mathcal{G}=\{y\mapsto G(y):(\forall l\in[L-1])[\|W_{l}\|_{F}\leq M_{l}]\wedge\|(W_{L})_{k}\|_{F}\leq M_{L,k}\} where (Wl)k(W_{l})_{k} is the kk-th row of WlW_{l}. Then,

Proof From Theorem 1 of (Golowich et al., 2018), we have that

This proves the first statement. For the second statement, since ∥(Wl)k∥F≤ML,k\|(W_{l})_{k}\|_{F}\leq M_{L,k}, we have that

This implies that ∥Wl∥F≤∑k=1DML,k2\|W_{l}\|_{F}\leq\sqrt{\sum_{k=1}^{D}M_{L,k}^{2}}. Thus, using Lemma 7,

H.3 Combining all together for the special case with deep neural networks

We now combine the above lemmas to complete the proof of Theorem 1 for the special case with deep neural networks:

Proof [Proof of Theorem 1] From Lemma 3, for any F\mathcal{F} and G\mathcal{G}, and for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}:

Finally, using Lemma 8 for the particular F\mathcal{F} and G\mathcal{G} with deep neural networks, we have that

Combining those, we have that for any δ>0\delta>0, with probability at least 1−δ1-\delta, the following holds for all F∈FF\in\mathcal{F} and G∈GG\in\mathcal{G}: