Fine-Tuned Vision Transformer

Machine Learning
Introduced by
Dosovitskiy, A. et al. (Google Brain)
Year
2020-2021
Type
Transfer learning / fine-tuning of attention-based image model
Family
Deep learning / NLP / CV

What does it do?

Fine-Tuned Vision Transformer adapts a pre-trained ViT, a model that splits an image into fixed-size patches and processes them with self-attention layers, to a new image classification or recognition task.

The labeled dataset for the new task is usually much smaller than the corpus used for pre-training, so the model starts from features already learned from many images. Only the output layer is new, and the encoder is adjusted to the target data.

The intuition behind the method

A ViT pre-trained on a large corpus such as ImageNet-21k or JFT-300M has already learned general visual features such as edges, textures and object parts. Fine-tuning keeps these features and continues training on your labeled images, so the model learns mainly what distinguishes your classes, for example lesion types in medical scans or land-cover classes in satellite tiles. Training the same architecture from random initialization on a small dataset generally struggles to reach comparable accuracy, because all features must then be learned from that small set. How much the pre-trained features help depends on how close the source and target image domains are.

History

Vision Transformer was introduced by Dosovitskiy et al. at Google Brain in 2020 and published at ICLR 2021. The paper reported that a standard transformer applied to sequences of image patches could match or exceed CNN accuracy when pre-trained on large image datasets. Fine-tuning these pre-trained ViTs on downstream tasks became a common pattern in computer vision. Later work on scaling ViT models (Zhai et al., 2022) extended this line of study, and follow-up models such as DeiT, Swin Transformer, BEiT and MAE are often used as starting points.

When to use it

Choose this method for an image classification or recognition problem with a labeled target dataset of moderate size, when a pre-trained ViT checkpoint exists whose training domain is reasonably close to your images (for example ImageNet-pretrained checkpoints for natural photographs, or domain-specific checkpoints where available). Typical fits include medical imaging, remote sensing, fine-grained species or product recognition, and document image analysis. Do not choose it when the labeled set is very small relative to the number of classes, because the new head and the large encoder will overfit; linear probing of frozen features or a CNN baseline is easier to justify in that case. It is also a poor fit when the target images differ radically from the pre-training data and no domain-matched checkpoint exists, or when the deployment device cannot hold the weights of a base-sized ViT, since these weights are large for edge hardware. If per-region feature attribution is the main requirement, plan for dedicated post-hoc explanation methods rather than relying on attention maps.

Limitations and considerations

  • High memory and compute requirements: fine-tuning base-sized ViT models needs substantial GPU memory, and the largest variants such as ViT-L/16 or ViT-H/14 can require multi-GPU setups.
  • The benefit of pre-training depends on domain match: when source images differ strongly from the target (for example natural photographs versus X-rays), the transferred features help less and more of the encoder must be retrained.
  • With few labeled examples per class, the encoder can overfit, and results depend strongly on regularization and augmentation.
  • Self-attention cost grows quadratically with the number of patch tokens, so high-resolution inputs, which produce many patches, become expensive unless windowed or hierarchical variants such as Swin are used.
  • Hyperparameter sensitivity: the learning rate schedule, layer-wise learning rate decay and augmentation choices can change final accuracy noticeably.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Strong accuracy on image classification when the pre-trained checkpoint matches the target domain, which is the main reason to start from a pre-trained ViT rather than random initialization.
  • The pre-trained encoder reduces how much labeled data is needed compared with training a transformer from random initialization.
  • Self-attention over all patch tokens lets every layer relate distant image regions, whereas local convolutional filters capture such relations only through depth.
  • Public checkpoints exist in several families (ViT-B, ViT-L, ViT-H, DeiT, Swin), with different trade-offs between accuracy, size and compute.
  • Attention maps can be inspected to see which patches influenced a prediction, which helps error diagnosis even though they are not a formal explanation.
  • The same pre-trained backbone can be reused with task-specific heads or decoders for tasks such as object detection and semantic segmentation.

Applications

  • Medical image classification (histopathology, radiology, dermatology).
  • Remote sensing and satellite image scene classification.
  • Fine-grained visual recognition (bird species, car models, plant disease).
  • Document image understanding (form classification, chart recognition).
  • Industrial quality control and defect detection from inspection images.
  • Few-shot image recognition using frozen ViT features as embeddings.

How it works

How it works

1

The input image is divided into a grid of fixed-size patches (e.g., 16x16 pixels). Each patch is flattened and linearly projected into an embedding vector. A learnable class token is prepended to the sequence and positional embeddings are added, giving the transformer a spatial sense of patch locations.

2

A ViT checkpoint pre-trained on a large image corpus (for example ImageNet-21k or JFT) is loaded. The encoder weights, including the multi-head self-attention blocks and feed-forward layers, were learned during pre-training and serve as the initialization for fine-tuning instead of random values.

3

The pre-trained classification head is removed and replaced by a new linear layer whose output dimension equals the number of classes in the target task. This new head is initialized randomly and is the only component that must be learned from scratch.

4

The full model (or selected layers) is trained end-to-end on the labeled target dataset using a low learning rate and cross-entropy loss. Layer-wise learning rate decay, warm-up schedules and data augmentation (RandAugment, mixup) are common practice: a low rate and warm-up limit how far the pre-trained weights move early in training, layer-wise decay keeps earlier layers closer to their pre-trained values, and augmentation reduces overfitting on small datasets.

Formula
\mathcal{L} = -\sum_{c} y_c \log \hat{p}_c
5

Model performance is assessed on a held-out test set using accuracy, top-5 accuracy, F1-score, or area under the ROC curve depending on the task. Hyperparameters and early stopping are decided on a separate validation split, and the test set is used once for the final report. Confusion matrices help diagnose misclassification patterns, and attention map visualizations show whether attention falls on task-relevant image regions, although attention is not a formal explanation.

Common pitfalls

  • Using a learning rate too high for the pre-trained encoder layers, causing catastrophic forgetting of ImageNet features.
  • Skipping data augmentation on small fine-tuning datasets, leading to overfitting to training examples.
  • Reporting only top-1 accuracy without F1 or AUC on imbalanced datasets, which masks poor minority-class performance.
  • Failing to resize or pad input images to the patch resolution expected by the pre-trained model, introducing resolution mismatch artifacts.
  • Treating attention maps as ground-truth explanations without acknowledging that attention does not equate to causal attribution.

Frequently asked questions

How much labeled data do I need to fine-tune a ViT?

There is no fixed minimum. Fine-tuning benefits from pre-training and can work with a modest number of labeled examples per class when strong augmentation and regularization are used. The more the target domain differs from the pre-training data, the more labeled examples are needed. When the labeled set is very small, linear probing of frozen features or a CNN baseline is often more reliable and should be compared first.

Should I fine-tune the full model or only the classification head?

Full fine-tuning (all layers with a small learning rate for the encoder) typically achieves the best accuracy. Head-only training (linear probing) is faster and safer when labeled data is very scarce, but yields lower accuracy. A middle ground is to freeze early layers and fine-tune only the last few transformer blocks.

Which ViT variant should I choose?

ViT-B/16 is a common starting point that balances accuracy and compute. ViT-L/16 or ViT-H/14 can give higher accuracy at much greater cost. For constrained resources, DeiT-Small or Swin-Tiny are smaller models that trade some accuracy for lower memory use. Where one exists, choose a checkpoint pre-trained on a domain close to your target task.

How do I prevent overfitting on a small fine-tuning set?

Apply strong data augmentation (RandAugment, CutMix, mixup), use a cosine learning rate schedule with warm-up, add dropout and stochastic depth, and use early stopping based on validation loss. Layer-wise learning rate decay, which applies lower rates to earlier layers, also helps preserve pre-trained features.

Can Fine-Tuned ViT be used for tasks beyond image classification?

Yes, for dense prediction tasks such as object detection and semantic segmentation. The usual approach is to keep the pre-trained encoder, replace the classification head with a task-appropriate decoder or prediction head, and fine-tune end-to-end. Generative uses are outside the scope of this page.

Related methods

Sources

  1. Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., & Houlsby, N. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. In International Conference on Learning Representations (ICLR 2021).

    Open publication reference
  2. Zhai, X., Kolesnikov, A., Houlsby, N., & Beyer, L. (2022). Scaling Vision Transformers. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR 2022), pp. 12104-12113.

    Open publication reference