Vision Transformer backbone (Dosovitskiy et al., 2020).
A ViT first splits the input image into a sequence of non-overlapping
patches and linearly projects each patch into a -dimensional
embedding. A learnable [CLS] token is prepended, a learnable
positional embedding is added, and the resulting sequence is processed
by depth stacked pre-norm transformer encoder blocks. The final
representation returned by forward_features is the CLS token
embedding after a final LayerNorm — the standard feature used for
classification or transfer learning.
Concretely, the input sequence fed to the encoder is
where is the -th flattened patch, is the patch projection, is the learnable positional embedding, and .
Use this backbone when you want features rather than logits — e.g.
fine-tuning on a custom downstream head, contrastive pretraining, or
feature extraction for retrieval. For end-to-end image classification,
use ViTForImageClassification instead.
Parameters
configViTConfigimage_size, patch_size, dim,
depth, num_heads, mlp_ratio, dropout,
attention_dropout, and in_channels. See ViTConfig.Attributes
patch_embed_PatchEmbedcls_tokenTensor[CLS] token, shape (1, 1, dim). Initialized with
truncated normal .pos_embedTensor(1, num_patches + 1, dim).
Initialized with truncated normal .pos_dropnn.Dropoutblocksnn.ModuleListconfig.depth stacked _ViTBlock encoder layers.normnn.LayerNormfeature_infolist[FeatureInfo]config.dim and spatial reduction equal to config.patch_size.Notes
The classification head is not included in this class — only the
backbone trunk. forward_features returns a flat
feature tensor, whereas forward wraps it in a
BaseModelOutput whose last_hidden_state has shape
for spatial consistency with other vision models.
Reference: Alexey Dosovitskiy et al., "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale", ICLR 2021, arXiv:2010.11929.
Examples
Build a ViT-Base/16 backbone and run a single forward pass:
>>> import lucid
>>> from lucid.models.vision.vit import ViT, ViTConfig
>>> cfg = ViTConfig() # ViT-Base/16 defaults
>>> model = ViT(cfg)
>>> x = lucid.randn(1, 3, 224, 224)
>>> feat = model.forward_features(x)
>>> feat.shape # (B, dim)
(1, 768)
>>> out = model(x)
>>> out.last_hidden_state.shape # (B, 1, dim)
(1, 1, 768)Used by 2
Constructors
1Properties
1feature_info: list[FeatureInfo]