MONA explainer 9 min read

ViT Architecture: Patch Embedding, Class Token and Encoder, Part by Part

Mona holds her hands apart as if measuring a stack, beside a dog photo cut into patches, a token column and stacked blocks

What is the ViT architecture?

The ViT architecture is the layout of a vision transformer: it cuts an image into square patches, turns each patch into a token (a list of numbers), adds one extra summary token (the class token) and each patch’s position, and runs all tokens through blocks where each token weighs every other.

Knowing these parts explains what patch size, image size and model size change; one dog photo from a photo-sorting app shows each part.

A vision transformer (ViT) is a transformer for images. A transformer works on a list of tokens; its key step, attention, lets each token weigh every other token and mix in what it finds relevant. Our transformer theme starts with attention and the transformer architecture; the ViT applies them to pixels, the coloured dots of an image.

What a ViT is overall is in our vision transformer explainer; here we take one apart. A pre-trained ViT (trained on a large image set) turns a photo into a label through five parts.

One dog photo, five parts

The app’s photo is 224 x 224 pixels and shows a dog. What happens to it, part by part: patch embedding → class token → position embeddings → transformer encoder → head.

Patch embedding: from pixels to 196 tokens

The photo is cut into non-overlapping 16 x 16-pixel patches: 196 of them, for this size and patch size only. Each is flattened into one row of colour values.

The patch embedding turns each row into a token with one learned linear step, a multiplication by a table of weights (numbers learned in training). The result has 768 numbers for ViT-Base: the model width. Hugging Face and torchvision implement it as a convolution whose filter jumps one patch at a time: the same step (see below).

The class token

The class token is one extra learned token of 768 numbers placed first, with no patch. Attention lets it mix in all 196 patch tokens, so its final numbers describe the whole photo, and the head reads only them.

Averaging the patch tokens works about as well, the original ViT paper found, given its own learning rate (the step size of training).

Position embeddings: where each patch was

Attention alone sees a bag of patches with no order, so the model adds to each token a learned list of 768 numbers for its position. After training, nearby patches, and patches in one row or column, have similar ones.

The authors compared no position embedding, one list per position, separate row and column lists, and relative positions (the distance between two patches). The learned options scored almost the same; leaving positions out scored clearly lower.

The encoder block

The transformer encoder is a stack of identical blocks. Each block, per token:

  • Layer norm rescales the token’s numbers.

  • Multi-head self-attention: each token weighs every other, in several parallel heads that work on slices of the numbers (attention mechanism in depth).

  • Residual connection: the block’s input is added back.

  • MLP: after a second layer norm, a small network (MLP) of two linear layers with a smooth function (GELU) between them, per token; the input is added back.

The head

After a final layer norm, the head turns the class token’s 768 numbers into a label. It is a small network in pre-training and one linear layer with one output per label for fine-tuning (continuing training on your own smaller photo set). The top output is “dog”.

The dog photo through the ViT: patches, tokens, class token, encoder blocks, head.

ViT sizes

ViT-B/16 means the Base size with 16 x 16 patches. Parameters are the learned weights; more blocks and a wider token cost more compute per photo.

SizeBlocksWidthHeadsParameters
Base127681286M
Large24102416307M
Huge32128016632M

If you only wanted the parts of a ViT and what each does, you can stop here.

Patch size sets the token count and the compute

Halving the patch side quadruples the patches: for the same photo, ViT-B/32 cuts 49 and ViT-B/16 cuts 196. torchvision lists 4.41 billion operations (GFLOPs) per image for B/32 and 17.56 for B/16, a ratio of 3.98. In the ViT paper, pre-training compute grew by about the same factor.

Only attention grows with the square of the token count, because it scores every pair of tokens; the MLP and the linear steps grow in step with the count.

At this size the total therefore grew about fourfold, like the tokens. The square shows with more tokens: at 384 x 384, the attention pairs are about 8.6 times the count at the original size.

The compute bought accuracy (the share of test images labelled correctly). After pre-training on the paper’s in-house JFT-300M set of 303 million images, for 7 epochs (passes over the data) and fine-tuning at 384 x 384, B/16 reached 84.15 % on ImageNet, the standard public photo benchmark, and B/32 80.73 %.

The weights barely change: only the patch step and the position table depend on the patch size.

The convolution in the code is the same linear step

Counting the paper’s design by arithmetic, with a plain linear patch step and a head for 1,000 labels, gives 86,567,656 weights for ViT-B/16. torchvision records exactly that count (num_params) for its convolution version, and the same count matches its B/32, L/16 and L/32 models to the last digit. The convolution adds no weights and removes none.

Training at one image size, fine-tuning at another

The ViT paper notes that fine-tuning at a higher resolution than pre-training often helps. The DeiT authors (Touvron and colleagues, whose recipe trains a ViT-B-sized model on ImageNet only) measured 81.8 % at 224 x 224 and 83.1 % at 384 x 384, while throughput fell to under a third.

With the same patch size, a 384 x 384 photo gives a 24 x 24 grid of 576 patches instead of 14 x 14, and the learned position table fits only the smaller grid. The paper’s fix: lay the position embeddings out on their grid, resize the grid (interpolation), then fine-tune.

In Hugging Face, interpolate_pos_encoding=True does this: it keeps the class token’s position vector aside and resizes the rest with bicubic interpolation; torchvision has interpolate_embeddings.

Bicubic, because the DeiT authors found that bilinear interpolation, a simpler resizing method, shrinks the vectors, and accuracy drops significantly if they are used without fine-tuning. The class token and the head need no change. Hands-on: the ViT fine-tuning guide.

Register tokens: scratch space for large models

Darcet and colleagues (2023, ICLR 2024) found that in large ViTs a small fraction of output tokens, on plain background patches, have vectors about ten times longer (higher norm) than the rest. Their hypothesis: the model reuses low-information patches to store information about the whole image.

In DINOv2, Meta’s ViT trained without labels, only the three largest of six sizes did this.

The fix adds a few learned tokens, called registers, after the patch embedding, like the class token, and drops them at the end. One register removed the artifacts; the authors kept 4, adding under 2 % compute.

With a linear probe (training only a new final layer on top of a frozen model), DINOv2 ViT-L/14, trained on ImageNet-22k (a larger ImageNet set), rose from 46.6 to 47.9 mIoU on ADE20k, a benchmark that labels every pixel by object (mIoU: the mean overlap between predicted and true regions).

ImageNet accuracy moved by half a point or less for all three model families the authors tested.

The position-embedding comparison, in numbers

The paper’s setup: ViT-B/16, ImageNet accuracy of a linear classifier trained on 5 labelled images per class, one value per variant; the appendix does not name the pre-training data.

One list per position: 64.2 %. Rows and columns: 64.0 %. Relative: 64.0 %. None: 61.4 %.

The three default variants sit within 0.21 points of each other, and the paper’s other places to insert the table (every layer, shared) stay within 0.33 points; dropping positions costs 2.6 to 2.9 points. The authors’ guess: patches form a small grid, so the way positions are written changes little.

When it breaks: Two places tie a ViT to its training setup: a new image size needs resized position embeddings, and averaging instead of the class token needs a new learning rate.

In the 2020 ViT paper, a ViT trained from scratch on a mid-sized set such as ImageNet without strong regularization (training measures against overfitting) landed a few points below ResNets of comparable size (a family of CNNs, convolutional neural networks that slide small filters over the image); the DeiT recipe above closes much of that gap with stronger training.

The ViT paper ties this to inductive bias (assumptions built into the design, like “nearby pixels belong together”): a ViT has much less of it than a CNN. Our ViT vs CNN comparison explains the trade.

Cheat sheet

The article on one page: open it full size, save it or share it.

Cheat sheet: the five ViT parts on one dog photo, the three model sizes, what patch size changes, position embedding results
PNG

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors