---
title: "ConViT — paper by d’Ascoli et al. (2022) — summary and ideas"
description: "ConViT gives vision transformers a convolution-like starting point that they can move beyond, improving image classification with limited…"
canonical: "https://research.elamur.ai/free/en/papers/ascoli-2022-convit-improving-vision-transformers-soft/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/ascoli-2022-convit-improving-vision-transformers-soft/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2022](https://md.research.elamur.ai/free/en/papers/2022/) / ConViT: improving vision transformers with soft convolutional inductive biases*

# ConViT: improving vision transformers with soft convolutional inductive biases*

Paper · 2022 · Stéphane d’Ascoli, Hugo Touvron, Matthew L. Leavitt et al.

**Authors:** [Stéphane d’Ascoli](https://md.research.elamur.ai/free/en/authors/stephane-d-ascoli/), [Hugo Touvron](https://md.research.elamur.ai/free/en/authors/hugo-touvron/), [Matthew L. Leavitt](https://md.research.elamur.ai/free/en/authors/matthew-l-leavitt/), [Ari S. Morcos](https://md.research.elamur.ai/free/en/authors/ari-s-morcos/), Giulio Biroli and [Levent Sagun](https://md.research.elamur.ai/free/en/authors/levent-sagun/) · **Year:** 2022 · **Venue:** Journal of Statistical Mechanics Theory and Experiment · **Licence:** [arXiv — non-exclusive license to distribute](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

[Cited by **37** papers in our library of more than 163,000 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/ascoli-2022-convit-improving-vision-transformers-soft/cited-by/) · Journal of Statistical Mechanics Theory and Experiment · [licence](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

- [PDF](https://arxiv.org/pdf/2103.10697)
- [DOI 10.1088/1742-5468/ac9830](https://doi.org/10.1088/1742-5468/ac9830)
- [arXiv 2103.10697](https://arxiv.org/abs/2103.10697)

## Summary

A photograph contains clues at very different distances. The patches along an edge can make sense together because they are neighbors. Recognizing the object that edge belongs to may require comparing it with parts much farther away. Convolution gives an image classifier a strong starting assumption about the first kind of clue. It applies the same small neighborhood operation across the image. A vision transformer can compare patches across the whole image from the start, but it has more to learn about which comparisons are worth making. The ConViT paper asks whether a vision transformer can start with the advantages of a convolution and still learn when to look farther afield. Its answer is to put the preference for local interactions in the initial settings of attention and let training change it. [Transformer and attention](https://md.research.elamur.ai/free/en/concepts/transformer/)

The authors introduce gated positional self-attention, or GPSA. Each attention head prepares one distribution over patches based on their relative positions and another based on their current representations. At initialization, the position-based distribution concentrates around an assigned offset, so different heads favor different places in a neighborhood. A learned gate determines how much of each distribution goes into the combined attention. Heads can keep using their starting neighborhoods, change the shape of those neighborhoods, or increasingly favor the content-based distribution. ConViT uses these gated operations early in the network and ordinary self-attention near the output.

On the ImageNet-1k test set, the authors report 82.2% top-1 accuracy for ConViT-S+ and 79.0% for DeiT-S+ in their main comparison, with both variants listed at 48M parameters. The advantage is larger when training uses fewer distinct images. In the class-by-class sub-sampling experiment, the table reports top-1 accuracy of 59.6% for ConViT-S and 48.0% for DeiT-S when each trains on 10% of the ImageNet-1k training images. The comparison holds the total exposure to training images constant by revisiting the smaller subsets more often. The headline ImageNet results use training from scratch without a teacher. A separate experiment shows that ConViT can also benefit from distillation.

The authors track where attention goes during training. Ordinary DeiT attention moves towards nearby patches early on, while ConViT's initially concentrated heads spread their attention to different degrees. In trained ConViTs, some early heads continue to use relative position heavily, while later gated layers favor content. The ablations help explain why the combination matters. A convolution-like initialization can give conventional positional attention an early advantage that disappears by the end of training. Separately normalizing the position and content distributions, then mixing them through a trainable gate, gives the classifier a more effective way to use spatial structure early and depart from it as learning proceeds.

## Deep dive: ConViT: improving vision transformers with soft convolutional inductive biases*

ConViT gives vision transformers a convolution-like starting point that they can move beyond, improving image classification with limited training data. · about 34 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### The assumptions built into convolution

An image classifier has to learn which variations matter for recognizing a class. A local visual pattern may contribute evidence wherever it appears in the frame. Conversely, a patch can belong to an object whose identity also depends on something on the other side of the image. A design can make one of those relationships easy to express at the outset and leave the other to be learned through several stages of processing. The paper treats this allocation of effort as a question about inductive bias, the preference a learning system brings to a problem before the examples have determined a solution.

Convolution builds in two related preferences. Locality limits the input to a spatial operator to a neighborhood around the position being processed. Weight sharing means that the same operator applies at different positions. Each offset within the neighborhood can have its own weights, but those weights are reused as the operator moves across the image. This reuse helps a feature found in one location to be recognized elsewhere without learning a separate detector for each location. It also reduces the number of adjustable weights that the training examples have to constrain.

The paper relates these properties to how a network responds to a translation. A spatial representation is equivariant when moving the input moves the representation correspondingly. Invariance refers to an output that remains the same under the movement. The authors associate shared local processing with equivariance and describe pooling as a route toward invariance. For classification, the broad appeal is that the evidence for a class can recur at different places. Convolution incorporates that expectation into the operation itself.

A stack of local operations can combine information over increasingly large parts of an image. A single local operation, however, can directly use only the positions its kernel covers. Self-attention provides a more direct connection between distant patches. It can also change how strongly it connects two locations when the image changes. Those properties expand what a layer can do, while leaving more choices to training. With few distinct examples, the authors argue that many of these choices are weakly constrained. A preference for ordinary spatial neighborhoods can then make the search for useful computations easier.

#### How image attention changed the trade-off

The paper traces attention from sequence-to-sequence systems, where it supplemented recurrent processing, to the Transformer, where self-attention became the main way elements of a sequence exchange information. In sequence-to-sequence translation, attention provided a mechanism for relating the part of a sequence being produced to relevant parts of the input. Self-attention applies the matching principle within a representation, so that each element can collect information from other elements of the same sequence. The paper points to the success of pretraining as part of the context for the wider adoption of this approach. [Neural Machine Translation by Jointly Learning to Align and Translate](https://md.research.elamur.ai/free/en/papers/bahdanau-2014-neural-machine-translation-jointly-learning/) · [Attention Is All You Need](https://md.research.elamur.ai/free/en/papers/vaswani-2017-attention-all-need/) · [BERT](https://md.research.elamur.ai/free/en/papers/devlin-2019-bert-pre-training-deep-bidirectional/)

The corresponding move in vision was to represent an image as a sequence of embedded patches. Once an image has this form, a self-attention layer can examine the relationships among its patches without hard-coding a small spatial neighborhood for each output. The Vision Transformer, or ViT, showed how far that design could go for classification with extensive pretraining. For the ConViT authors, its appetite for pretraining data raised a separate question from eventual accuracy. A flexible architecture can be capable of learning an effective image classifier and still need considerable evidence to find one. [Vision Transformer](https://md.research.elamur.ai/free/en/papers/dosovitskiy-2020-image-worth-16x16-words-transformers/)

DeiT, the Data-efficient Image Transformer, supplied the more immediate comparison. It offered a training recipe for image transformers using ImageNet without additional pretraining data, and it also explored knowledge distillation from a convolutional teacher. In distillation, the teacher's outputs provide training guidance to the student. This gives the student access to preferences embodied in a trained convolutional classifier even when the student uses attention for spatial interactions. ConViT asks what portion of that help can come from placing a spatial preference directly in the student at initialization. A teacher remains a compatible option in the experiments. [DeiT](https://md.research.elamur.ai/free/en/papers/touvron-2020-training-data-efficient-image-transformers/) · [Distilling the Knowledge in a Neural Network](https://md.research.elamur.ai/free/en/papers/hinton-2015-distilling-knowledge-neural-network/)

Other work had already explored ways to combine convolution and attention within a network. The paper describes architectures that augment convolutional processing with attention and experiments that replace selected convolutions with attention. One set of replacement experiments found the strongest results with convolution early and attention later. This division suggests that useful spatial interactions can change with depth. It also leaves a design decision to the architect, who chooses in advance the stages at which the network switches between the operations. In the gated layers of ConViT, training can change that balance individually for each head.

#### Why initialization is a plausible place for the bias

The connection between self-attention and convolution gave the authors a more specific starting point than simply asking early attention to stay close to the query. They draw on work showing that positional self-attention can represent a convolution if each head selects a particular offset and the outputs are then combined appropriately. A group of such heads can gather the same pattern of relative locations that a convolutional kernel would cover. The earlier work also observed emerging convolution-like patterns in attention trained with relative position information. That made a structured spatial starting point plausible for an operation that already had the capacity to express it.

The authors connect this to previous experiments that initialized fully connected networks to behave like convolutional ones and then allowed the additional connections to be trained. In both settings, the initial computation embodies a prior about the problem while the subsequent parameterization permits a wider range of solutions. For ConViT, the question is how to give an attention head a recognizable spatial role now, while keeping the route to content-dependent behavior usable later. The design therefore has to address both the initial attention map and the mechanism by which it can change.

### The method, step by step

#### Represent the image as a sequence of patches

ConViT starts with the patch representation used by its vision-transformer baseline. The input image is divided into non-overlapping patches, and a convolutional stem converts them to vectors. Each vector describes a patch in a form the following blocks can process. The patches still have positions on the original image grid, so the network can associate a displacement with any pair of patch locations. The sequence representation is what self-attention processes. The grid is what gives the positional part of GPSA its meaning.

The paper describes the architecture at an input size of 224. A learned absolute position embedding is added to each patch representation at the input. This gives a patch a signal for where it lies in the image. The relative representation used by GPSA has a different role. It describes where a possible source patch lies in relation to the patch receiving information. A head can therefore use one set of relative-position weights for the same displacement throughout the grid, while the input embeddings can still carry information about absolute location.

How ConViT processes an image The steps in order.

#### Let patches exchange information through attention

Consider a patch whose representation is about to be updated. Its query is a vector used to ask which parts of the image have relevant information. Each candidate source patch supplies a key, a vector against which the query is compared, and a value, which is the information that can actually be passed along. These roles are implemented as learned projections. A patch can derive all of them from its current representation, while the different projection weights let each representation serve a different purpose.

The comparison between a query and a key uses their inner product. A normalization called softmax converts the scores for a given query into weights that sum to one. The more weight a source patch receives, the larger its contribution to the weighted combination of values. The head can thus use several patches for one update, weighting them according to how their keys score against the query.

```
A = softmax(QKᵀ / √Dₕ) ∈ ℝᴸ¹ˣᴸ²
```

Here A is the attention matrix, Q contains the query vectors, and K contains the key vectors. The superscript ᵀ transposes K so that matrix multiplication pairs queries with keys. Dₕ is the width of a query or key in a head, and √ denotes the square root used to scale the scores. L¹ and L² denote the query and key sequence lengths, respectively. The expression ℝᴸ¹ˣᴸ² indicates a real-valued matrix with a row per query and a column per key. The operation softmax applies separately to each row.

```
softmax(X)ᵢⱼ = exp(Xᵢⱼ) / ∑ₖ exp(Xᵢₖ)
```

In this formula X is any matrix of scores, and Xᵢⱼ is the entry for query row i and candidate column j. The function exp is the exponential. The sum runs over all candidate columns k for the same row. Dividing by that sum makes the weights for the row positive and normalizes their total. The X in this definition denotes a score matrix. In the attention-layer formulas below, X denotes the input sequence of embedded representations.

In self-attention, the queries and keys are formed from the same sequence. The paper denotes the input by X and its embedding width by Dₑₘᵦ. With one patch per row, the query and key projections multiply that matrix on the feature side. Both projections take Dₑₘᵦ input features to Dₕ features for each head. They create the vectors used to choose where information comes from. The value projection separately determines the information available to send.

```
SAₕ(X) = Aʰ X Wᵥₐₗʰ
```

SAₕ is the output of self-attention head h. X is the matrix of input representations, Aʰ is the attention matrix computed by that head, and Wᵥₐₗʰ is its learned value projection. The product X Wᵥₐₗʰ supplies a projected value for every source. Left-multiplying by Aʰ produces a weighted combination of those values for each query. The head's output has a row for every input position and Dₕ features in each row.

```
MSA(X) = concatₕ∈Nₕ) Wₒᵤₜ + bₒᵤₜ
```

MSA denotes multi-head self-attention. The function concat joins the outputs SAₕ(X) of the heads along the feature dimension. The index h ranges over the Nₕ heads, as indicated by [Nₕ]. Joining the heads gives the full embedding width Dₑₘᵦ, which the paper defines as Nₕ times Dₕ. The learned matrix Wₒᵤₜ projects the combined representation back to the block's feature space, and bₒᵤₜ is an output bias added at each position. The projections let heads gather different kinds of information in parallel and allow the layer to combine what they gather.

#### Give positional attention a neighborhood to start from

The query and key comparison has no separate term for the displacement between image locations. Absolute position embeddings can influence the representations from which the queries and keys are formed. The paper also considers an explicit positional self-attention rule, or PSA, that includes a score for relative position. In that rule, the content score and the relative-position score enter the same softmax.

```
Aᵢⱼʰ = softmaxⱼ((Qᵢʰ)ᵀ Kⱼʰ + (vₚₒₛʰ)ᵀ rᵢⱼ)
```

Aᵢⱼʰ is the weight that head h assigns from query i to source j. Qᵢʰ and Kⱼʰ are the corresponding query and key vectors, and ᵀ indicates the transpose in an inner product. The relative position of patch i with respect to patch j is represented by the vector rᵢⱼ. The vector vₚₒₛʰ contains the head's learned weights for that encoding. Their inner product gives a scalar spatial score, which the rule adds to the query–key score. The subscript j on softmax indicates that the sum of the two scores is normalized across all sources for a fixed query.

The positional score can express a particular kind of local behavior. For each head, choose an offset relative to the query, such as a diagonal neighbor. Favor locations at that offset and reduce the score as a source gets farther from it. If each head is assigned one offset in a small grid, the heads together can retrieve a configuration of neighbors like the one covered by a convolutional kernel. Each query uses the same offset assignments. This is how the construction reflects weight sharing across spatial locations.

```
rᵢⱼ = (‖δᵢⱼ‖², δᵢⱼ,₁, δᵢⱼ,₂)
```

The vector rᵢⱼ is the fixed positional encoding used by ConViT for patch pair i, j. The displacement δᵢⱼ has two coordinates on the patch grid, written δᵢⱼ,₁ and δᵢⱼ,₂. The notation ‖δᵢⱼ‖² gives the squared Euclidean length of that displacement. The encoding has Dₚₒₛ = 3 components in the gated layers. It uses the same rule across the grid and remains fixed through training.

```
vₚₒₛʰ = −αʰ (1, −2Δ₁ʰ, −2Δ₂ʰ)
```

Here vₚₒₛʰ is the initial position-weight vector of head h. Its assigned center Δʰ is a displacement with coordinates Δ₁ʰ and Δ₂ʰ. The positive αʰ sets the initial concentration around that center. The constants 1 and −2 set the coefficients of the squared distance and coordinate terms when this vector is dotted with rᵢⱼ. The position score then favors displacements near Δʰ. A term depending only on the chosen center would add the same quantity to every score in a row, which leaves that row's softmax unchanged.

A concentrated head and a broad head can favor the same offset. The concentration determines how sharply preference drops as the source moves away from that offset. For large αʰ, the position distribution tends towards selecting the source at the chosen displacement where it is available. For smaller αʰ, surrounding locations contribute more. The authors illustrate the distinction using an ImageNet image, one query patch, and different initial locality strengths. The ordinary untrained attention map can already show shapes from the input. The purely positional maps instead reflect the offsets and concentrations assigned to the heads.

The paper first states this construction for conventional PSA. There, setting the query and key projection matrices to zero makes the initial attention depend only on position, and identity value weights provide the construction's starting value transformation. With sufficiently concentrated heads covering the offsets of the kernel, the subsequent output projection can combine the retrieved values as a convolution combines contributions from different offsets. ConViT takes the offset assignment and the form of the spatial weights from this construction. Its separate gate lets the content projections stay active from the beginning.

Keeping rᵢⱼ fixed also changes how positional attention scales in trainable parameters. ConViT learns a short position-weight vector for each head instead of learning a vector separately for the many positional comparisons. The same scoring rule gives a weight to every available displacement. Training can therefore alter the effective center or span of positional attention by changing the head's weights. This retains routes to faraway patches without introducing the hard neighborhood cutoff discussed in the paper's account of earlier positional attention.

#### Normalize position and content separately, then mix them

In ordinary PSA, the two scores compete inside a single softmax. Their magnitudes matter because the exponential normalization can make a large difference in one score dominate smaller differences in the other. A very concentrated spatial initialization can consequently give the query–key comparisons little influence. This creates a difficulty for training. The spatial preference helps early, but a content mechanism that makes little difference to the output can have difficulty becoming useful later.

GPSA changes the order of operations. It uses one softmax on the content scores and another on the positional scores. Both branches then supply a distribution over the same sources. A learned scalar for each head determines how to combine the two. A sharply concentrated position distribution can coexist with a content distribution that gives high weight to completely different patches. The gate decides the overall contribution of each branch, while each branch decides how to allocate its own contribution.

```
σ(x) = 1 / (1 + exp(−x))
```

The function σ is the sigmoid and x is any real scalar, here evaluated on the head's gate parameter. The function exp is the exponential. The positive denominator maps the parameter to a weight between zero and one, rising as the parameter rises. In GPSA, this weight is the share assigned to the positional distribution.

```
Aᵢⱼʰ = (1 − σ(λʰ)) softmaxⱼ((Qᵢʰ)ᵀ Kⱼʰ) + σ(λʰ) softmaxⱼ((vₚₒₛʰ)ᵀ rᵢⱼ)
```

The entry Aᵢⱼʰ belongs to head h, query patch i and source patch j. The gate parameter is λʰ, and σ(λʰ) is the position share. The expression 1 − σ(λʰ) gives the content share. Qᵢʰ and Kⱼʰ are the query and key vectors in the content branch. The position branch compares vₚₒₛʰ, the head's spatial weights, with rᵢⱼ, the fixed encoding of their displacement. The superscript ᵀ indicates the transpose in each inner product. Each softmaxⱼ normalizes its own scores over the candidate sources for query i. Addition combines the resulting weighted distributions.

```
normalize(A)ᵢⱼ = Aᵢⱼ / ∑ₖ Aᵢₖ
```

The paper writes an explicit row normalization for the resulting attention. A is the matrix being normalized, Aᵢⱼ is the weight for source j in query row i, and k indexes every source in that row. The denominator is the row's total weight. This expresses attention as a probability distribution over source locations. With both branches row-normalized and their mixing weights complementary, the mixture already has unit row sums in exact arithmetic.

```
GPSAₕ(X) = normalize(Aʰ) X Wᵥₐₗʰ
```

GPSAₕ is the output of the gated positional head h, X contains the input patch representations, and Aʰ is its mixed attention matrix. The function normalize is the row normalization just defined. The learned value matrix Wᵥₐₗʰ projects the input representations before they are gathered. Thus both attention branches act on the same projected values. The branch choice changes where the head gathers information from, and the value projection determines what features are available at those sources.

In principle the authors could initialize λʰ at a large positive value to give the spatial branch nearly the entire mixture. They choose λʰ = 1 for every GPSA head instead. This sets a preference for position while allowing a contribution from content from the outset. Both λʰ and vₚₒₛʰ can subsequently change. A head can become less local by reducing the weight of position, by broadening its positional distribution, or by changing where that distribution is centered. Conversely, content attention can itself concentrate on nearby patches if their representations make them useful sources. The gate measures reliance on a scoring branch, while the spatial distances of the resulting attention measure where information is gathered.

The gate is a learned parameter of each head, so it specifies that head's branch mixture once training has set it. The content scores still vary with the query and the image. This distinction matters for interpreting the design. Two heads in the same layer can settle on different mixtures, and one head can give different patches high content scores in different images. The gate itself expresses a head-level preference shared across those images.

#### Assemble the classifier and set up the comparisons

The standard architecture described in the paper has 12 blocks, with GPSA in the first 10 and ordinary self-attention in the final 2. Each block also contains a feed-forward network made of 2 linear transformations with a GeLU activation between them. The feed-forward network acts on each representation after attention has exchanged information across positions. Residual connections carry the incoming representation alongside the output of both the attention operation and the feed-forward operation. The block stack maintains the embedding width.

A class token provides the representation used to predict the image label. The token has no ordinary position on the patch grid. ConViT therefore appends it after the last gated block, where the remaining attention operates without the explicit pairwise displacement rule. Earlier gated blocks exchange information among patches. The ordinary attention blocks then allow the class token to collect information from the resulting patch representations. This placement keeps the spatial construction tied to pairs of locations for which displacement is defined.

The authors retain the absolute position embeddings of the baseline in the main comparisons. The earlier gated layers therefore receive representations that already have absolute position information while also receiving fixed relative coordinates in their positional attention calculation. Keeping both in place avoids changing that aspect of the input recipe at the same time as the attention mechanism. A later masking experiment tests how much the trained classifiers depend on the absolute embeddings.

To allocate spatial roles, the authors consider initial grids resembling 2 × 2, 3 × 3 and 4 × 4 convolutional filters, using 4, 9 and 16 heads respectively. This changes head count relative to the original DeiT configurations, which use 3, 6 and 12 heads. They consequently set up two comparisons. The first starts from the published DeiT sizes and training recipe. It uses 48 instead of 64 features per head in the ConViTs to bring overall widths and parameter counts closer to the original DeiTs. The paper calls these versions ConViT-Ti, ConViT-S and ConViT-B. The small pair still differs in width and parameter count, an important qualification when comparing their accuracies.

The second comparison matches the head count across architectures and uses 64 features per head for both. These are the variants with a plus sign in their names. Matching both quantities lets a reader compare architectures at equal widths and equal reported parameter counts. The authors lower the learning rate from 0.0005 to 0. 0004 and a reduction in batch size from 1024 to 512 for stable training of these variants on 8 GPUs. For the comparisons with the original DeiTs, they retain the published scheduling, augmentation and regularization settings. The paper reports releasing the ConViT implementation and pretrained weights.

### Experiments and results

#### Classification accuracy on the full training set

The main experiments train from scratch on ImageNet-1k and report accuracy on its test set after 300 epochs. Top-1 accuracy gives credit when the most highly ranked label matches the image's class. Top-5 accuracy gives credit when the correct label is anywhere in the first five predictions. The paper reports the training configurations alongside parameter counts, operation counts and throughput. Those quantities help separate a gain in classification accuracy from a change in the resources used to obtain it.

The main comparison uses no distillation. Results for the original DeiT-Ti, DeiT-S and DeiT-B are taken from the DeiT paper. The authors also train the matched-head variants themselves. Within those pairs, both architectures have the same reported width, head count, parameter count and operation count. This makes them a direct test of whether the improvement is simply a consequence of adding heads to a vision transformer. The results favor ConViT within each of the matched pairs.

Matched-head DeiT and ConViT on ImageNet-1k test top-1 accuracy ConViT leads its matched-head DeiT comparison at every reported size.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| DeiT-Ti+ | 75.9 |
| ConViT-Ti+ (this paper) | 76.7 |
| DeiT-S+ | 79.0 |
| ConViT-S+ | 82.2 |
| DeiT-B+ | 77.5 |
| ConViT-B+ | 82.5 |

At the tiny matched setting, each architecture has 10M parameters and is listed at 2G operations. The small matched pair has 48M parameters and 10G operations for either architecture. The base matched pair is listed at 152M parameters and 30G operations each. The base DeiT+ attains lower top-1 accuracy than the small DeiT+, while ConViT's reported accuracy increases across these settings. The paper suggests that this pattern may reflect sensitivity to the adjusted training settings. It comes from the particular shared recipe used to fit the plus variants on the available hardware.

The original-size comparisons provide a second view. On the ImageNet-1k test set, the published DeiT-Ti scores 72.2 top-1 and ConViT-Ti scores 73.1, with both at 6M parameters and 1G operations. The base comparison is also matched by those reported counts. DeiT-B scores 81.8 and ConViT-B scores 82.4, both at 86M parameters and 17G operations. The small comparison uses 22M parameters and 4.3G operations for DeiT-S, whose top-1 result is 79.8, and 27M parameters and 5.4G operations for ConViT-S, whose result is 81.3. The accuracy gap in the small pair thus accompanies a difference in size and operations. The small plus pair supplies the complementary comparison at equal counts.

Top-5 accuracy tells a similar story in the matched pairs. In the tiny plus comparison, DeiT-Ti+ scores 93.2 and ConViT-Ti+ scores 93.6. The scores for the small plus pair are 94.4 and 95.9, respectively, while those for the base plus pair are 93.5 and 95.9. ConViT-S+ and ConViT-B+ therefore have the same reported top-5 accuracy while differing on top-1. The top-1 ordering and top-5 coverage answer related questions about predictions, and the paper reports both.

#### Throughput is a separate comparison

Equal operation counts give a different view from measured throughput. The speed measurements are images processed per second at batch size 128 on a Nvidia Quadro GP100 GPU. In each same-size plus pair, ConViT processes fewer images per second than DeiT. For example, the small plus pair is listed at 382 for ConViT-S+ and 480 for DeiT-S+. In the original tiny pair, the corresponding rates are 734 for ConViT-Ti and 1442 for DeiT-Ti. The additional positional computations have an observed runtime cost in this implementation even where the tabulated counts are equal.

A practitioner can also compare variants across sizes. ConViT-S+ achieves 82.2% top-1 accuracy against 81.8% for the original DeiT-B, uses 48M parameters against 86M, and processes 382 images per second against 187 in the paper's benchmark. This supports the practical case for the smaller ConViT at that point in the comparison. The benchmark concerns batched classification on the stated device. Its throughput is a property of the architecture as implemented and measured under those conditions.

The paper places its accuracy and parameter results alongside earlier convolutional and transformer classifiers. That plot offers a broader view of where ConViT fits, using performance figures from the respective publications. The within-paper pairs remain the more direct architectural comparisons because their sizes and training choices are documented together. The wider comparison is evidence that ConViT is competitive in the reported accuracy and size range. The matched pairs show what happens when more of the experimental setup is held constant.

#### Learning from fewer distinct images

The sample-efficiency experiment reduces the available training images within every class of ImageNet-1k. The row labeled 5%, for example, means that training retains that fraction of each class. It leaves the classification task in place while reducing the number of distinct examples available for learning. To hold the amount of image exposure constant, the authors increase the number of training epochs in inverse proportion to the fraction retained. The smaller training pools are therefore revisited more often. The experiment asks how accurately the systems can classify from less varied training material at comparable exposure.

```
epoch multiplier = 1/f
```

Here f is the retained fraction of training images in each class, and the epoch multiplier is the factor applied to the training duration measured in epochs. The numerator 1 gives the reciprocal of f. The paper specifies f as one of 0.05, 0.1, 0.3, 0.5 or 1. The adjustment keeps the total presentation count constant across subset sizes under the described procedure.

DeiT-S and ConViT-S test top-1 accuracy by ImageNet-1k training fraction ConViT-S leads at every training fraction, with the largest separation at the smallest fraction.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| DeiT-S with 5% of training data | 34.8 |
| ConViT-S with 5% of training data (this paper) | 47.8 |
| DeiT-S with 10% of training data | 48.0 |
| ConViT-S with 10% of training data | 59.6 |
| DeiT-S with 30% of training data | 66.1 |
| ConViT-S with 30% of training data | 73.7 |
| DeiT-S with 50% of training data | 74.6 |
| ConViT-S with 50% of training data | 78.2 |
| DeiT-S with 100% of training data | 79.9 |
| ConViT-S with 100% of training data | 81.4 |

The reported top-5 scores corroborate the top-1 pattern. With 5% of training data, DeiT-S reaches 57.8 and ConViT-S reaches 70.7. With 10%, the corresponding top-5 accuracies are 71.5 and 80.3. The full-training row records 95.0 and 95.8. The classification task remains harder for both systems as training images are taken away. The difference is that ConViT retains more test accuracy at each fraction, and the paper reports its strongest relative advantage at the smallest fraction.

The paper's table and accompanying prose give different values for the 10% top-1 comparison. The prose gives 59.5% for ConViT and 46.5% for DeiT, while the table gives the values in the chart. The chart follows the table so the plotted series belongs to one reported comparison across all fractions. The direction of the finding is the same in both reports. Similarly, the full-training row belongs to the sub-sampling series and has its own values, distinct from the small variants' headline comparison.

The authors also compare their low-data result with a previously reported top-1 accuracy of 56.4% from a search over convolutional classifiers. They present this as perspective on the competitiveness of ConViT when data is limited. The sub-sampling series answers the more specific question about DeiT and ConViT under the paper's shared procedure. It shows that the difference is most pronounced where the training pool has the least variety, even though the same total number of examples is presented over training.

#### Distillation and a second classification dataset

The supplementary distillation experiment uses a RegNet-16GF teacher and runs for 300 epochs on ImageNet. Hard distillation provides training targets from the teacher's class predictions. With this procedure, the top-1 accuracy of ConViT-S+ goes from 82.2 to 82.9, and DeiT-B goes from 81.8 to 83.0. DeiT-S goes from 79.8 to 80.9. The distilled ConViT-S+ and DeiT-B end up close in accuracy at their reported sizes of 48M and 86M parameters, respectively. The experiment shows that the gain from direct spatial initialization can coexist with a gain from the teacher. [Designing Network Design Spaces](https://md.research.elamur.ai/free/en/papers/radosavovic-2020-designing-network-design-spaces/)

Distillation entails running the teacher during training. ConViT's teacher-free result incurs no such forward pass. The authors interpret the smaller benefit of the teacher for ConViT as consistent with some overlap between what a convolutional teacher transfers and what the gated architecture already supplies. The fact that ConViT improves with the teacher leaves room for additional guidance. These comparisons report the joint effects of an architectural prior and teacher supervision under the specific distillation procedure.

The supplementary CIFAR100 experiment resizes images to 224 × 224, extends training and adapts the learning-rate schedule accordingly. The learning curves cover 3000 epochs, and the authors describe signs of overfitting after 1000 epochs. They report 82.1% top-1 accuracy for a ConViT with 10M parameters. This experiment extends the classification comparison to another dataset and also gives a direct example of the distinction between strong performance and complete protection from overfitting. Its long schedule and resizing are part of the stated evaluation setup.

### What the ablations show

#### Separate the gate from the initial spatial pattern

The main ablation uses ConViT-S+ and evaluates ImageNet training with the full set and with 10% of the training data. The authors vary three decisions in the early attention blocks. They give the heads either their convolution-like positional settings or an alternative initialization. They either train the gate or hold it fixed. They also compare trainable early attention with frozen early attention and with ordinary DeiT attention. These changes address different explanations for the gain, so the conditions are easiest to read by asking what each removed component does to the computation.

When the paper describes the gate as removed in the trainable-attention comparisons, it fixes λ at 0. The resulting mixture gives the two separately normalized branches equal weight. Both branches still operate, and their underlying weights can still be trained. The change specifically removes a head's ability to learn the overall share assigned to position. This differs from conventional PSA, in which position and content contribute scores to the same softmax. It also differs from the test-time interventions in which a branch is assigned a weight of zero.

ConViT-S+ ablations on ImageNet test top-1 accuracy with 10% training data Learned gates and convolution-like initialization together give the highest accuracy.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| DeiT with ordinary attention | 47.8 |
| GPSA with fixed gates and no convolutional initialization | 54.6 |
| GPSA with learned gates and no convolutional initialization | 56.9 |
| GPSA with fixed gates and convolutional initialization | 57.4 |
| GPSA with learned gates and convolutional initialization (this paper) | 59.7 |
| Frozen GPSA with convolutional initialization | 54.3 |
| Frozen GPSA with no convolutional initialization | 44.8 |

With 10% of training data, trainable GPSA with a fixed equal mixture and without convolutional initialization reaches 54.6 top-1, compared with 47.8 for the ordinary DeiT ablation baseline. This comparison indicates that changing the attention operation already helps in the reported low-data setting. Keeping the initialization unstructured and training the gate gives 56.9. Keeping the gate fixed and providing the convolution-like initialization gives 57.4. Using both gives 59.7. The best setting combines a useful starting map with the ability to change how much the head relies on the spatial branch.

With the full ImageNet training set, the same comparisons give 79.1 for DeiT and 81.6 for trainable GPSA with neither a trainable gate nor the convolution-like initialization. With the initialization and fixed gates, accuracy is 82.0. With learned gates and without the initialization, it is 81.4. The complete configuration reaches 82.2. Most of the observed improvement over ordinary attention in this full-data ablation is present in the version with a fixed mixture and without the spatial initialization. The separate contributions are clearer in the run with fewer training images. In particular, the effect of training the gate depends on how the positional branch is initialized and on how much training data is available.

The frozen tests look at what the starting computation supplies when the early attention parameters cannot improve. The feed-forward networks in the first 10 blocks can still train, and the later classifier retains trainable processing. On the full training set, the convolutionally initialized frozen condition reaches 78.6 top-1, close to the ordinary DeiT ablation at 79.1. Frozen attention without the convolutional initialization reaches 73.7. With 10% of the data, the convolutionally initialized frozen condition reaches 54.3, which exceeds the DeiT baseline's 47.8. The frozen condition without that initialization records 44.8.

These frozen results are most informative as a comparison of initial operations. If the fixed attention gathers information from useful neighborhoods, later trainable calculations can do more with the resulting features than when fixed attention lacks that organization. The full trainable ConViT is stronger than either frozen condition. And the trainable computations retained around the frozen layers still have substantial capacity. The ablation isolates the usefulness of a structured fixed spatial operation in this architecture, leaving the broader question of how much attention image transformers require open.

#### Vary the strength, depth and form of the spatial preference

The paper also varies the initial concentration of positional attention and the number of early blocks that use GPSA. These experiments train on the first 100 classes of ImageNet. Increasing the concentration around assigned offsets and replacing more early attention layers with GPSA both improve final test accuracy over the tested settings. The learning curves show an especially large benefit early in training. The authors single out the contrast at 20 epochs when using 9 GPSA layers. The result concerns progress in training epochs. An epoch with GPSA can have a different processing cost from an epoch with ordinary attention, as the throughput comparisons suggest.

Examining the effect over time helps distinguish two ways an initialization can matter. A good starting operation can extract useful features before content-based interactions have been learned. A high final accuracy additionally requires the training procedure to refine the computation. In the restricted-class experiments, more strongly structured early attention helps during the part of learning when the ordinary baseline is still establishing useful interactions. The controlled comparisons with weaker and shallower versions of GPSA show that the amount of initial structure makes a difference within the tested architectures.

A supplementary experiment separates early progress and final performance more sharply. It replaces GPSA in ConViT-B with conventional positional self-attention and trains on ImageNet for 300 epochs alongside DeiT-B. The convolution-like initialization gives that version an early lead. Over later training, the ordinary DeiT catches up and finishes ahead. The authors attribute this to the continuing dominance of position in the conventional PSA version, based on their inspection of its attention maps. The result motivates the specific gate design. Giving content its own normalized distribution preserves an explicit way to increase its contribution, even when the positional distribution starts sharply peaked.

#### Measure where attention actually goes

A gate can reveal the share assigned to the position branch, but that share alone cannot tell how far attention travels. A positional map can broaden, and content-based attention can favor nearby sources. The authors therefore define a separate nonlocality measure. For each query, it weights the distance to every source patch by the attention assigned to that source, then averages over query positions. A large value means the head assigns more weight to distant locations on average.

```
Dₗₒ꜀ˡ,ʰ = (1/L) ∑ᵢ ∑ⱼ Aᵢⱼˡ,ʰ ‖δᵢⱼ‖
```

Dₗₒ꜀ˡ,ʰ is the nonlocality of head h in layer l, written as a superscript ˡ to identify the layer. L is the number of query patches. Index i runs over those queries, and j runs over the source patches. Aᵢⱼˡ,ʰ is the attention weight from query i to source j in that layer and head. The quantity ‖δᵢⱼ‖ is the Euclidean distance between the patch positions. Unlike the squared distance in the positional encoding, this measure uses the distance itself. The factor 1/L averages the weighted distances across queries.

```
Dₗₒ꜀ˡ = (1/Nₕ) ∑ₕ Dₗₒ꜀ˡ,ʰ
```

Dₗₒ꜀ˡ is the whole layer's nonlocality, Nₕ is the number of heads, and the sum runs over the head-specific nonlocalities Dₗₒ꜀ˡ,ʰ in layer l. The analysis can consequently follow individual heads or summarize a full layer. The paper's main nonlocality curves average the measurements over 1024 images and follow DeiT-S and ConViT-S through 300 epochs of ImageNet training.

In DeiT-S, nonlocality falls early across the 12 layers. In the later part of training, lower layers remain relatively local and upper layers assign more weight to distant patches. The initially unstructured attention thus develops an early preference for neighboring image locations through learning. Averaged visualizations over 100 images support this interpretation. The lower-layer maps concentrate on the query and surrounding patches after training, while the paper describes much longer-range interactions in the tenth layer. The distance measure shows a property of the maps that emerges over training even without an explicit displacement term in the attention rule.

ConViT-S begins with greater locality in its gated layers. Its nonlocality rises as training proceeds, while the authors report that the resulting attention retains more locality than DeiT. Its depth pattern also differs from DeiT's. The first layer and the later gated layers move substantially away from their starting degree of locality, while some middle layers stay much more local. The second layer is a particularly clear example. An architecture containing the same kind of GPSA operation throughout its early blocks thus learns different spatial patterns at different depths.

The gate trajectories supply another view of this change. In the ConViT-S plots, the average positional weight declines during training in all gated layers. Some heads retain appreciable positional weight in layers 1–5, while the position branch is used very little in layers 6–10 at the end of training. ConViT-Ti retains positional use in its first 4 layers and ConViT-B in its first 6. The authors suggest that the larger architecture may benefit from keeping the initial prior available at greater depth. Model scale, width and the number of heads vary across these comparisons, so the trajectories describe the variants as trained.

Selected maps illustrate what the averages leave out. In the second layer of the tiny ConViT, the first two displayed heads emphasize content, while the third and fourth rely more strongly on position. Among those positional heads, one keeps a tighter map and the other attends over a broader area. The gated attention shown at layer 10 looks more like the content-based attention of DeiT. The maps help interpret the separation between position weight and concentration. Heads with substantial positional weight can still differ in how widely they gather information.

Distillation changes the DeiT trajectories as well. In the comparison with a convolutional RegNet teacher, nonlocality still drops during early training but rebounds less by the end. The authors interpret this as evidence that the student's attention reflects some of the teacher's locality. This observation helps explain their comparison of the two ways to supply a spatial preference. The student trained with a teacher arrives at a more local configuration. ConViT begins with organized local heads and learns to vary the extent to which it uses them.

#### Mask trained components at test time

The authors also intervene after training. In the first test, they remove the absolute position embeddings at inference. ImageNet accuracy for DeiT-Ti falls from 72.2 to 38.3, while ConViT-Ti goes from 73.1 to 67.1. Both variants were trained with the embeddings. ConViT has a second source of spatial information because the relative encodings remain available in its GPSA layers. The different responses show that the trained ConViT depends less on the absolute embeddings in this test.

A second test forces the GPSA mixture to use only position or only content in various sets of gated layers. Setting the positional mixture weight to 1 switches off content attention. Setting it to 0 switches off the positional branch. With 3 layers masked, ConViT-Ti's ImageNet accuracy is 62.3 when content is suppressed and 63.5 when position is suppressed. The unmasked score is 73.1. The relatively similar effects are consistent with both branches supporting useful computations early in the architecture.

As the intervention covers more layers, the gap grows. With 5 layers masked, accuracy is 35.0 when content is removed and 53.1 when position is removed. With 10 layers masked, the figures are 1.3 and 46.8, respectively. These are test-time interventions on the same trained classifier. They disturb the computations the heads and later blocks had adapted to during training. Taken together with the learned gates, they show why access to content matters so much for the trained classifier, even though a position-based organization was valuable at the start.

### Limitations

#### Limits the authors identify

The authors distinguish the sample-efficiency gains from the throughput cost of positional attention. ConViT can reach higher accuracy with fewer parameters than a larger DeiT, while a matched ConViT can process images more slowly than its DeiT counterpart. Their speed measurements refer to a specific GPU and batch size. The efficiency improvement supported by the sub-sampling experiment concerns the diversity of training examples required to reach a given level of accuracy. The paper offers separate evidence for speed and accuracy under its hardware benchmark.

The paper also reports signs of overfitting in its long CIFAR100 runs. A convolution-like prior helps organize the starting computation, but extensive training still produces the warning signs the authors note. Similarly, they present initialization from pretrained convolutions as a question for future work. The experiments establish how a prescribed convolution-like configuration can help when imposed at initialization. Whether learned convolutional features can reduce the amount of training data further remains an open question in the paper.

The authors describe a smaller dependence on absolute position embeddings and suggest that future configurations could remove them. The reported experiment masks them at test time after training with them present. The resulting drop quantifies the dependency of the trained classifier under that intervention. Accuracy when training from the beginning without absolute embeddings is a separate question. The same distinction applies to branch masking. Removing a branch from a trained system tests its contribution to the learned computation, while training a system with that branch absent could let the remaining components adapt.

#### What the experimental setup leaves open

The main sub-sampling study retains a fraction of images from each ImageNet-1k class and revisits the retained images more often. This tests sample efficiency under the same class definitions and a controlled presentation budget. It leaves open how ConViT would compare when training examples are sparse for only particular classes, when the training and evaluation distributions differ, or when training is held fixed in elapsed time. Similarly, the restricted-class hyper-parameter study measures how strength and depth affect the classifier in that particular subset. The best concentration and placement can depend on the data and the training regime.

The comparison with the original DeiT recipes and the comparison with matched-head DeiTs support different claims. In the original small comparison, ConViT is wider and larger, alongside its higher accuracy. The plus comparison controls those architectural quantities while using the paper's adjusted learning rate and batch size. The weaker accuracy of DeiT-B+ relative to DeiT-S+ is a reason to read that specific large-variant margin in light of the shared training recipe. The paper reports individual scores and learning curves for these comparisons, so the reported values describe the runs shown rather than an estimate of their variation across repeated training.

The locality measurements characterize where attention weights fall. The gate gives the share assigned to each branch, and the distance metric reduces a spatial distribution to an average. Heads can have the same average distance while favoring different offsets or distributing their weight differently. A map can show which patches received weight for a given query, while learned value projections, output projections, residual connections and later blocks also shape the classification. The combination of maps, gate trajectories and interventions supports claims about routing information through attention. A complete causal account of particular class predictions remains outside what these measurements establish. [Interpretability](https://md.research.elamur.ai/free/en/topics/interpretability/)

Finally, the paper evaluates image classification. Its discussion of stronger inductive biases helping when data is scarce offers a rationale for the experiments, and its comparisons show benefits across the settings tested. The suggestion that learnable priors can preserve a higher performance ceiling is broader than the benchmark. The ImageNet results measure finite training runs under specified recipes. They leave open the behavior of the same architecture at much larger data scales or in vision tasks that require different kinds of outputs.

### What came after

[How to train your ViT?](https://md.research.elamur.ai/free/en/papers/andreas-2021-how-train-your-vit-data/) cites ConViT in work concerned with data, augmentation and regularization for vision transformers. Its subject puts the training protocol alongside architecture as a determinant of performance. ConViT's corresponding evidence comes from holding the original DeiT recipe fixed in one comparison and matching architectural size in another, then reducing the pool of training images by class. The citation connects those concerns. A specific adoption of gated positional self-attention is undocumented in the citation relationship.

[Towards Robust Vision Transformer](https://md.research.elamur.ai/free/en/papers/mao-2022-robust-vision-transformer/) cites ConViT in work focused on robustness. This raises a different evaluation question from the one ConViT answers with its limited-data experiments. A classifier trained with fewer distinct images can be measured on the same classification benchmark, as in ConViT, while robustness depends on the conditions under which predictions are challenged. The citation establishes the connection between the papers. It leaves the later paper's use of ConViT's heads, initialization and gate unspecified.

[MobileOne](https://md.research.elamur.ai/free/en/papers/vasu-2023-mobileone-improved-one-millisecond-mobile/) cites ConViT in work on a mobile backbone. Its stated focus brings execution speed into a discussion that ConViT approaches through both operation counts and measured throughput. ConViT's closely matched comparisons show how architectures with the same reported operation count can have different measured speeds. MobileOne's citation places ConViT in the context of efficient backbone design. It does not establish that MobileOne uses ConViT's gated attention or its convolution-like initialization.

## Cite

Cite as Stéphane d’Ascoli, Hugo Touvron, Matthew L. Leavitt, Ari S. Morcos, Giulio Biroli and Levent Sagun. 2022. ConViT: improving vision transformers with soft convolutional inductive biases*. Journal of Statistical Mechanics Theory and Experiment.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.1088/1742-5468/ac9830](https://doi.org/10.1088/1742-5468/ac9830) · [arXiv 2103.10697](https://arxiv.org/abs/2103.10697)

```bibtex
@article{dascoli2022convit,
  title = {{ConViT: improving vision transformers with soft convolutional inductive biases*}},
  author = {Stéphane d’Ascoli, Hugo Touvron, Matthew L. Leavitt, Ari S. Morcos, Giulio Biroli and Levent Sagun},
  journal = {Journal of Statistical Mechanics Theory and Experiment},
  year = {2022},
  doi = {10.1088/1742-5468/ac9830},
  eprint = {2103.10697},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1088/1742-5468/ac9830}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
