Understanding Robustness of Transformers for Image Classification
Paper · 2021 · Srinadh Bhojanapalli, Ayan Chakrabarti, Daniel Gläsner et al.
Summary
A classifier can recognize an object in a photograph and lose track of it when the image shifts, blurs, or is redrawn. Understanding Robustness of Transformers for Image Classification asks whether those failures change when a network reads an image as a sequence of patches. The authors compare Vision Transformers, or ViTs, with residual convolutional networks, or ResNets, across different network sizes and amounts of pretraining data. They also change the trained ViTs themselves to find out which parts of the network matter most for classification. The study concerns both the stability of predictions and the way information moves through a Transformer.
On tests using common corruptions, artistic renditions, and naturally difficult photographs, better clean ImageNet performance generally went with better performance under changed conditions. The architecture comparison depended on pretraining. ViTs often lagged behind comparable ResNets with the smallest training corpus. With JFT-300M pretraining, they generally matched or surpassed their convolutional counterparts on these tests, and increasing the size of the ViT yielded stronger gains. This pattern makes pretraining part of the explanation for robustness, alongside the design of the network.
The tests using deliberately chosen image changes gave a more varied answer. ResNets had an advantage over ViTs under the simpler gradient-based test in some training regimes. That advantage did not persist under the stronger iterative test, and perturbations crafted for one architecture transferred poorly to the other. Patch size also mattered. ViTs using 16 × 16 patches generally held their position relative to comparable ResNets when images were shifted and rotated, while those using 32 × 32 patches were more susceptible. The larger patches fared better when shape and texture pointed to different classes, yielding more predictions that agreed with shape.
Inside the ViT, the opening block was unusually important. Most other individual blocks could be bypassed after training with little loss of classification accuracy, although removing several eventually caused larger losses. Patch representations became highly correlated across the later blocks, while the CLS token, the part of the sequence used to make the final prediction, continued to change. Cutting direct communication between patches late in the network had a much smaller effect than making that cut near the start. Together, the observations suggest that later blocks can still contribute to the prediction even when the image patches themselves change little.
Deep dive: Understanding Robustness of Transformers for Image Classification
How Vision Transformers and ResNets handle image corruptions, shifts, and adversarial inputs, and what layer removal reveals about attention. · about 32 minutes to read
The problem and its context
Why the patch grid raised a new question
Clean image classification tests whether a network can assign the expected class to an image drawn from its ordinary evaluation distribution. Robustness asks how well that decision survives a change in the image or in the computation. A network that does well on clean photographs may encounter different visual cues in a drawing, noise in a photograph, or an object at a slightly different position. These changes can preserve the intended class while altering the evidence available to the network. The paper asks whether changing the architecture changes which variations cause trouble.
Convolution was a natural baseline because its operation reflects the spatial layout of an image. A convolution looks at nearby values and applies the same learned operation at different positions. The first property is locality. The second gives a convolution a form of translation equivariance: moving a pattern can move the corresponding response with it. Image classification typically calls for a different outcome at the final decision, where a modest shift should leave the predicted class stable. The distinction matters because a spatial property of a layer and the stability of a whole classifier are different things. The authors treat locality and equivariance as inductive biases, meaning properties built into how the network processes inputs before it learns from examples. Relational inductive biases, deep learning, and graph networks
The paper situates ResNets within a long line of convolutional work on vision. Residual connections let a signal continue through a skip path while a learned operation adds an update. They changed how deep networks could be built and analyzed while retaining convolution as the main operation. That distinction made a ResNet a useful comparison for ViT. Both families have residual paths, but the operation that moves information between spatial locations differs. In a ResNet it is primarily convolution. In a ViT it is attention over a sequence derived from the image.
The Transformer arrived at vision by way of language. The paper describes earlier language systems as relying heavily on recurrent computation, where a sequence is processed through a succession of states. Self-attention allowed the representation of a token to draw directly on other tokens through scores based on their vector representations. The resulting contextual representations could be learned during pretraining and adapted to downstream tasks. The paper cites the successes of BERT alongside work on few-shot language learning.
An image has spatial organization but no single sequence inherent in it. One earlier approach described in the paper treated the pixels as sequence elements. It gave competitive results in a self-supervised setting, where the learning signal comes from the data itself, but working with a sequence made from individual pixels was computationally costly. ViT operates on patches. It divides the image into disjoint regions and projects each region into a vector, producing a shorter sequence for the Transformer. The original ViT study had shown that, with enough pretraining data, this approach could compete favorably with similarly sized residual networks. An Image is Worth 16x16 Words
That earlier work gave the robustness question its particular shape. A small translation can move image content across the fixed borders used to form the patch sequence. An object can still look much the same to a person even though the pixels grouped into particular tokens have changed. The authors also ask what happens when a two-dimensional arrangement becomes a sequence. Reading the patches as a sequence gives attention access to locations outside a local neighborhood, but leaves open how strongly the resulting classifier depends on the spatial organization of nearby patches. Those questions call for different tests. A shift or rotation probes sensitivity to the way the image is divided. A restriction on attention probes what the trained network does with the patch relationships it has learned.
Why test several kinds of robustness
Earlier research described in the paper had already supplied different ways to challenge an image classifier. A corruption benchmark applies a known degradation to an image. A rendition benchmark changes how an object is depicted, with examples such as embroidery or painting. A filtering procedure can also discover photographs that are difficult even though their pixels have never been deliberately altered. All can lower accuracy, but they impose different demands. A network that recognizes a blurred photograph needs to make use of evidence remaining after blur. Recognizing an embroidered object may require handling different local textures. An ordinary photograph selected for difficulty can reveal a blind spot within the broader world of photographic images.
Prior work on deliberate perturbations gave the authors a further distinction. For a given image, a test can search for a small pixel change chosen to make that particular classifier fail. It can also search over shifts and rotations, which have a direct geometric interpretation. In both cases, the result depends on the set of changes considered and the search used to find them. The paper uses these tests alongside the natural benchmarks because clean accuracy, resistance to a fixed collection of corruptions, and resistance to a change selected for its effect are different observations about a classifier.
Research on internal computation supplied the other half of the study. Earlier work on residual networks found that many paths through a trained network were shorter than its full depth and that successive layers within a stage could refine an existing representation. Studies of language Transformers had also investigated redundancy in attention and the roles of different layers. The authors extend this line of inquiry to image classification, where the sequence includes both patch tokens and a special token read out for the class prediction. They ask whether the image tokens and the classification token follow the same pattern as they pass through the stack.
The paper also describes work that combined attention with other approaches to vision. Some studies added attention to conventional visual networks. Another trained a data-efficient image Transformer with a convolutional teacher, using the teacher’s predictions as a learning signal. Work on vision and language used attention between image and text tokens, while a dual-encoder approach used a ViT to represent the image and compared the resulting representation with a text representation through a dot product. These examples explain the breadth of interest in attention at the time. The robustness study focuses on ViT because its main processing stack uses Transformer blocks throughout. Vision & language · Learning Transferable Visual Models From Natural Language Supervision
The method, step by step
From pixels to a class prediction
The researchers begin with trained ViT and ResNet checkpoints, which are saved sets of weights. For each evaluation, they resize an image directly to the dimensions the network expects and normalize the pixel intensities to its input range. This resizing ignores the original aspect ratio, so a rectangular image can be stretched to fit the expected input. The procedure uses no crop. For most of the networks, the expected input dimensions are 384 × 384 pixels. The ResNet processes the prepared image through its convolutional network. The ViT first converts it into a sequence.
Each patch in that sequence is a square region, and the regions do not overlap. The learned input projection turns each region into a vector of the same width, so the Transformer can treat every region as a token. The projection is implemented with a convolution in the embedding layer. Its filters determine the width of the resulting vectors. The key architectural distinction lies in what happens to those vectors afterwards. The ViT stack exchanges information through attention over the patch sequence.
The paper uses a suffix to identify patch size. ViT-B/16 is a Base variant using 16 × 16 patches, and ViT-L/32 is a Large variant using 32 × 32 patches. The notation gives the shape of the regions on which the embedding operation works.
x ⋅ x
Here x is the side length of a patch in pixels and is the value given after the slash in the variant’s name. The multiplication dot joins the patch’s two equal dimensions. A smaller x yields more patch tokens for the same image dimensions. That changes both the amount of computation and the granularity of the visual information carried by each token.
The network attaches a CLS token to the patch sequence. This is a special position whose eventual representation feeds the classification decision. Its initial representation has no patch of pixels assigned to it. Over the course of processing, it can draw on the image information represented elsewhere in the sequence. The patch tokens can also interact with one another, so the representation available to the CLS token can already contain information gathered from multiple regions.
Each Transformer block applies multi-head self-attention followed by a feed-forward layer, also called an MLP, or multilayer perceptron. Self-attention compares token representations through dot products and uses the resulting scores to determine how information from the sequence is combined. Multiple heads allow a block to perform several such attention operations. The MLP then transforms the representation at each token position separately. The layer design includes normalization and skip connections. The skip connections are essential to the later intervention because they provide a route around a computation whose contribution the authors remove.
How the Vision Transformer classifies an image
The steps in order.
How the comparison is organized
The ViT checkpoints came from the original ViT authors. The residual-network checkpoints came from the authors of Big Transfer. The study covers Base, Large, and Huge ViTs, along with ResNets of different depths and widths. For a designation such as ResNet-50x3, the x3 denotes a multiplier on the number of channels. This naming convention differs from the slash suffix used for ViT patch sizes. The authors compare networks of similar scale and training history where the checkpoint collection allows it, and examine how accuracy changes with the number of trainable parameters.
The pretraining corpora span markedly different sizes. ILSVRC-2012 has approximately 1.3 million images, and ImageNet-21k has roughly 12.8 million images. JFT-300M has around 375M labels for 300M images. The last two counts describe different things: labels are annotations, while images are the items to which the labels apply. The distinctions between the corpora matter because robustness is measured after learning from each of these regimes.
All checkpoints ultimately target ILSVRC-2012 classification. For a network trained on a larger corpus, fine-tuning adapts the pretrained weights to that task. The ILSVRC-2012-only variants represent the smallest data regime in the comparison. The common target makes the clean validation results a reference for the robustness experiments. Much of the study then asks what happens to the accuracy of those already trained classifiers when the images, or the computation applied to them, are changed at evaluation time.
The image experiments follow several routes. For benchmark corruptions, the authors aggregate accuracy across different degradation types and severity levels. For renditions and naturally difficult photographs, they evaluate on collections selected for those properties. For the controlled pixel and spatial perturbations, they compare clean and altered versions of images drawn from the ILSVRC-2012 validation set. The benchmark whose labels come from the shape of a stylized object supplies a different metric, since it asks whether shape determines the prediction when texture may suggest something else. Evaluation & benchmarks
How the input tests change an image
For the pixel perturbations, the paper limits the largest change to any pixel component. The authors call this an infinity-norm bound.
L∞
L denotes the norm and ∞ marks the convention of taking the largest absolute component of a change. The bound in the experiments is one gray level. The authors translate that amount into the intensity scale expected by the classifier under evaluation. The valid intensity range also constrains the perturbed image. A classifier-specific test uses knowledge of the weights and the architecture and is therefore described as white-box.
The two pixel tests share a source of information: the gradient of the classification loss with respect to the input. Here the loss is cross-entropy against the correct class, so it reflects how the prediction treats that class. The Fast Gradient Sign Method, or FGSM, uses the sign of the gradient in a single update. Projected Gradient Descent, or PGD, updates repeatedly while keeping the total change within the allowed bound. In the paper’s setup, PGD uses eight iterations and a step size of 1/8 gray levels. In that fraction, 1 is the numerator and 8 the denominator, and the value measures the size of an iteration’s change on the gray-level scale. Recomputing the direction after an update lets the iterative method respond to how the change has altered the classifier’s behavior. This gives the authors a way to see whether an apparent advantage holds when they use a stronger test with the same overall pixel budget.
For the spatial test, the allowable changes are shifts and rotations. The authors search a fixed grid that supplies 9 equally spaced choices for each translation axis and 31 equally spaced angles. They use the same grid across images and classifiers.
2511 (9 × 9 × 31)
2511 is the number of spatial transformations in the grid. Within the parentheses, the two 9 values count the horizontal and vertical translation choices and 31 counts rotation choices. The multiplication signs express the use of all combinations. Each translation axis ranges from −16 to 16 pixels, and the rotation angle ranges from −30° to 30°. The minus sign indicates the opposite direction on the given axis or in the angle convention, and ° denotes degrees. The translation range was chosen to span the width of the largest patches discussed in this comparison.
A transformed image is computed with bilinear interpolation, which estimates pixel intensities at displaced coordinates from nearby values. Areas outside the source image are filled with black. For a given classifier and image, the test counts a failure if any transformation on the grid gives the wrong class. This is more demanding than reporting average accuracy across the grid. It asks whether there is a tested placement or angle at which that particular image fails.
How the authors intervene in the network
The internal study begins by comparing representations from different blocks on the same inputs. The authors examine all tokens together and then look at the CLS token on its own. For ViT, the comparison uses the magnitude of the Pearson correlation coefficient. Pearson correlation describes the strength and direction of a linear association. Taking its magnitude treats strong associations of either sign as strong correlations.
|ρ| = 1
ρ stands for the Pearson correlation coefficient. The bars denote its absolute value, = denotes equality, and 1 is the maximum magnitude, shown at the dark end of the paper’s correlation plots. For the extended comparison, the activations come from a random subset of 4096 images in the ILSVRC-2012 validation set. The ResNet comparison uses linear centered kernel analysis, a similarity measure that accommodates representations of different shapes. This is useful across ResNet stages because spatial downsampling changes the dimensions of their activations.
The next step is a lesion study, an evaluation in which a chosen component is bypassed. The authors bypass an entire Transformer block or just one of its attention and feed-forward components. The residual path carries the input forward around the omitted computation. The checkpoint remains trained as before, so the resulting accuracy measures whether the existing network can tolerate that bypass during inference. In the experiment that removes several blocks, the opening block is kept and the other choices are sampled.
n > 1
Here n counts removed blocks, > means greater than, and 1 marks the boundary between a single bypass and the experiment with several. For each tested n, the authors draw 25 independent samples of the removed block set. They report the mean accuracy across those samples, the standard error of that mean, and the lowest and highest observed accuracies. The spread matters because the same number of removed blocks can describe quite different interventions.
The final experiment changes who can attend to whom. Although the network processes a sequence, the authors know each patch’s position in the original image grid. For the restricted-attention experiments, the paper expresses the grid dimensions as follows.
384/16 × 384/16
Each 384 is an input side length in pixels and each 16 is the corresponding patch side length. Each slash denotes division, and × connects the grid dimensions for the two spatial axes. A distance mask suppresses attention between patches if their separation exceeds the chosen limit on either axis. The mask leaves communication between the CLS token and all patches available. A randomly permuted mask keeps the amount of masking the same while changing which pairs are removed. The most severe restriction in this set shuts off direct patch-to-patch links in selected blocks while retaining access between patches and CLS. These tests let the authors distinguish the effect of limiting attention from the effect of specifically preserving local relationships.
Experiments and results
Clean accuracy and benchmark coverage
The clean comparison uses the ILSVRC-2012 validation set. Its main purpose is to anchor the results from the changed inputs. A classifier can achieve higher accuracy after a corruption simply because it was already a stronger classifier on clean images. To see how much clean performance tells them, the authors compare the relative standing of networks across the original and altered distributions. In general, stronger clean performance goes with stronger benchmark performance. This relation holds across several types of changes, which makes clean validation informative, although the spatial and shape tests illustrate how a particular design choice can alter the ordering.
ImageNet-C measures classification with algorithmically generated corruptions. The main groups are noise, blur, weather, and digital changes. They contain 15 corruption types with five severity levels, for 75 distinct settings. An additional group contributes 20 settings. The paper’s aggregate robustness comparison includes 95 settings, with accuracy averaged across corruptions and severities. The benchmark’s setup offers several levels of detail: an overall accuracy, a breakdown by corruption group, and results for particular corruptions such as Gaussian noise, motion blur, fog, and pixelation.
ImageNet-C coverage by corruption group selection
The paper’s aggregate includes both the main corruption groups and the extra group.
The numbers
| System or setting | distinct corruption settings |
|---|---|
| Extra group | 20 |
| Main corruption groups | 75 |
| Aggregate used in the paper (this paper) | 95 |
An aggregate across this coverage estimates how well classification survives a collection of degradations. Each degradation can still tell a different story about what evidence is being lost or altered. Blur can make fine detail difficult to use, while a contrast change affects how intensities distinguish regions. The authors’ separate plots for the groups and individual corruptions let the overall comparison be examined in that narrower setting. The main architecture result is about the broad pattern, with room for variation among individual corruptions.
When training uses the smallest corpus, similarly sized ResNets generally do better on ImageNet-C, and a larger ViT does not reliably improve on a smaller one. That is consistent with the observed clean comparison and with the earlier suggestion that built-in spatial structure is helpful when data is limited. With ImageNet-21k pretraining, most ViTs show stronger corruption tolerance. With JFT-300M pretraining, the improvement is more pronounced and ViTs beat the comparison ResNets on most corruptions. In the larger-data regime, increasing ViT size and using smaller patches can both improve performance. A smaller patch also increases the number of tokens to process, so patch size is a computational choice as well as a representational one.
Renditions and naturally difficult photographs
ImageNet-R supplies renditions of ILSVRC-2012 classes. The pictures include forms such as paintings and embroidery, where the texture and local image statistics can differ from those of the photographs on which the original classification task is based. The authors measure accuracy on those changed depictions. The question is whether the classifier can recognize the category when a different medium expresses it. This makes the test distinct from applying a uniform image operation to existing photographs.
The ordering on ImageNet-R broadly resembles the ordering on ImageNet-C. With the smallest training corpus, the ViTs fall behind the ResNets. The ViTs become more competitive with larger pretraining corpora and can surpass the residual networks. The gains from increasing ViT size are also clearer in the larger-data comparisons. Agreement across these two benchmarks matters because it makes the result less dependent on a single way of generating difficult images. The treatment of visual information changes in different ways when a photograph is corrupted and when the same class of object appears in embroidery.
ImageNet-A presents another case. The images are real photographs, selected because a trained ResNet-50 found them difficult. They retain local image statistics similar to ordinary ImageNet photographs. Though the filter came from one network family, ViTs also struggle with the selected images. The examples therefore expose some shared difficulties between architectures. Pretraining on larger datasets helps ViT, and the authors observe an advantage over ResNet once both have been pretrained on JFT-300M. The selection rule is part of the interpretation because it can make the sample particularly demanding for residual classifiers.
The three benchmarks support a qualified account of architectural robustness. The smallest-data results leave room for the effect of biases such as convolutional locality. The largest-data results show that a network built around patch attention can handle these changes at least as well across a broad range of conditions. ImageNet-A adds the observation that substantial architectural differences do not automatically remove the difficulties of a hard image collection. The weight of each observation comes from the particular selection or construction of the images.
What scaling changes
The scaling comparisons put each classifier’s error rate against its number of trainable parameters. Error rate measures incorrect classifications, so lower values indicate better performance. Holding the pretraining corpus at JFT-300M, the authors observe consistent trends across up to two orders of magnitude in parameter count. The reduction in error with increasing size is more favorable for ViT than for ResNet on the reported comparison. This is visible both on clean ILSVRC-2012 validation and on the robustness benchmarks.
Within each family, the slopes of error against size are fairly similar across the different evaluation sets. Absolute performance can still differ from one dataset to another. Similar slopes suggest that expanding a family can produce related improvements across several sorts of difficulty, even when the underlying reasons that individual images are hard differ. The comparison covers a range of network sizes within a fixed data regime, which is what gives that observation its meaning.
The appendix repeats the scaling comparison for ImageNet-21k pretraining. In most cases, the ViT curve shows no better gains from increasing parameter count than the ResNet curve. ImageNet-C is the exception named by the authors. This qualifies the more favorable scaling trend seen with JFT-300M. A ViT can have strong corruption or rendition accuracy under a given training regime, while the change in its accuracy as parameters are added can still resemble the change seen in ResNets. Performance at one size and the rate of improvement across sizes answer different questions.
Small pixel changes chosen for each classifier
The authors conduct the pixel tests on 1,000 images drawn from the ILSVRC-2012 validation set. The comparison includes accuracy on the original images and on images changed using FGSM or PGD. Most classifiers have the same input dimensions for this comparison. The authors omit ViT-H/14 from the perturbation figure because its expected resolution differs. Evaluating clean and changed versions of the same validation images anchors the perturbation results to the accuracy these networks achieved on that sample.
Both pixel tests reduce accuracy. PGD generally reduces it more, even though it works within the same overall intensity bound. Larger networks tend to maintain higher accuracy, and larger pretraining corpora tend to help. Within those broad tendencies, the rankings depend on the pretraining regime and perturbation procedure. Among the classifiers trained only on ILSVRC-2012, the authors report relatively strong ViT performance compared with similarly sized ResNets, especially under PGD. With ImageNet-21k, ResNets do better against FGSM, while the ViTs do better against PGD. With JFT-300M, FGSM tolerance largely follows network size. Under PGD, the gains from adding parameters appear to diminish past 300 million parameters.
The paper’s overall characterization is that the ResNet advantage observed with the simpler test does not hold under the more successful iterative test. The details by pretraining regime explain why that is a statement about the comparison as a whole. The ranking can reverse in a particular regime. The authors suggest that ViT’s large initial projection might make the first gradient reflect patterns coordinated over a patch-sized region. A perturbation selected in a single update may interact differently with that projection than one whose direction is revised over the course of the test. The explanation identifies a candidate mechanism for the FGSM result.
The transfer experiment asks whether a perturbation retains its effect when applied to a different architecture. The authors generate perturbations for ViTs and evaluate the resulting images with ResNets, then generate them for ResNets and evaluate with ViTs. The headline transfer comparison uses JFT-300M checkpoints, while the extended assessment spans training regimes and includes both perturbation methods. The selected changes cause much less difficulty when moved across families than when used against the classifiers for which they were chosen. This is a different kind of evidence from ImageNet-A, where images selected using a ResNet also prove difficult for ViTs.
The examples visualized from the iterative test help explain what that transfer comparison is probing. In both families, the largest changes appear around foreground objects. For ViT, the patterns exhibit clear alignment with the patch borders. For ResNet, the patterns are less spatially coherent. Two perturbations can have the same maximum pixel change and still have a very different spatial structure. The connection to the ViT patch grid is visible in the examples, independently of the numerical accuracy comparison.
Position, angle, and the balance of visual cues
The spatial results are also reported on 1000 images from the ILSVRC-2012 validation set. Both families are susceptible to shifts and rotations under the grid evaluation. ViTs using 16 × 16 patches generally retain their relative standing alongside similarly sized ResNets. Those using 32 × 32 patches lose substantially more ground. The comparison speaks directly to the concern about placing a fixed patch grid over an image. The use of patches is compatible with spatial robustness comparable to ResNet in this test, with patch size determining how well the tested variants hold up.
The patch-size result is easiest to read against each classifier’s performance on the clean sample. The grid includes changes that keep an object recognizable while shifting the pixel evidence entering particular patch embeddings. A network must keep making the correct prediction across those placements to pass the worst-case test. Its accuracy can fall even when many individual placements would still work. The experiment thus measures a stricter form of stability over the tested transformations than a comparison built from one randomly chosen shift for each image.
The Conflict Stimuli experiment changes the role of patch size. The benchmark uses 160 object images with white backgrounds and 48 texture images. Style transfer combines object shapes with textures to produce 1280 test images, including examples whose shape and texture suggest different categories. Shape accuracy is the fraction of test examples classified in agreement with the object’s shape. A higher value indicates that shape guided the classifier to the target category more often under the conditions of the benchmark.
On this measure, 32 × 32 ViTs outperform their 16 × 16 counterparts. The authors suggest that a larger patch may preserve more shape information within a region. Their comparison also shows that the JFT-300M ResNets do not rank by network size on shape accuracy as they do on the other reported tests. The shape result identifies a tradeoff in what the smaller patches buy. The finer grid accompanies better spatial stability and stronger results on the main classification benchmarks, while the coarser grid is associated with stronger shape-based classification when texture can conflict with shape.
What the ablations show
Similar patch states can coexist with an evolving prediction
The authors first compare the hidden representations produced by pairs of blocks. A hidden representation is the collection of token vectors at that point in the network. When all tokens are considered, the later blocks form a large group with highly correlated representations. Earlier blocks also exhibit grouping, but the concentration of similarity near the end is the most prominent feature. The ViT develops this pattern without the explicit arrangement into spatial stages found in the comparison ResNets, where downsampling marks changes in resolution.
Repeating the analysis with just the CLS token gives a different profile. Its representation changes comparatively slowly near the beginning and more quickly later on. Since the final classifier reads the CLS representation, those late changes are relevant to interpreting the apparently stable all-token results. The patch representations make up most of the sequence. Substantial similarity among those representations can dominate the view of all tokens even while the part of the sequence that directly supplies the prediction continues to evolve.
The interpretation offered by the paper is that early computation develops representations through interactions among image patches, while later computation concentrates more on gathering task-relevant information into CLS. The correlation evidence locates where representations change, and the attention masks test the proposed division of labor more directly. A late block could update CLS by reading patch features that it leaves largely intact. Such an operation would produce both the high similarity of patch states and a meaningful change in the final classification state.
The extended correlation analysis considers ViT-B/32, ViT-B/16, ViT-L/32, and ViT-L/16 across the different pretraining regimes. Its ResNet reference covers ResNet-50x3, ResNet-101x1, and ResNet-101x3. The comparison makes it possible to see grouping in both families, with similarity measured in a way appropriate to the shape of each family’s activations. The connection is structural rather than a direct comparison between numerical scores from the two similarity measures. One family has stages separated by changes in resolution. In the other, groups are inferred from how alike the representations look across depth.
Which computations can be bypassed
The lesion study tests whether a single component is needed once the network has been trained. Bypassing the opening block is the conspicuous exception to the pattern of small losses from individual deletions. Most other single blocks can be bypassed without a substantial drop in accuracy. The authors see a similar tolerance when they bypass one attention layer or one feed-forward layer. These are distinct interventions because each block has separate skip paths around those parts. The experiment isolates the contribution of an individual update in the presence of the rest of the trained computation.
A plausible reason the opening block stands out is that its output is the first representation contextualized by the stack. Later blocks ordinarily receive patch tokens whose representations have already been updated using information from elsewhere in the image. Bypassing the first block changes the starting point for all those later updates. The lesion result establishes the opening block’s greater importance for the trained network. The additional attention restrictions show that early cross-patch exchange matters as well, giving more specificity to the observation than the lesion result could supply on its own.
The multiple-removal comparison gives a clearer picture of redundancy. The larger ViTs usually hold up better as more blocks are removed, while accuracy in smaller variants declines quickly after relatively few removals. The average across sampled removals describes what happens to a typical selection at a given count. The minimum and maximum show how much the identity of the removed blocks can matter. Keeping the first block across these comparisons prevents the failure associated with bypassing that exceptional position from dominating the result.
The pretraining comparison reverses a pattern seen in several of the input tests. Larger pretraining corpora help recognition under changed images, but the resulting ViTs tend to lose more accuracy when parts of the network are removed. The authors suggest that the larger datasets may lead the network to use more of the available computation. Here utilization is an interpretation of the measured sensitivity. Removing a component creates a larger penalty in those checkpoints, which is consistent with that component making a greater contribution to the trained computation.
Bypassing complete blocks causes larger losses than bypassing individual sublayers. Among the two kinds of sublayers, removing a given number of attention layers causes more damage than removing the same number of MLP layers. The comparison is especially informative because both interventions preserve the skip path and leave the other sublayer in each affected block available. Attention is the component that exchanges information among token positions. Its greater importance under removal is consistent with interactions among positions being harder for the remaining computation to compensate for. The paper notes that earlier observations for language Transformers may favor the opposite ordering.
When local attention is enough
The restricted-attention study asks a narrower question than whole-layer removal. It preserves the attention operation and alters the set of token pairs it can use. When patch attention is restricted to spatial neighbors, accuracy generally degrades gradually as the restriction tightens. These classifiers learned with unrestricted attention. Their ability to keep recognizing images with only local direct exchange between patches shows that substantial parts of the learned computation remain effective through those connections.
The randomly permuted mask is important because any mask removes potential communication. If the local mask alone were evaluated, its result would combine two effects: how many entries were removed and which spatial relationships were preserved. Random permutation provides a comparison at the same amount of masking. In most settings studied, the random restriction does more damage than the spatial one. The large ViT trained only on ILSVRC-2012 is a notable exception. Thus the advantage of preserving neighbors is an observed pattern across the study with a specific counterexample.
The CLS token still has access to every patch under these masks. An image-wide route therefore remains open even when direct patch-to-patch attention is local. The result indicates how much direct long-range exchange the patch tokens can lose under those conditions. It also helps explain why masking distant pairs need not have the same effect as removing entire attention layers. A restricted layer can still pass information locally and still contribute to the global readout.
The strongest intervention within this study blocks direct interactions among patches entirely in selected layers. For ViT-B/16 pretrained on JFT-300M, the authors compare doing this near the beginning and near the end. Applying it late has relatively little effect on ILSVRC-2012 accuracy. Applying it early causes a substantial reduction. The number and placement of available paths matter more here than the mere presence of an abstract attention mechanism. The early patch representations depend strongly on exchanging spatial information, while the later computation can make effective use of the patch features already available to CLS.
Read together, the interventions explain how late blocks can matter even with highly correlated patch representations. Cutting direct patch interactions leaves the late CLS update available, so the prediction can still use information from different regions. Bypassing a whole block removes that update along with the other calculations. Bypassing several blocks can then remove enough opportunities to update the shared readout that accuracy declines. This account connects the correlation analysis, the depth-dependent mask experiment, and the gradual deterioration under repeated removal.
Limitations
Qualifications the authors give
The clearest warning concerns ImageNet-A. The image selection favors examples that were already hard for a ResNet-50. A ViT’s advantage over a ResNet on that sample has to be interpreted alongside the selection rule. The shared challenge remains an observation in its own right: ViTs struggle with many of the difficult photographs despite the different way they process inputs. The comparative advantage under JFT-300M is more sensitive to how the collection was assembled.
The authors also condition the favorable scaling comparison on the volume of pretraining data. JFT-300M supports the stronger ViT trend, while ImageNet-21k generally does not, with ImageNet-C identified as an exception in the appendix. Their suggestion that the gap could grow at larger sizes is an extrapolation from the measured error trends. Similar slopes across benchmarks offer a basis for asking whether the pattern extends further. They do not establish how the relation will behave on other tasks or at sizes beyond the studied checkpoints.
In discussing deliberate changes to images, the paper presents the connection between FGSM and the patch projection as a likely explanation. The visualized alignment with the patch grid is consistent with a role for the input representation. A direct causal test would have to vary the initial projection while accounting for other changes to the network and training. The explanation for the shape result is similarly tentative. A larger patch offers a plausible way to retain more of an object’s local shape, while the measured outcome is an association between patch size and shape accuracy on Conflict Stimuli.
The findings on redundancy lead the authors to suggest that a ViT could be pruned for inference. Their evidence is the tolerance of trained checkpoints to bypasses and masks, accompanied by a decline when enough computation is removed. Removing some layers successfully does not specify a pruning schedule, which layers to keep in a compressed network, or the resulting deployment cost. The experiments establish where there is room for intervention and where the trained classifier is particularly sensitive.
Further limits of the experimental design
The corpus comparisons vary more than the amount of data. ILSVRC-2012, ImageNet-21k, and JFT-300M are different collections. They are not controlled subsamples of a single corpus trained under an otherwise identical procedure. In addition, the ViT and ResNet weights came from their respective original studies. The use of comparable families, shared pretraining regimes, and a common fine-tuning target makes the comparisons informative, while the corpus and checkpoint design limits how completely the effects of architecture, training process, and data composition can be disentangled.
The clean and perturbed evaluation results are largely expressed as accuracy and error on particular datasets. If two classifiers begin at different clean accuracies, the one with better accuracy under a change can have more room to lose in the process. A statement about which classifier achieves the higher perturbed accuracy differs from a statement about which classifier loses fewer of its initially correct predictions. The paper’s finding that clean rankings tend to predict perturbed rankings is evidence for reading both together. It leaves room for patch size, the attack procedure, and the source of the images to alter a specific comparison.
The deliberate pixel changes are tested under one reported magnitude bound on a subset of the validation set. FGSM and PGD provide empirical evidence about failures those procedures can find. Their results do not guarantee correctness for every change inside the bound. Likewise, poor transfer across families applies to the perturbations constructed and compared in the paper. The selected changes are evidence about the relation between those networks under the tested procedure, and the result has limited reach beyond that procedure.
The spatial test has its own boundary. It searches a discrete grid with fixed translations and angles, uses bilinear interpolation, and fills the uncovered image area with black. A failure establishes sensitivity somewhere in that grid. The setup does not isolate the effect of crossing a patch border from the effect of interpolation or from the change in visible content at the image boundary. The patch-size comparison is therefore strongest as a finding about classification under the common test. Extending it to every possible subpatch displacement or every way of rendering a rotated image would require additional evidence.
Shape accuracy is also tied to the construction of the benchmark. It indicates agreement with the source shape under the particular combinations produced by style transfer. The measure cannot identify the full set of cues used for ordinary photographs or establish that a classifier has learned shape in the same way a person does. The comparison remains informative precisely because its task is narrower. It probes a condition under which texture and shape can support different answers and reports which variant more frequently follows the shape label.
Finally, the internal analyses characterize trained networks at inference. Correlated representations show similarity across blocks, but can conceal small changes that matter to the decision. A successful bypass shows that the remaining computations can support a correct answer in its absence. It says little about whether that computation helped during training, whether other tasks need it, or whether the same removal preserves robustness under image changes. The attention experiments also retain a global path through CLS. Their conclusion about local patch attention therefore concerns a network with that path available. These qualifications place the strongest mechanistic finding at the level the interventions actually test: the relative importance of early direct patch exchange and late classification readout in the studied ViTs.
What came after
Towards Robust Vision Transformer takes up the question of robustness as a design objective. The earlier study evaluates already trained ViTs and shows that their tolerance depends on patch size, pretraining, and the kind of change applied to the image. The later work’s stated aim is to develop a robust Vision Transformer. That shift in aim makes the benchmark distinctions in the earlier paper consequential. A design intended to improve robustness has several possible targets, including accuracy under ordinary corruptions and stability under particular spatial or pixel changes. Improvements under one of those tests do not by themselves characterize behavior under the others.
MLP-Mixer pursues an all-MLP architecture for vision, extending the architectural question raised by the comparison with ResNet. The earlier paper studies a stack in which self-attention exchanges information across tokens and the MLP processes each token separately. An all-MLP vision architecture asks what can be achieved with a different choice of building block. This is related to the lesion evidence in a specific way. Bypassing attention in a ViT measures the contribution of attention to a system trained to use it. Designing an architecture around MLPs concerns what the complete system can learn when its building blocks and their roles are chosen from the start. The citation connects these lines of inquiry, while the architectural goal is distinct from reproducing the earlier intervention.
DAFormer addresses the related problem of domain-adaptive semantic segmentation through network architecture and training strategy. Segmentation asks for a spatially resolved assignment of categories, whereas the ViT robustness paper reads out a single class for an image. Domain adaptation asks how to handle the change from one image distribution to another. The connection lies in treating robustness under changed input conditions as dependent on both the architecture and how that architecture is trained. The earlier paper contributes classification evidence that the relative standing of architectures under a shift can change with pretraining. The later work takes that broad concern into a setting where adaptation and spatial predictions are the focus.
Cite
Cite as Srinadh Bhojanapalli, Ayan Chakrabarti, Daniel Gläsner, Daliang Li, Thomas Unterthiner and Andreas Veit. 2021. Understanding Robustness of Transformers for Image Classification. IEEE/CVF International Conference on Computer Vision (ICCV).
@inproceedings{bhojanapalli2021understanding,
title = {{Understanding Robustness of Transformers for Image Classification}},
author = {Srinadh Bhojanapalli, Ayan Chakrabarti, Daniel Gläsner, Daliang Li, Thomas Unterthiner and Andreas Veit},
booktitle = {IEEE/CVF International Conference on Computer Vision (ICCV)},
year = {2021},
doi = {10.1109/iccv48922.2021.01007},
eprint = {2103.14586},
archivePrefix = {arXiv},
url = {https://doi.org/10.1109/iccv48922.2021.01007}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bhojanapalli-2021-understanding-robustness-transformers-image-classification/