W HEN V ISION T RANSFORMERS O UTPERFORM R ES N ETS WITHOUT P RE - TRAINING OR S TRONG D ATA A UGMENTATIONS
A BSTRACT
Vision Transformers (ViTs) and MLPs signal further efforts on replacing handwired features or inductive biases with general-purpose neural architectures.
Existing works empower the models by massive data, such as large-scale pre-training and/or repeated strong data augmentations, and still report optimization-related problems (e.g., sensitivity to initialization and learning rates).
Hence, this paper investigates ViTs and MLP-Mixers from the lens of loss geometry, intending to improve the models’ data efﬁciency at training and generalization at inference.
Visualization and Hessian reveal extremely sharp local minima of converged models.
By promoting smoothness with a recently proposed sharpnessaware optimizer, we substantially improve the accuracy and robustness of ViTs and MLP-Mixers on various tasks spanning supervised, adversarial, contrastive, and transfer learning (e.g., +5.3% and +11.0% top-1 accuracy on ImageNet for ViT-B/16 and Mixer-B/16, respectively, with the simple Inception-style preprocessing).
We show that the improved smoothness attributes to sparser active neurons in the ﬁrst few layers.
The resultant ViTs outperform ResNets of similar size and throughput when trained from scratch on ImageNet without large-scale pre-training or strong data augmentations.
Model checkpoints are available at https: /github.com/google-research/vision_transformer .
I NTRODUCTION
Transformers (Vaswani et al., 2017) have become the de-facto model of choice in natural language processing (NLP)
(Devlin et al., 2018;
Radford et al., 2018).
In computer vision, there has recently been a surge of interest in end-to-end Transformers (Dosovitskiy et al., 2021; Touvron et al., 2021b;
Liu et al., 2021b; Fan et al., 2021; Arnab et al., 2021; Bertasius et al., 2021;
Akbari et al., 2021) and MLPs (Tolstikhin et al., 2021; Touvron et al., 2021a; Liu et al., 2021a; Melas-Kyriazi, 2021), prompting the efforts to replace hand-wired features or inductive biases with general-purpose neural architectures powered by data-driven training.
We envision these efforts may lead to a uniﬁed knowledge base that produces versatile representations for different data modalities, simplifying the inference and deployment of deep learning models in various application scenarios.
Despite the appealing potential of moving toward general-purpose neural architectures, the lack of convolution-like inductive biases also challenges the training of vision Transformers (ViTs) and
MLPs.
When trained on ImageNet (Deng et al., 2009) with the conventional Inception-style data preprocessing (Szegedy et al., 2016), Transformers “yield modest accuracies of a few percentage points below ResNets of comparable size” (Dosovitskiy et al., 2021).
To boost the performance, existing works resort to large-scale pre-training (Dosovitskiy et al., 2021; Arnab et al., 2021; Akbari et al., 2021) and repeated strong data augmentations (Touvron et al., 2021b), resulting in excessive demands of data, computing, and sophisticated tuning of many hyperparameters.
For instance,
Dosovitskiy et al.
(Dosovitskiy et al., 2021) pre-train ViTs using 304M labeled images, and Touvron et al.
(2021b) repeatedly stack four strong image augmentations.
In this paper, we show ViTs can outperform ResNets (He et al., 2016) of even bigger sizes in both accuracy and various forms of robustness by using a principled optimizer, without the need for largescale pre-training or strong data augmentations.
MLP-Mixers (Tolstikhin et al., 2021) also become on par with ResNets.
We ﬁrst study the architectures fully trained on ImageNet from the lens of loss landscapes and draw the following ﬁndings.
First, visualization and Hessian matrices of the loss landscapes reveal that
Transformers and MLP-Mixers converge at extremely sharp local minima, whose largest principal curvatures are almost an order of magnitude bigger than ResNets’.
Such effect accumulates when the gradients backpropagate from the last layer to the ﬁrst, and the initial embedding layer suffers the largest eigenvalue of the corresponding sub-diagonal Hessian.
Second, the networks all have very small training errors, and MLP-Mixers are more prone to overﬁtting than ViTs of more parameters (because of the difference in self-attention).
Third, ViTs and MLP-Mixers have worse “trainabilities” than ResNets following the neural tangent kernel analyses (Xiao et al., 2020).
Therefore, we need improved learning algorithms to prevent the convergence to a sharp local minimum when it comes to the convolution-free ViTs and MLP-Mixers.
The ﬁrst-order optimizers (e.g., SGD and Adam (Kingma & Ba, 2015)) only seek the model parameters that minimize the training error.
They dismiss the higher-order information such as ﬂatness that correlates with generalization (Keskar et al., 2017; Kleinberg et al., 2018; Jastrz˛ebski et al., 2019; Smith & Le, 2018; Chaudhari et al., 2017).
The above study and reasoning lead us to the recently proposed sharpness-aware minimizer (SAM) (Foret et al., 2021) that explicitly smooths the loss geometry during model training.
SAM strives to ﬁnd a solution whose entire neighborhood has low losses rather than focus on any singleton point.
We show that the resultant models exhibit smoother loss landscapes, and their generalization capabilities improve tremendously across different tasks including supervised, adversarial, contrastive, and transfer learning (e.g., +5.3% and +11.0% top-1 accuracy on ImageNet for ViT-B/ and Mixer-B/16, respectively, with the simple Inception-style preprocessing).
The enhanced ViTs achieve better accuracy and robustness than ResNets of similar and bigger sizes when trained from scratch on ImageNet, without large-scale pre-training or strong data augmentations.
Moreover, we demonstrate that SAM can even enable ViT to be effectively trained with (momentum) SGD, which usually lies far behind Adam when training Transformers (Zhang et al., 2020).
By analyzing some intrinsic model properties, we observe that SAM increases the sparsity of active neurons (especially for the ﬁrst few layers), which contribute to the reduced Hessian eigenvalues.
The weight norms increase, implying the commonly used weight decay may not be an effective regularization alone.
A side observation is that, unlike ResNets and MLP-Mixers, ViTs have extremely sparse active neurons (see Figure 2 (right)), revealing the potential for network pruning (Akbari et al., 2021).
Another interesting ﬁnding is that the improved ViTs appear to have visually more interpretable attention maps.
Finally, we draw similarities between SAM and strong augmentations (e.g., mixup) in that they both smooth the average loss geometry and encourage the models to behave linearly between training images.
B ACKGROUND AND R ELATED W ORK
We brieﬂy review ViTs, MLP-Mixers, and some related works in this section.
Dosovitskiy et al.
(2021) show that a pure Transformer architecture (Vaswani et al., 2017) can achieve state-of-the-art accuracy on image classiﬁcation by pre-training it on large datasets such as ImageNet-21k (Deng et al., 2009) and JFT-300M (Sun et al., 2017).
Their vision Transformer (ViT) is a stack of residual blocks, each containing a multi-head self-attention, layer normalization (Ba et al., 2016), and a MLP layer.
ViT ﬁrst embeds an input image x ∈ R H × W × C into a sequence of features z ∈ R N × D by applying a linear projection over N nonoverlapping image patches x p ∈ R N ×
( P 2 · C ) , where D is the feature dimension, P is the patch resolution, and N = HW/Pis the sequence length.
The self-attention layers in ViT are global and do not possess the locality and translation equivariance of convolutions.
ViT is compatible with the popular architectures in
NLP (Devlin et al., 2018; Radford et al., 2018) and, similar to its NLP counterparts, requires pretraining over massive datasets (Dosovitskiy et al., 2021;
Akbari et al., 2021; Arnab et al., 2021) or [Table] [Figure] strong data augmentations (Touvron et al., 2021b).
Some works specialize the ViT architectures for visual data (Liu et al., 2021b; Yuan et al., 2021;
Fan et al., 2021; Bertasius et al., 2021).
More recent works ﬁnd that the self-attention in ViT is not vital for performance, resulting in several architectures exclusively based on MLPs (Tolstikhin et al., 2021; Touvron et al., 2021a; Liu et al., 2021a; Melas-Kyriazi, 2021).
Here we take MLP-Mixer (Tolstikhin et al., 2021) as an example.
MLP-Mixer shares the same input layer as ViT; namely, it partitions an image into a sequence of nonoverlapping patches/tokens.
It then alternates between token and channel MLPs, where the former allows feature fusion from different spatial locations.
We focus on ViTs and MLP-Mixers in this paper.
We denote by “S” and “B” the small and base model sizes, respectively, and by an integer the image patch resolution.
For instance, ViT-B/16 is the base ViT model taking as input a sequence of 16 × 16 patches.
Appendices contain more details.
V I T S AND MLP-M IXERS C ONVERGE AT S HARP L OCAL M INIMA
The current training recipe of ViTs, MLP-Mixers, and related convolution-free architectures relies heavily on massive pre-training (Dosovitskiy et al., 2021; Arnab et al., 2021;
Akbari et al., 2021) or a bag of strong data augmentations (Touvron et al., 2021b;
Tolstikhin et al., 2021; Cubuk et al., 2019; 2020; Zhang et al., 2018; Yun et al., 2019).
It highly demands data and computing, and leads to many hyperparameters to tune.
Existing works report that ViTs yield inferior accuracy to the ConvNets of similar size and throughput when trained from scratch on ImageNet without the combination of those advanced data augmentations, despite using various regularization techniques (e.g., large weight decay, Dropout (Srivastava et al., 2014), etc.).
For instance, ViT-B/16 (Dosovitskiy et al., 2021) gives rise to 74.6% top-1 accuracy on the ImageNet validation set (224 image resolution), compared with 78.5% of ResNet-152 (He et al., 2016).
Mixer-B/16 (Tolstikhin et al., 2021) performs even worse (66.4%).
There also exists a large gap between ViTs and ResNets in robustness tests (see
Table 2 for details).
Moreover, Chen et al.
(2021c)
ﬁnd that the gradients can spike and cause a sudden accuracy dip when training ViTs, and Touvron et al.
(2021b) report the training is sensitive to initialization and hyperparameters.
These all point to optimization problems.
In this paper, we investigate the loss intending reduce dependency
ViTs and MLP-Mixers converge at extremely sharp local minima.
It has been extensively studied that the convergence to a ﬂat region whose curvature is small beneﬁts the generalization of neural networks (Keskar et al., 2017; Kleinberg et al., 2018; Jastrz˛ebski et al., 2019; Chen & Hsieh, 2020;
Smith & Le, 2018; Zela et al., 2020; Chaudhari et al., 2017).
Following Li et al.
(2018), we plot the loss landscapes at convergence when ResNets, ViTs, and MLP-Mixers are trained from scratch on ImageNet with the basic Inception-style preprocessing (Szegedy et al., 2016) (see Appendices for details).
As shown in Figures 1(a) to 1(c), ViTs and MLP-Mixers converge at much sharper regions than ResNets.
Besides, we calculate the training error under Gaussian perturbations on the model parameters L N train =
E (cid:15)
∼N
[ L train ( w + (cid:15) )] in Table 1, which reveals the average ﬂatness.
Although ViT-B/16 and Mixer-B/16 achieve lower training error L train than that of ResNet-152, their loss values after random weight perturbation become much higher.
We further validate the results by computing the dominate Hessian eigenvalue λ max , which is a mathematical evaluation of the worstcase landscape curvature.
The λ max values of ViT and MLP-Mixer are orders of magnitude larger than that of ResNet, and MLP-Mixer suffers the largest curvature among the three species (see Section 4.4 for a detailed analysis).
Small training errors.
This convergence at sharp regions coincides with the training dynamics shown in Figure 2 (left).
Although Mixer-B/16 has fewer parameters than ViT-B/16 (59M vs. 87M), it has a smaller training error (also see L train in Table 1) but much worse test accuracy, implying that using the cross-token MLP to learn the interplay across image patches is more prone to overﬁtting than ViTs’ self-attention mechanism whose behavior is restricted by a softmax.
To validate this statement, we simply remove the softmax in ViT-B/16, such that the query and key matrices can freely interact with each other.
Although having lower L train (0.56 vs. 0.65), the obtained ViTB/16-Free performs much worse than the original ViT-B/16 (70.5% vs. 74.6%).
Its L N train and λ max are 7.01 and 1236.2, revealing that ViT-B/16-Free converges to a sharper region than ViTB/16 ( L N train is 6.66 and λ max is 738.8) both on average and in the worst-case direction.
Such a difference probably explains why it is easier for MLP-Mixers to get stuck in sharp local minima.
ViTs and MLP-Mixers have worse trainability.
Furthermore, we discover that ViTs and MLPMixers suffer poor trainabilities, deﬁned as the effectiveness of a network to be optimized by gradient descent (Xiao et al., 2020; Burkholz & Dubatovka, 2019; Shin & Karniadakis, 2020).
Xiao et al.
(2020) show that the trainability of a neural network can be characterized by the condition number of the associated neural tangent kernel (NTK), Θ( x, x (cid:48) )
=
J ( x ) J ( x (cid:48) )
T , where J is the Jacobian matrix.
Denoting by λ 1 ≥ · · · ≥ λ m the eigenvalues of NTK Θ train , the smallest eigenvalue λ m converges exponentially at a rate given by the condition number κ = λ 1 /λ m .
If κ diverges then the network will become untrainable (Xiao et al., 2020; Chen et al., 2021a).
As shown in Table 1, κ is pretty stable for ResNets, echoing previous results that ResNets enjoy superior trainability regardless of the depth (Yang & Schoenholz, 2017;
Li et al., 2018).
However, we observe that the condition number diverges when it comes to ViT and MLP-Mixer, conﬁrming that the training of ViTs desires extra care (Chen et al., 2021c; Touvron et al., 2021b).
A P RINCIPLED O PTIMIZER FOR C ONVOLUTION -F REE A RCHITECTURES
The commonly used ﬁrst-order optimizers (e.g., SGD (Nesterov, 1983), Adam (Kingma & Ba, 2015)) only seek to minimize the training loss L train ( w ) .
They usually dismiss the higher-order information such as curvature that correlates with the generalization (Keskar et al., 2017; Chaudhari et al., 2017; Dziugaite & Roy, 2017).
However, the objective L train for deep neural networks are highly non-convex, making it easy to reach near-zero training error but high generalization error L test during evaluation, let alone their robustness when the test sets have different distributions (Hendrycks & Dietterich, 2019; Hendrycks et al., 2020).
ViTs and MLPs amplify such drawbacks of ﬁrst-order optimizers due to the lack of inductive bias for visual data, resulting in excessively sharp loss landscapes and poor generalization, as shown in the previous section.
We hypothesize that smoothing the loss landscapes at convergence can signiﬁcantly improve the generalization ability of those convolution-free architectures, leading us to the recently proposed sharpness-aware minimizer (SAM)
(Foret et al., 2021) that explicitly avoids sharp minima.
4. SAM: O VERVIEW
Intuitively, SAM (Foret et al., 2021) seeks to ﬁnd the parameter w whose entire neighbours have low training loss L train by formulating a minimax objective:
[Equation]
(1) where ρ is the size of the neighbourhood ball.
Without loss of generality, here we use l 2 norm for its strong empirical results (Foret et al., 2021) and omit the regularization term for simplicity.
Since the exact solution of the inner maximization (cid:15)
[Equation]
=
[Equation]
) is hard to obtain, they employ an efﬁcient ﬁrst-order approximation:
[Equation]
Under the l 2 norm, ˆ (cid:15) ( w ) is simply a scaled gradient of the current weight w .
After computing ˆ (cid:15) ,
SAM updates w based on the sharpness-aware gradient ∇ w L train ( w ) | w +ˆ (cid:15) ( w ) .
4. S HARPNESS - AWARE OPTIMIZATION IMPROVES V I T S AND MLP-M IXERS
We train ViTs and MLP-Mixers with no large-scale pre-training or strong data augmentations.
We directly apply SAM to the original ImageNet training pipeline of ViTs (Dosovitskiy et al., 2021) without changing any hyperparameters.
The pipeline employs the basic Inception-style preprocessing (Szegedy et al., 2016).
The original training setup of MLP-Mixers (Tolstikhin et al., 2021) includes a combination of strong data augmentations, and we replace it with the same Inceptionstyle preprocessing for a fair comparison.
Note that we perform grid search for the learning rate, weight decay, Dropout before applying SAM.
Please see Appendices for training details.
Smoother regions around the local minima.
Thanks to SAM, both ViTs and MLP-Mixers converge at much smoother regions, as shown in Figures 1(d) and 1(e).
Moreover, both the average and the worst-case curvature, i.e., L N train and λ max , decrease dramatically (see Table 1).
Higher accuracy.
What comes along is tremendously improved generalization performance.
On ImageNet, SAM boosts the top-1 accuracy of ViT-B/16 from 74.6% to 79.9%, and Mixer-B/ from 66.4% to 77.4%.
For comparison, the improvement on a similarly sized ResNet-152 is 0.8%.
Empirically, the degree of improvement negatively correlates with the constraints of inductive biases built into the architecture.
ResNets with inherent translation equivalence and locality beneﬁt less from landscape smoothing than the attention-based ViTs.
MLP-Mixers gain the most from the smoothed loss geometry.
In Table 3, we further train two hybrid models (Dosovitskiy et al., 2021) to validate this observation, where the Transformer takes the feature map extracted from a ResNet-50 as the input sequence.
The improvement brought by SAM decreases after we introduce the convolution to ViT, for instance, +2.7% for R50-B/16 compared to +5.3% for ViT-B/16.
Moreover, SAM brings larger improvements to the models of larger capacity (e.g., +4.1% for Mixer-S/16 vs. +11.0% for Mixer-B/16) and longer patch sequence (e.g., +2.1% for ViT-S/32 vs. +5.3% for ViT-S/8).
Please see Table 2 for more results.
SAM can be easily applied to common base optimizers.
Besides Adam, we also apply SAM on top of the (momentum)
SGD that usually performs much worse than Adam when training Transformers (Zhang et al., 2020).
As expected, we ﬁnd that under the same training budget (300 epochs), the
ViT-B/16 trained with SGD only achieves 71.5% accuracy on ImageNet, whereas Adam achieves
[Table] Surprisingly, SGD + SAM can push the result to 79.1%, which is a huge +7.6% absolute improvement.
Although Adam + SAM is still higher (79.9%), their gap largely shrinks.
Better robustness.
We also evaluate the models’ robustness using ImageNet-R (Hendrycks et al., 2020) and ImageNet-C (Hendrycks & Dietterich, 2019) and ﬁnd even bigger impacts of the smoothed loss landscapes.
On ImageNet-C, which corrupts images by noise, bad weather, blur, etc., we report the average accuracy against 19 corruptions across ﬁve levels.
As shown in Tables 1 and 2, the accuracies of ViT-B/16 and Mixer-B/16 increase by 9.9% and 15.0% (which are 21.2% and 44.4% relative improvements), after SAM smooths their converged local regions.
In comparison, SAM improves the accuracy of ResNet-152 by 2.2% (4.4% relative improvement).
We can see that SAM enhances the robustness even more than the relative clean accuracy improvements (7.1%, 16.6%, and 1.0% for ViT-B/16, Mixer-B/16, and ResNet-152, respectively).
4. V I T S OUTPERFORM R ES N ETS WITHOUT PRE - TRAINING OR STRONG AUGMENTATIONS
[Table]
The performance of an architecture is often conﬂated with the training strategies (Bello et al., 2021), where data augmentations play a key role (Cubuk et al., 2019; 2020; Zhang et al., 2018; Xie et al., 2020; Chen et al., 2021b).
However, the design of augmentations requires substantial domain expertise and may not translate between images and videos, for instance.
Thanks to the principled sharpness-aware optimizer, we can remove the advanced augmentations and focus on the architectures themselves.
When trained from scratch on ImageNet with SAM, ViTs outperform ResNets of similar and greater sizes (also comparable throughput at inference) regarding both clean accuracy (on ImageNet (Deng et al., 2009),
ImageNet-ReaL (Beyer et al., 2020), and ImageNet V2 (Recht et al., 2019)) and robustness (on ImageNet-R
(Hendrycks et al., 2020) and ImageNet-C (Hendrycks & Dietterich, 2019)).
ViT-B/16 achieves 79.9%, 26.4%, and 56.6% top-1 accuracy on ImageNet, ImageNet-R, and ImageNet-C, while the counterpart numbers for ResNet-152 are 79.3%, 25.7%, and 52.2%, respectively (see Table 2).
The gaps between ViTs and ResNets are even wider for small architectures.
ViT-S/16 outperforms a similarly sized ResNet-50 by 1.4% on ImageNet, and 6.5% on ImageNet-C.
SAM also signiﬁcantly improves MLP-Mixers’ results.
[Table]
4. I NTRINSIC CHANGES AFTER SAM
We take a deeper look into the models to understand how they intrinsically change to reduce the
Hessian’ eigenvalue λ max and what the changes imply in addition to the enhanced generalization.
Smoother loss landscapes for every network component.
In Table [Table] we break down the Hessian of the whole architecture into small diagonal blocks of Hessians concerning each set of parameters, attempting to analyze what speciﬁc components cause the blowing up of λ max in the models trained without SAM.
We observe that shallower layers have larger Hessian eigenvalues λ max , and the ﬁrst linear embedding layer incurs the sharpest geometry.
This agrees with the ﬁnding in (Chen et al., 2021c) that spiking gradients happen early in the embedding layer.
Additionally, the multi-head self-attention (MSA) in ViTs and the Token MLPs in MLP-Mixers, both of which mix information across spatial locations, have comparably lower λ max than the other network components.
SAM consistently reduces the λ max of all network blocks.
We can gain insights into the above ﬁndings by the recursive formulation of Hessian matrices for
MLPs (Botev et al., 2017).
Let h k and a k be the pre-activation and post-activation values for layer k , respectively.
They satisfy h k
= W k a k − 1 and a k = f k ( h k ) , where W k is the weight matrix and f k is the activation function (GELU (Hendrycks & Gimpel, 2020) in MLP-Mixers).
Here we omit the bias term for simplicity.
The diagonal block of Hessian matrix H k with respect to W k can be recursively calculated as:
[Equation]
where ⊗ is the Kronecker product, H k is the pre-activation Hessian for layer k , and L is the objective function.
Therefore, the Hessian norm accumulates as the recursive formulation backpropagates to shallow layers, explaining why the ﬁrst block has much larger λ max than the last block in Table 4.
Greater weight norms.
After applying SAM, we ﬁnd that in most cases, the norm of the postactivation value a k − 1 and the weight W k +1 become even bigger (see Table 4), indicating that the commonly used weight decay may not effectively regularize ViTs and MLP-Mixers (see Appendix J for further veriﬁcation when we vary the weight decay strength).
Sparser active neurons in MLP-Mixers.
Given the recursive formulation Equation (3), we identify another intrinsic measure of MLP-Mixers that contribute to the Hessian: the number of activated neurons.
Indeed, B k is determined by the activated neurons whose values are greater than zero, since the ﬁrst-order derivative of GELU becomes much smaller when the input is negative.
As a result, the number of active GELU neurons is directly connected to the Hessian norm.
Figure(right) shows the proportion of activated neurons for each block, counted using 10% of the ImageNet training set.
We can see that SAM greatly reduces the proportion of activated neurons for the ﬁrst few layers of the Mixer-B/16, pushing them to much sparser states.
This result also suggests the potential redundancy of image patches.
ViTs’ active neurons are highly sparse.
Although Equations (3) and (4) only involve MLPs, we still observe a decrease of activated neurons in the ﬁrst layer of ViTs (but not as signiﬁcant as in
MLP-Mixers).
More interestingly, we ﬁnd that the proportion of active neurons in ViT is much smaller than another two architectures — given an input image, less than 10% neurons have values greater than zero for most layers (see Figure 2 (right)).
In other words, ViTs offer a huge potential for [Table] network pruning.
This sparsity may also explain why one Transformer can handle multi-modality signals (vision, text, and audio) (Akbari et al., 2021).
Visually improved attention maps in ViTs.
We visualize ViT-S/16’s attention map of the classiﬁcation token averaged over the last multi-head attentions in Figure 3 following Caron et al.
Interestingly, the ViT model optimized with SAM appears to possess visually improved attention map compared with the one trained via the vanilla AdamW optimizer.
4. SAM VS . STRONG AUGMENTATIONS
Previous sections show that SAM can improve the generalization (and robustness) of ViTs and
MLP-Mixers.
Meanwhile, another paradigm to train these models on ImageNet from scratch is to stack multiple strong augmentations (Touvron et al.
, 2021b;a; Tolstikhin et al., 2021).
Hence, it is interesting to study the differences and similarities between the models trained by SAM and by using strong data augmentations.
For the augmentation experiments, we follow Tolstikhin et al.
(2021)’s pipeline that includes mixup (Zhang et al., 2018) and RandAugment (Cubuk et al., 2020).
Generalization.
Table 5 shows the results of strong data augmentation, SAM, and their combination on ImageNet.
Each row corresponds to a training set of a different fraction of ImageNet-1k.
SAM beneﬁts ViT-B/16 and Mixer-B/
more
than the strong data augmentations, especially when the training set is small.
For instance, when the training set contains only 1/10 of ImageNet training images, ViT-B/16-SAM outperforms ViT-B/16-AUG by 7.6%.
Apart from the improved validation accuracy, we also observe that both SAM and strong augmentations increase the training error (see
Figure 2 (Middle) and Table 6), indicating their regularization effects.
However, they have distinct training dynamics as the loss curve for ViT-B/16-AUG is much nosier than ViT-B/16-SAM.
[Table]
Sharpness at convergence.
Another intriguing question is as follows.
Can augmentations also smooth the loss geometry similarly to SAM?
To answer it, we also plot the landscape of ViTB/16-AUG (see Figure 5 in the Appendix) and compute its Hessian λ max together with the average ﬂatness L N train in Table 6.
Surprisingly, strong augmentations even enlarge the λ max .
However, like SAM, augmentations make ViT-B/16-AUG smoother and achieve a signiﬁcantly smaller training error under random Gaussian perturbations than ViT-B/16.
These results show that both SAM and augmentations make the loss landscape ﬂat on average .
The difference is that SAM enforces the smoothness by reducing the largest curvature via a minimax formulation to optimize the worst-case scenario, while augmentations ignore the worse-case curvature and instead smooth the landscape over the directions induced by the augmentations.
Interestingly, besides the similarity in smoothing the loss curvature on average, we also discover that
SAM-trained models possess “linearality” resembling the property manually injected by the mixup augmentation.
Following Zhang et al.
(2018), we compute the prediction error in-between training data in Table 6, where a prediction y is counted as a miss if it does not belong to { y i , y j } evaluated at x = 0 .
5 x i + 0 .
5 x j .
We observe that SAM greatly reduces the missing rate ( R ) compared with the vanilla baseline, showing a similar effect to mixup that explicitly encourages such linearity.
A BLATION S TUDIES
In this section, we provide a more comprehensive study about SAM’s effect on various vision models and under different training setups.
We refer to Appendices B to D for the adversarial, contrastive and transfer learning results.
5. W HEN SCALING THE TRAINING SET SIZE
Previous studies scale up training data to show massive pre-training trumps inductive biases (Dosovitskiy et al., 2021;
Tolstikhin et al., 2021).
Here we show SAM further enables ViTs and MLPMixers to handle small-scale training data well.
We randomly sample 1/4 and 1/2 images from each ImageNet class to compose two smaller-scale training sets, i.e., i1k (1/4) and i1k (1/2) with 320, and 640,583 images, respectively.
We also use ImageNet-21k to pre-train the models with SAM, followed by ﬁne-tuning on ImageNet-1k without SAM.
The ImageNet validation set remains intact.
SAM can still bring improvement when pre-trained on ImageNet-21k (+0.3%, +1.4%, and 2.3% for ResNet-152, ViT-B/16, and Mixer-B/16, respectively).
As expected, fewer training examples amplify the drawback of ViTs and MLP-Mixers’ lack of the convolutional inductive bias — their accuracies decline much faster than ResNets’ (see Figure 4 in the Appendix and the corresponding numbers in Table 5).
However, SAM can drastically rescue ViTs and MLP-Mixers’ performance decrease on smaller training sets.
Figure 4 (right) shows that the improvement brought by SAM over vanilla SGD training is proportional to the number of training images.
When trained on i1k (1/4), it boosts ViT-B/16 and Mixer-B/16 by 14.4% and 25.6%, escalating their results to 66.8% and 62.8%, respectively.
It also tells that ViT-B/16-SAM matches the performance of ResNet-152-SAM even with only 1/2 ImageNet training data.
C ONCLUSIONS AND L IMITATIONS
This paper presents a detailed analysis of the convolution-free ViTs and MLP-Mixers from the lens of the loss landscape geometry, intending to reduce the models’ dependency on massive pre-training and/or strong data augmentations.
We arrive at the sharpness-aware minimizer (SAM) after observing sharp local minima of the converged models.
By explicitly regularizing the loss geometry through SAM, the models enjoy much ﬂatter loss landscapes and improved generalization regarding accuracy and robustness.
The resultant ViT models outperform ResNets of comparable size and throughput when learned with no pre-training or strong augmentations.
Further investigation reveals that the smoothed loss landscapes attribute to much sparser activated neurons in the ﬁrst few layers.
Last but not least, we discover that SAM and strong augmentations share certain similarities to enhance the generalization.
They both smooth the average loss curvature and encourage linearity.
Despite achieving better generalization, training ViTs with SAM has the following limitations which could lead to potential future work.
First, SAM incurs another round of forward and backward propagations to update (cid:15) , which will lead to around 2x computational cost per update.
Second, we notice that the effect of SAM diminishes as the training dataset becomes larger, so it is vital to develop learning algorithms that can improve/accelerate the large-scale pre-training process.
E THICS S TATEMENT
We are not aware of any immediate ethical issues in our work.
We hope this paper can provide new insights into the convolution-free neural architectures and their interplay with optimizers, hence beneﬁting future developments of advanced neural architectures that are efﬁcient in data and computation.
Possible negative societal impacts mainly hinge on the applications of convolution-free architectures, whose societal effects may translate to this work.
A CKNOWLEDGEMENT
This work is partially supported by NSF under IIS-1901527, IIS-2008173, IIS-2048280 and by
Army Research Laboratory under agreement number W911NF-20-2-0158.
R EPRODUCIBILITY S TATEMENT
We provide comprehensive experimental details and references to existing works and codebases to ensure reproducibility.
The speciﬁcation of all the architectures used in this paper is available in
Appendix A.
The instructions for plotting the landscape and the attention map are detailed in
Appendix E. We also present our approach to approximating Hessian’s dominant eigenvalue λ max and the NTK condition number in Appendices F and G, respectively.
Finally, Appendix H describes all the necessary training conﬁgurations, data augmentations and SAM hyperparameters to ensure the reproducibility of our results
A PPENDICES A A RCHITECTURES
Table 8 speciﬁes the ViT (Dosovitskiy et al., 2021; Vaswani et al., 2017) and MLP-Mixer (Tolstikhin et al., 2021)
architectures used in this paper.
“S” and “B” denote the small and base model scales following (Dosovitskiy et al., 2021; Touvron et al., 2021b;
Tolstikhin et al., 2021), followed by the size of each image patch.
For instance, “B/16” means the model of base scale with non-overlapping image patches of resolution 16 × 16 .
We use the input resolution 224 × 224 throughout the paper.
Following Tolstikhin et al.
(2021), we sweep the batch sizes in { 32 , 64 , . . . , 8192 } on TPU-v3 and report the highest throughput for each model.
[Table]
and MLP-Mixer architectures used in this paper.
We train all the architectures with image resolution 224 ×
[Table]
B W HEN SAM M EETS A DVERSARIAL T RAINING
Interestingly
[Table]
SAM and adversarial training are both minimax problems except that SAM’s inner maximization is with respect to the network weights, while the latter concerns about the input for All models are ﬁne-tuned with 224 × 224 resolution, a batch size of 512, cosine learning rate decay, no weight decay, and grad clipping at global norm 1.
[Figure]
defending contrived attack (Madry et al.,
; Wong et al., 2020).
Moreover, similar to SAM,
Shafahi et al.
(2019) suggest that adversarial training can ﬂatten and smooth the loss landscape.
In light of these connections, we study ViTs and MLP-Mixers under the adversarial training framework (Wu et al., 2020; Madry et al., 2018).
We use the fast adversarial training (Wong et al., 2020) (FGSM with random start) with the l ∞ norm and maximum per-pixel change 2/255 during training.
All the hyperparameters remain the same as the vanilla supervised training.
When evaluating the adversarial robustness, we use the PGD attack (Madry et al., 2018) with the same maximum per-pixel change 2/255.
The total number of attack steps is 10, and the step size is 0.25/255.
To incorporate
SAM, we formulate a three-level objective:
[Equation]
(5) where S sam and S adv denote the allowed perturbation norm balls for the model parameter w and input image x , respectively.
Note that we can simultaneously obtain the gradients for computing (cid:15) and δ by backpropagation only once.
To lower the training cost, we use fast adversarial training (Wong et al., 2020) with the l ∞ norm for δ , and the maximum per-pixel change is set as 2/255.
Table 7 (see Appendices) evaluates the models’ clean accuracy, real-world robustness, and adversarial robustness (under 10-step PGD attack (Madry et al., 2018)).
It is clear that the landscape smoothing signiﬁcantly improves the convolution-free architectures for both clean and adversarial accuracy.
However, we observe a slight accuracy decrease on clean images for ResNets despite gain for robustness.
Similar to our previous observations, ViTs surpass similar-size ResNets when adversarially trained on ImageNet with Inception-style preprocessing for both clean accuracy and adversarial robustness.
C W HEN SAM M EETS C ONTRASTIVE L EARNING
In addition to data augmentations and large-scale pre-training, another notable way of improving a neural model’s generalization is (supervised) contrastive learning (Chen et al., 2020; He et al., 2020; Caron et al., 2021; Khosla et al., 2020).
We couple SAM with the supervised contrastive learning (Khosla et al., 2020) for 350 epochs, followed by ﬁne-tuning the classiﬁcation head byepochs for both ViT-S/16 and ViT-B/16.
We train ViTs under the supervised contrastive learning framework (Khosla et al., 2020).
We take the classiﬁcation token output from the last layer as the encoded representation and retain the structures of the projection and classiﬁcation heads (Khosla et al., 2020).
We employ a batch size 2048 without memory bank (He et al., 2020) and use AutoAugment (Cubuk et al., 2019) with strength 1.0 following Khosla et al.
For the 350-epoch pretraining stage, the contrastive loss temperature is set as 0.1, and we use the LAMB optimizer (You et al., 2020) with learning rate 0 .
001 × batch sizealong with a cosine decay schedule.
For the second stage, we train the classiﬁcation head for 90 epochs via a RMSProp optimizer (Tieleman & Hinton, 2012) with base learning rate 0.05 and exponential decay.
The weight decays are set as 0.3 and 1efor the ﬁrst and second stages, respectively.
We use a small SAM perturbation strength ρ = 0 . 02 .
Compared to the training procedure without SAM, we ﬁnd considerable performance gain thanks to
SAM’s smoothing of the contrastive loss geometry, improving the ImageNet top-1 accuracy of ViTS/16 from 77.0% to 78.1%, and ViT-B/16 from 77.4% to 80.0%.
In comparison, the improvement on ResNet-152 is less signiﬁcant (from 79.7% to 80.0% after using SAM). [Figure] [Table] [Figure]
[Table]
[Figure] [Table] [Figure] [Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
D W HEN SAM M EETS T RANSFER L EARNING
We also study the role of smoothed loss geometry in transfer learning.
We select four datasets to test ViTs and MLP-Mixers’ transferabilities: CIFAR-10/100 (Krizhevsky, 2009), Oxford-IIIT
Pets (Parkhi et al., 2012), and Oxford Flowers-102 (Nilsback & Zisserman, 2008).
We use image resolution 224 × 224 during ﬁne-tuning on downstream tasks, other settings exactly follow Dosovitskiy et al.
; Tolstikhin et al.
(2021) (see Table 9).
Note that we do not employ SAM during ﬁne-tuning.
We perform a grid search over the base learning rates on small sub-splits of the training sets (10% for Flowers and Pets, 2% for CIFAR-10/100).
After that, we ﬁne-tune on the entire training sets and report the results on the respective test sets.
For comparison, we also include
ResNet-50-SAM and ResNet-152-SAM in the experiments.
Table 10 summarizes the results, which conﬁrm that the enhanced models also perform better after ﬁne-tuning and that MLP-Mixers gain the most from the sharpness-aware optimization.
E V ISUALIZATION E. L OSS LANDSCAPE
We use the “ﬁlter normalization” method (Li et al., 2018) to visualize the loss function curvature in
Figure 1 and 5.
For a fair comparison, we use the cross-entropy loss when plotting the landscapes for all architectures, although the original training objective is the sigmoid loss for ViTs and MLPMixers.
Note that their sigmoid loss geometry is even sharper.
We equally sample 2,500 points on the 2D projection space and compute the losses using 10% of the ImageNet training images (Chen et al., 2020), i.e., the i1k (1/10) subset in the main text to save computation.
E. A TTENTION MAP
The visualization of the ViT’s attention maps (Figure 3 in the main text) follows (Caron et al., 2021).
We average the self-attention scores of the “classiﬁcation token” from the last MSA layer to obtain a matrix A ∈ R H/P × W/P , where H , W , P are the image height, width, and the patch resolution, respectively.
Then we upsample A to the image shape H × W before generating the ﬁgure. [Table]
F H ESSIAN E IGENVALUE
The Hessian matrix requires second-order derivative, so we compute the Hessian (and all the subdiagonal Hessian) λ max using 10% of the ImageNet training images (i.e., i1k (1/10)) via power iteration 1 , where we use 100 iterations to ensure its convergence.
G NTK C ONDITION N UMBER
We approximate the neural tangent kernel on the i1k (1/10) subset by averaging over block diagonal entries (with block size 48 × 48 ) in the full NTK.
Notice that the computation is based on the architecture at initialization without training.
As the activation plays an important role when computing
NTK — we ﬁnd that smoother activation functions enjoy smaller condition numbers, we replace the
GELU in ViT and MLP-Mixer with ReLU for a fair comparison with ResNet.
H T RAINING D ETAILS
We use image resolution 224 × 224 during ﬁne-tuning on downstream tasks, other settings exactly follow (Dosovitskiy et al., 2021;
Tolstikhin et al., 2021) (see Table 9).
Note that we do not employ
SAM during ﬁne-tuning.
We perform a grid search over the base learning rates on small sub-splits of the training sets (10% for Flowers and Pets, 2% for CIFAR-10/100).
After that, we ﬁne-tune on the entire training sets and report the results on the respective test sets. [Table]
[Table] Except for the experiments in Section 4.5 (SAM with strong data augmentations) and Appendix C (contrastive learning) [Table] we train all the models from scratch on ImageNet with the basic Inceptionstyle preprocessing (Szegedy et al., 2016), i.e., a random image crop and a horizontal ﬂip with probability 50%.
Please see Table 12 for the detailed training settings.
We simply follow the original training settings of ResNet and ViT (Kolesnikov et al., 2020; Dosovitskiy et al., 2021).
For MLPMixer, we remove the strong augmentations in its original training pipeline and perform a grid search over the learning rate in { 0 . 003 , 0 . 001 } , weight decay in { 0 . 3 , 0 . 1 , 0 . 03 } , Dropout rate in { 0 . 1 , 0 . 0 } , and stochastic depth in { 0 . 1 , 0 . 0 } .
Note that training for 90 epochs is enough for ResNets to converge, and longer schedule brings almost no effect.
For all the experiments, we use 128 TPUv3 cores (2 per chip), resulting in 32 images per core.
The SAM computation for ˆ (cid:15) is conducted on each core independently.
H. P ERTURBATION STRENGTH IN SAM
Different architecture species favor different strengths of perturbation ρ .
We perform a grid search over ρ and report the best results — Table 11 reports the corresponding strengths used in our ImageNet experiments.
Besides, we show the results when varying ρ in Table 13.
Similar to (Foret et al., 2021), we also ﬁnd that a relative small ρ ∈ [0 . 02 , 0 . 05] works the best for ResNets.
However, larger ρ gives rise to the best results for ViTs and MLP-Mixers.
We also observe that architectures with larger capacities and longer input sequences prefer stronger perturbation strengths.
Interestingly, the choice of ρ coincides with our previous observations.
Since MLP-Mixers suffer the sharpest landscapes, they need the largest perturbation strength.
As strong augmentations and contrastive learning already improve generalization, the suitable ρ becomes signiﬁcantly smaller.
Note that we do not re-tune any other hyperparameters when using SAM.
H. T RAINING ON I MAGE N ET SUBSETS
In Section 5.1, we train the models on ImageNet subsets, and the hyperparameters have to be adjusted accordingly.
We simply change the batch size to maintain similar total iterations and keep all other settings the same, i.e., 2048 for i1k (1/2), 1024 for i1k (1/4), and 512 for i1k (1/10).
We do not scale the learning rate as we ﬁnd the scaling harms the performance.
H. T RAINING WITH STRONG AUGMENTATIONS
We tune the learning rate and regularization when using strong augmentations (mixup with probability 0.5, RandAugment with two layers and magnitude 15) in Section 4.5 following (Tolstikhin et al., 2021).
For ViT, we use 1e-3 peak learning rate, 0.1 weight decay, 0.1 Dropout, and 0.1 stochastic depth; For MLP-Mixer, those hyperparameters are exactly the same as (Tolstikhin et al., 2021), peak learning rate as 1e-3, weight decay as 0.1, Dropout as 0.0, and stochastic depth as 0.1.
Other settings are unchanged (Table 12).
I L ONGER S CHEDULE OF V ANILLA SGD
Since SAM needs another forward and backward propagation to compute ˆ (cid:15) [Table] its training overhead is ∼ 2 × of the vanilla baseline.
We also experiment with 2 × schedule vanilla training (600 epochs).
We observe that training longer brings no effect on both clean accuracy and robustness, indicating that the current 300 training epochs for ViTs and MLP-Mixers are enough for them to converge.
J V ARYING W EIGHT D ECAY S TRANGTH
[Table]
In this section, we vary the strength of weight decay and see the effects of this commonly used regularization approach.
As shown in Table 14, weight decay helps improve the accuracy on ImageNet when training without SAM, the weight norm also decreases when we enlarge the decay strength as expected.
However, enlarging the weight decay aggravates the problem of converging to a sharper region measured by both L N train and λ max .
Another observation is that (cid:107) w (cid:107) 2 consistently increases after applying SAM for every weight decay strength in Table 14, together with the improved ImageNet accuracy and smoother landscape curvature.