What Is a Vision Transformer (ViT), and How Does It Differ from CNN-Based Detectors?
A Vision Transformer (ViT) is a standard transformer encoder applied to an image that has been cut into fixed-size patches, with each patch treated the way a language model treats a word token. Because every patch can attend to every other patch in every layer, the model can draw on the whole image from its first layer, while a CNN detector’s convolutions process local regions. The vision transformer architecture replaces the bias towards local processing that convolution builds in with global attention. That trade has a price: a ViT needs far more training data or strong pretraining to match a CNN, and its attention cost grows quadratically with the number of patches, so it also grows with input resolution.
Vision Transformer Architecture, Component by Component
The original design, from Dosovitskiy et al. (ICLR 2021), adds almost no image-specific machinery: apart from the first patch-extraction step, an image is handled as a sequence of patches by a standard transformer encoder of the kind used in NLP.
Patch embedding. The image is split into N patches. Each patch is flattened and multiplied by a trainable matrix that projects it to the model dimension d, which gives n embedded patches. With patch resolution P, the patch count is N = HW/P², and that number is also the sequence length the transformer works on. In practice this “patchify stem” is implemented as a convolution with a 16 × 16 kernel and a stride of 16.
Position embeddings. A transformer block does not care what order the patch embeddings arrive in, so it has no built-in sense of where a patch sits in the image. Positional information is added as fixed or trainable embeddings, summed with the patch tokens before the first block.
Class token. A trainable vector is added to the patch sequence before the first layer. It passes through every transformer layer and is then projected by a linear layer to predict the class. Supervision reaches the model only through that token, so self-attention has to spread information between the patch tokens and the class token.
Encoder blocks. Each block pairs a multi-head self-attention module, which models relationships between patches, with an MLP that projects each patch separately. Normalisation and residual connections wrap both modules. Multi-head attention runs several self-attention operations (“heads”) in parallel and projects their concatenated outputs.
Model names encode the patch size: ViT-L/16 is the Large variant with 16 × 16 patches. Sequence length is inversely proportional to the square of the patch size, so smaller patches cost more compute. For scale, a survey of efficient ViTs lists ViT-B/16 at 86.6 million parameters, 17.6 GFLOPs at 32-bit precision and a 330 MB model.
Worked Example: One 224 × 224 Image Through ViT-B/16
The steps below follow from the definitions above. Treat the arithmetic as an illustration of how the mechanism scales, not as a measured result.
- Split the image into 16 × 16 patches. 224 / 16 = 14, which gives a 14 × 14 grid of 196 patches (N = 224 × 224 / 16²).
- Flatten each patch. A 16 × 16 RGB patch holds 16 × 16 × 3 = 768 values.
- Project each flattened patch to the model dimension and add its position embedding.
- Add the class token to get 197 tokens in total.
- In every attention head of every layer, compute a score for each pair of tokens: 197 × 197 = 38,809 scores.
- Double the input to 448 × 448 and the grid becomes 28 × 28 = 784 patches, or 785 tokens with the class token. That is 785 × 785 = 616,225 scores per head per layer, roughly 16 times as many for four times the pixels.
This last step is the resolution problem in miniature, and the latency section below returns to it.
How Is a Vision Transformer Different from a Regular Transformer?
The building block is the same transformer encoder. The original Transformer, from Vaswani et al. (2017), uses attention alone and drops recurrence and convolution entirely. ViT keeps that encoder and changes what goes into it: the image is broken into patches, the patches become vectors, and those vectors are treated like token embeddings. An encoder processes its whole input at once, so every token attends to every other token and no causal masking is needed. In vision, that means the left side of an image can attend to the right side, and the reverse, in every layer. If you need a refresher on the encoder itself, our explainer on what transformers are in deep learning covers attention and encoder structure outside the image domain.
How Does Patch Embedding and Self-Attention Actually Process an Image, Compared with Convolution and Pooling?
A convolutional layer slides a fixed-size filter over each local region of the input, and its cost grows linearly with the pixel count, O(HW). Locality, two-dimensional neighbourhood structure and translation equivariance are built into every layer of a CNN. In a ViT, only the MLP layers are local and translation-equivariant, and the self-attention layers are global. Pooling then shrinks the feature map stage by stage, so a CNN’s receptive field widens with depth and global context only shows up in the later layers.
Self-attention reverses that order. It relates each token to all the others, which gives global information extraction and goes beyond the fixed receptive field of a convolution. The original ViT paper measured how far attention reaches, a figure analogous to receptive field size in a CNN. In lower layers some heads attend across most of the image while others stay near the query location, and in the second half of the network most heads attend widely. A representation analysis by Raghu et al. (2021) attributes the differences between ViTs and CNNs to self-attention, which aggregates global information early, and to residual connections that carry features strongly from lower to higher layers. One more contrast matters for inspection images. Gu’s 2023 thesis found ViT’s vulnerability to patch attacks insensitive to where the patch sits, while ResNet was most vulnerable at the image centre, because central pixels feed more neurons in a CNN.
The practical consequence is that a CNN starts with a strong prior about how images work, and a ViT has to learn that prior from data. Everything in the next three sections follows from that.
How Much Labelled Data Does a ViT Need Relative to a CNN Backbone for an Industrial Inspection Task?
With fewer built-in inductive biases, a ViT needs more training data or strong pretraining to match a CNN.
- The original ViT paper concludes that “large scale training trumps inductive bias” once models are trained on datasets of 14M to 300M images.
- DeiT (Touvron et al.) reports that the original results came from a private 300-million-image dataset, and that the ViT authors concluded transformers “do not generalize well when trained on insufficient amounts of data”. DeiT got competitive results from ImageNet alone, about 1.28 million images, but only with extensive data augmentation and distillation from a CNN teacher.
- Xiao et al. (2021) found that a plain ViT trained only on ImageNet-1k underperformed RegNetY across the model-size range and also trailed ResNets.
- CoAtNet (2021) argues that transformers can generalise worse than convolutional networks because they lack the right inductive bias.
- On a small integrated-circuit defect dataset, the IH-ViT study (2023) measured 69.71% accuracy for ResNet50 against 66.45% for a plain ViT.
The DefT authors put the industrial consequence plainly: learning local structure implicitly takes large datasets and long training, which runs against industrial imaging applications with limited samples. We read this as a rule for planning, not a fixed threshold. With a small labelled defect set, a ViT trained from scratch is the wrong starting point. The fair comparison is a fine-tuned pretrained ViT (or a hybrid) against a fine-tuned pretrained CNN, both scored on validation data that looks like the production line.
What Are the Latency and Memory Implications of ViT Attention at Production Input Resolutions?
Global attention costs O(n²) in time and memory, where n is the number of patches, because it computes a score for every pair of patches. In the worked example, doubling the input side length quadruples the patch count and multiplies the attention scores by about 16. The Swin authors make the same point: for high-resolution images and dense prediction, quadratic attention becomes intractable. The QT-ViT authors (NeurIPS 2024) name this growth as the factor that limits ViT in real-world applications.
A study of 190 real-world ViTs and 102 CNNs on mobile devices found:
- At comparable FLOPs, ViTs consistently took longer to run. A ViT at 5.00 GFLOPs had 1.75 times the latency of a CNN at 4.95 GFLOPs.
- ViTs have lower arithmetic intensity than CNNs, so they are more likely to be memory-bound.
- Intermediate-tensor memory for ViT-S was 14% higher than for ResNet-18 at 224 × 224 and 43% higher at 512 × 512.
- The DETR-ResNet101 detector used 5.0 GB of mobile memory for a single 512 × 1333 image.
- Most real-world ViTs could not run on mobile GPUs at all, because ML frameworks lacked support for their operations.
Outside mobile devices the picture is less clear-cut, and the sources disagree. The original ViT paper reports that the theoretical quadratic scaling barely starts to show, and only for the largest models at the largest resolutions, and that large ViTs are more memory-efficient than ResNets. Xiao et al. found that runtime tracks activations (r = 0.93) far better than FLOPs (r = 0.75), and that ViTs are fast relative to their FLOPs while EfficientNets are slow. Xiao et al. ran their ViTs at 224 × 224 resolution on ImageNet. For an inspection line running high-resolution frames on edge hardware, we give more weight to the mobile measurements and to the detection results below, because their conditions are closer to that deployment. On a server GPU at modest resolution, plain ViT cost may be acceptable, but that has to be measured rather than assumed. Choosing models for constrained devices is covered separately in our guide to lightweight vision models.
Do ViTs Fix the Lighting Variation, Occlusion and Shifted Class Distributions That Break CNN Detectors?
No: ViT is not always more robust than a CNN. Gu’s thesis found that ViTs are more robust than ResNet when individual patches are naturally corrupted, because attention can ignore them. The same attention mechanism makes ViTs more vulnerable to adversarial patches, since it can be pulled towards the perturbed region.
The IH-ViT authors note that ViT pretraining sets such as ImageNet have uniform image sizes and information density balanced across the whole image. In surface-defect segmentation, the DefT paper found that pure transformer methods (SETR, Swin-Unet) handled complex backgrounds better than UNet but still missed some defect regions and produced unclear boundaries. Off-the-shelf models that work in demos fail in production at the edge cases, lighting conditions and throughput requirements of real deployments. A ViT picked for benchmark headroom carries those risks, plus the data-hunger risk from the section above.
What Do Swin Backbones, DETR-Style Detectors and Hybrid Designs Change in Practice?
ConvNeXt (Liu et al., 2022) notes that a vanilla ViT struggles with object detection and segmentation, and that hierarchical transformers such as Swin, which bring back several ConvNet priors, made transformers practical as general vision backbones.
Swin: Windowed Attention with Linear Cost
Swin computes self-attention only within non-overlapping local windows. Each window holds a fixed number of patches, so cost grows linearly with image size instead of quadratically. In the paper’s terms, global attention is quadratic in the patch count hw, while window attention is linear when the window size M is fixed (7 by default). To keep information flowing between windows, Swin shifts the window partition in alternating blocks, and it merges patches across stages to build a hierarchical feature pyramid. It also uses a relative position bias in place of ViT’s absolute embeddings. The authors found that absolute position embedding helped classification slightly but hurt detection and segmentation, and concluded that an inductive bias towards translation invariance is still preferable for dense prediction. As a detection backbone, Swin-T gave +3.4 to 4.2 box AP over ResNet-50, at slightly higher model size, FLOPs and latency.
DETR-Style Detectors
DETR (Carion et al., 2020) treats detection as direct set prediction. A transformer encoder-decoder and a bipartite-matching loss replace non-maximum suppression and anchor generation. The original design converged slowly and had limited feature spatial resolution. Deformable DETR attends only to a small set of sampling points around a reference, and the authors report better results, especially on small objects, with ten times fewer training epochs. RT-DETR (2023) reports 53.1% AP on COCO at 108 FPS on a T4 GPU for its R50 variant. ViDT (2021) builds a detector directly on Swin with linear-complexity attention. It reports AP comparable to YOLOS, a detector built on plain ViT, at much higher FPS, because YOLOS keeps quadratic global attention. ViTDet (Li et al., 2022) shows that a plain ViT backbone can work for detection if it uses window attention plus a few cross-window propagation blocks. With MAE pretraining, it reaches 61.3 AP box on COCO using only ImageNet-1K pretraining. Choosing between DETR-style and YOLO-family detectors for a given job is a separate decision, covered in our object detection models guide.
Hybrid CNN-Transformer Designs
The original ViT paper already described a hybrid, in which patches are taken from a CNN feature map instead of raw pixels. Hugging Face’s ViT Hybrid implementation, for example, uses BiT convolutional features as the initial tokens. In that paper, hybrids slightly outperformed plain ViT at small compute budgets, and the gap vanished for larger models. Later work went further. Replacing the patchify stem with a few stacked stride-two 3 × 3 convolutions made training more stable and raised ImageNet-1k top-1 accuracy by about 1-2% at the same FLOPs and runtime. CvT adds convolutional token embedding and projection to bring shift, scale and distortion invariance into ViT. On one IC-defect classification dataset, the IH-ViT hybrid, which fuses ResNet50 and ViT features, reached 72.51% against 69.71% for ResNet50 and 66.45% for ViT. DefT reports a better speed-accuracy trade-off for surface defects with fewer or similar parameters.
Hybrids do not settle the argument in the transformer’s favour, though. ConvNeXt’s authors point out that hybrid success is credited to the superiority of transformers rather than to convolution’s inductive biases.
When Is a Vision Transformer the Right Choice for a Defect-Detection or Inspection Deployment, and When Is a CNN Detector Still Better?
The deciding factors are data volume, input resolution and deployment budget, not which architecture is fashionable. The table sums up the evidence above as a starting position, to be confirmed on your own validation data.
| Situation | Starting position | Why |
|---|---|---|
| Small labelled defect set, training from scratch | CNN | ViT needs large-scale data to make up for weak inductive bias. |
| Small labelled set, strong pretrained weights available | Benchmark a fine-tuned CNN against a fine-tuned hybrid | On one small IC-defect dataset, the IH-ViT hybrid beat both ResNet50 and plain ViT. |
| Defects that depend on long-range context (cluttered backgrounds, pseudo-defects) | Hybrid or hierarchical transformer | CNN locality limits long-range modelling; pure transformers lose local detail. |
| High-resolution frames at fixed latency | Windowed (Swin-style) or CNN; avoid plain global attention | Global attention cost is quadratic in patch count; window attention is linear. |
| Edge or mobile deployment | CNN or an efficient hybrid, measured on the target device | On mobile, ViTs showed higher latency than CNNs at comparable FLOPs and more memory at comparable model size. |
| Large data, server GPUs, classification at modest resolution | ViT is a reasonable candidate | Pretrained at JFT-300M scale, ViT reached ResNet-level results with 2-4× less compute. |
We would add one discipline whichever row applies: write down the chosen backbone’s data requirement, its latency and memory at the deployment resolution, and its expected false-positive and miss rates on production-representative images before committing training spend.
The broader set of production CV failure modes is where the architecture decision has to be checked. TechnoLynx’s computer vision R&D work can carry out backbone selection and validation for inspection deployments like these.
FAQ
What Are Vision Transformers Used For?
ViT was introduced for image classification, where it matched or beat convolutional networks when pretrained on large datasets. Hierarchical variants such as Swin extended transformers to object detection and semantic segmentation, and hybrid designs have been applied to surface and IC defect detection.