Count ViT tokens, attention cost and patch embedding size

Why it matters Choosing between ViT/16 and ViT/8, or a higher input resolution, is a cost decision made with exactly these numbers.

Patch size is the main knob on a ViT's cost: halving it quadruples the tokens and multiplies attention cost by 16.

Write vit_cost(img_size, patch, dim, depth, cls=True). The image is img_size x img_size with 3 channels and img_size divisible by patch. tokens = (img_size // patch)^2 plus 1 if cls. Attention multiply-adds for QK^T and the weighted sum of V together are 2 * tokens^2 * dim per layer, so attn_macs = depth * 2 * tokens^2 * dim. The patch embedding is a linear map from patch * patch * 3 values to dim with a bias: patch_embed_params = patch * patch * 3 * dim + dim. Return a dict with integer "tokens", "attn_macs" and "patch_embed_params".

Signaturedef vit_cost(img_size, patch, dim, depth, cls=True)

Example

vit_cost(224, 16, 768, 12) gives tokens 197, attn_macs 715,591,680 and patch_embed_params 590,592.

Understand the idea

A ViT turns every patch into one token, so the number of tokens is set by how finely you cut the image. Self-attention compares every token with every other token, so its cost grows with the square of the token count. Halving the patch size gives 4 times the tokens and about 16 times the attention work, like a meeting where everyone must talk to everyone: double the people and the conversations quadruple.

Tiny example: 224 x 224 with 16 x 16 patches gives 14 * 14 = 196 patches, plus a class token: 197. With width 768 and 12 layers, attention costs 12 * 2 * 197^2 * 768, about 716 million multiply-adds. The patch embedding has 16 * 16 * 3 * 768 + 768 = 590,592 parameters.

Rules: tokens = (S / p)^2 + cls; attn_macs = depth * 2 * tokens^2 * dim.

This is why high-resolution ViTs and detectors switch to windowed attention.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplevit_cost(224, 16, 768, 12)
  • Sample 2: patch 8vit_cost(224, 8, 384, 12)
  • Test 3: no clsvit_cost(32, 4, 64, 6, cls=False)