AI Wiki中文/EN

Vision Transformer: from image patches to a class token

视觉 Transformer

Run a complete small ViT, test patch-order symmetry, and track token counts, attention cost and data assumptions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with a prediction

Cut an image into small square patches, shuffle those patches, and ask a classifier for its answer. Should the answer change? For the original ViT construction with its positional embeddings removed, the class-token output is unchanged by a permutation of whole patch tokens. The model still sees the pixels inside each patch; what it loses is a way to distinguish the patches’ global arrangement.

That prediction follows from how attention works, and the program below tests it. It provides a more useful introduction than saying that ViT “treats images as language.” Patches are numeric arrays of pixels, not words or detected objects. A patch boundary may cut straight through an object.

The original Vision Transformer projects fixed-size image patches into vectors, adds learned position embeddings and a classification token, and processes the sequence with a Transformer encoder. Its design reuses the encoder machinery with relatively few image-specific structural choices. ViT method,§3.1

Here the topic is that original raw-patch, class-token architecture. Vision Transformers are a broader family; Swin, for example, changes attention neighborhoods and spatial resolution across stages.

Follow the tensors and equations

Let an H×W image have C channels. Choose a square patch side P that divides both H and W. Flatten each patch in a fixed pixel/channel order. There are N patches, and the embedding matrix E maps each P²C-dimensional row to width D:

N=HWP2,Xp∈RN×P2C,E∈RP2C×D.\begin{aligned}N&=\frac{HW}{P^2},\\X_p&\in\mathbb R^{N\times P^2C},\\E&\in\mathbb R^{P^2C\times D}.\end{aligned}

Prepend a learned class vector, then add a learned position row for every token, including the class token:

Z0=[xcls;XpE]+Epos,Epos∈R(N+1)×D.\begin{aligned}Z_0&=[x_{\mathrm{cls}};X_pE]+E_{\mathrm{pos}},\\E_{\mathrm{pos}}&\in\mathbb R^{(N+1)\times D}.\end{aligned}

Bias terms are omitted in this compact equation; the program includes them. A convolution with kernel P, stride P and no padding can implement the same patch projection, provided its weights use the same flattening order. This operation does not slide a window one pixel at a time. The fixed official implementation uses such a patch projection and then flattens its grid. ViT source, raw-patch path

With T=N+1 tokens and n_h equal-sized heads, each head has width d_h=D/n_h. Its attention computation is:

Q=ZWQ,K=ZWK,V=ZWV,A=softmax⁡row ⁣(QK⊤dh),O=AV.\begin{aligned}Q&=ZW_Q,\quad K=ZW_K,\quad V=ZW_V,\\A&=\operatorname{softmax}_{\mathrm{row}}\!\left(\frac{QK^\top}{\sqrt{d_h}}\right),\\O&=AV.\end{aligned}

Concatenate the heads and apply an output projection. Each row of A sums to one. These are weights for mixing values, not calibrated probabilities that a patch caused the prediction. The class token participates as a query, key and value; it is not a separate external averaging operation.

The encoder applies normalization before attention and before its two-layer MLP, adding a residual after each. A final normalization supplies the class-token representation:

Z^l=Zl−1+MSA⁡(LN⁡(Zl−1)),Zl=Z^l+MLP⁡(LN⁡(Z^l)),y=LN⁡(ZL)0.\begin{aligned}\widehat Z_l&=Z_{l-1}+\operatorname{MSA}(\operatorname{LN}(Z_{l-1})),\\Z_l&=\widehat Z_l+\operatorname{MLP}(\operatorname{LN}(\widehat Z_l)),\\y&=\operatorname{LN}(Z_L)_0.\end{aligned}

The MLP uses GELU between its two linear transformations. The paper uses a hidden-layer classification head during pretraining and a linear head when fine-tuning. Our example uses a random linear head to expose nontrivial output before training; it does not reproduce the paper’s zero-initialized fine-tuning head. Equations 1–4 and fine-tuning

Now justify the opening prediction. Let Π permute only the patch rows while fixing the class row. Shared linear projections, rowwise LN and the MLP commute with that permutation. Attention scores transform into ΠQKᵀΠᵀ, so the output rows are permuted in the same way. The class row is unchanged. Fixed position embeddings generally break this symmetry; permuting the corresponding position rows together restores it. Position labels let a model distinguish locations, but do not make a randomly initialized model understand their geometric meaning.

A complete small forward pass

The example runs an entire two-block classifier, not only a patch reshaping demonstration. Python 3.12.4 and NumPy 1.26.4 suffice. It uses a fixed 8×8 RGB image, patch side 2, width 8, two heads and an MLP hidden width 16. That is much smaller than the paper’s models. GELU is evaluated with the exact erf formula; dropout is disabled, and no parameters are trained.

StepShape
RGB input8×8×3
Flattened patches16×12
Projected patch rows16×8
Add class token and positions17×8
Attention scores per encoder block2×17×17
Final class probabilities3
"""Original small ViT forward pass: HWC images, pre-LN, no dropout/training."""
import math
import numpy as np


def positive(n):
    if isinstance(n,(bool,np.bool_)) or not isinstance(n,(int,np.integer)) or n<1:
        raise ValueError('expected a positive integer')
    return int(n)


def finite(x,ndim):
    x=np.asarray(x,dtype=float)
    if x.ndim!=ndim or min(x.shape)<1 or not np.isfinite(x).all():
        raise ValueError('expected finite nonempty tensor of the specified rank')
    return x


def patchify(x,patch):
    x=finite(x,3);p=positive(patch);h,w,c=x.shape
    if h%p or w%p:raise ValueError('image sides must be divisible by patch size')
    return x.reshape(h//p,p,w//p,p,c).transpose(0,2,1,3,4).reshape(-1,p*p*c)


def norm_params(width):
    width=positive(width)
    return (np.ones(width),np.zeros(width))


def layer_norm(x,params,eps=1e-5):
    x=np.asarray(x,dtype=float);gamma,beta=map(np.asarray,params)
    if x.ndim<2 or x.shape[-1]<1 or not np.isfinite(x).all():raise ValueError('invalid normalization input')
    if gamma.shape!=(x.shape[-1],) or beta.shape!=gamma.shape or eps<=0 or not np.isfinite(eps):
        raise ValueError('normalization shape or epsilon mismatch')
    if not np.isfinite(gamma).all() or not np.isfinite(beta).all():raise ValueError('invalid normalization parameters')
    centered=x-x.mean(axis=-1,keepdims=True)
    return centered/np.sqrt((centered*centered).mean(axis=-1,keepdims=True)+eps)*gamma+beta


def softmax(x):
    x=np.asarray(x,dtype=float)
    if x.ndim<1 or x.shape[-1]<1 or not np.isfinite(x).all():raise ValueError('invalid logits')
    z=np.exp(x-x.max(axis=-1,keepdims=True))
    return z/z.sum(axis=-1,keepdims=True)


def gelu(x):
    x=np.asarray(x,dtype=float)
    return .5*x*(1+np.vectorize(math.erf,otypes=[float])(x/np.sqrt(2)))


def make_block(width,heads,hidden,rng):
    width,heads,hidden=map(positive,(width,heads,hidden))
    if width%heads:raise ValueError('width must divide into equal heads')
    matrix=lambda a,b:rng.normal(0,.1,(a,b))
    return dict(qkv=matrix(width,3*width),qkv_bias=np.zeros(3*width),
                projection=matrix(width,width),projection_bias=np.zeros(width),
                first=matrix(width,hidden),first_bias=np.zeros(hidden),
                second=matrix(hidden,width),second_bias=np.zeros(width),
                norm1=norm_params(width),norm2=norm_params(width),heads=heads)


def attention(x,block):
    x=finite(x,2);n,width=x.shape;heads=positive(block['heads'])
    if width%heads:raise ValueError('width must divide into equal heads')
    qkv=(x@block['qkv']+block['qkv_bias']).reshape(n,3,heads,width//heads)
    q,k,v=qkv.transpose(1,2,0,3)
    weights=softmax((q@k.transpose(0,2,1))/np.sqrt(width//heads))
    y=(weights@v).transpose(1,0,2).reshape(n,width)
    return y@block['projection']+block['projection_bias'],weights


def encoder(x,blocks,final_norm):
    weights=[]
    for block in blocks:
        delta,a=attention(layer_norm(x,block['norm1']),block);x=x+delta;weights.append(a)
        y=layer_norm(x,block['norm2'])
        x=x+gelu(y@block['first']+block['first_bias'])@block['second']+block['second_bias']
    return layer_norm(x,final_norm),weights


def make_model(shape=(8,8,3),patch=2,width=8,heads=2,depth=2,hidden=16,classes=3,seed=11):
    shape=tuple(positive(x) for x in shape);patch,width,heads,depth,hidden,classes=map(positive,(patch,width,heads,depth,hidden,classes))
    if len(shape)!=3 or shape[0]%patch or shape[1]%patch:raise ValueError('invalid image/patch shape')
    if width%heads:raise ValueError('width must divide into equal heads')
    rng=np.random.default_rng(seed);n=shape[0]*shape[1]//patch**2
    return dict(shape=shape,patch=patch,embedding=rng.normal(0,.1,(patch*patch*shape[2],width)),
                embedding_bias=np.zeros(width),cls=np.zeros((1,width)),
                positions=rng.normal(0,.02,(n+1,width)),
                blocks=[make_block(width,heads,hidden,rng) for _ in range(depth)],
                final_norm=norm_params(width),head=rng.normal(0,.1,(width,classes)),head_bias=np.zeros(classes))


def encode_patches(patches,model,positions=None):
    patches=finite(patches,2);x=patches@model['embedding']+model['embedding_bias']
    x=np.concatenate((model['cls'],x),axis=0)
    pos=model['positions'] if positions is None else finite(positions,2)
    if pos.shape!=x.shape:raise ValueError('position table does not match the token sequence')
    x,weights=encoder(x+pos,model['blocks'],model['final_norm'])
    logits=x[0]@model['head']+model['head_bias']
    return dict(logits=logits,probabilities=softmax(logits),tokens=x,attention=weights)


def forward(x,model):
    x=finite(x,3)
    if x.shape!=model['shape']:raise ValueError('image shape differs from the configured model')
    return encode_patches(patchify(x,model['patch']),model)


if __name__=='__main__':
    x=np.arange(192.,dtype=float).reshape(8,8,3)/192
    model=make_model();result=forward(x,model)
    print('patches / tokens:',patchify(x,2).shape,result['tokens'].shape)
    print('probabilities:',np.round(result['probabilities'],6).tolist())
    patches=patchify(x,2);order=np.arange(len(patches))[::-1];zero=np.zeros_like(model['positions'])
    a=encode_patches(patches,model,zero)['logits'];b=encode_patches(patches[order],model,zero)['logits']
    print('no-position permutation gap:',round(float(np.max(np.abs(a-b))),12))
    print('attention score entries per head, 224/16 and 448/16:',197**2,785**2)

Expected output:

patches / tokens: (16, 12) (17, 8)
probabilities: [0.315122, 0.43031, 0.254568]
no-position permutation gap: 0.0
attention score entries per head, 224/16 and 448/16: 38809 616225

The zero permutation gap is rounded to twelve decimal places. The tests check the actual logits and token rows to a numerical tolerance. A second test keeps distinct positional rows fixed while shuffling patches and observes a change; a third shuffles both patches and their positions and restores the class output. These controlled cases separate what follows from the architecture from what must be learned.

The 8×8 numeric ramp is synthetic input, not a labeled image dataset. Its probabilities have no recognition-quality interpretation. Altering the image size requires a matching model and position table; this implementation raises an error instead of silently cropping or resizing.

Limits and comparisons

Patch size controls both the visible detail within tokens and the length of the sequence. For a 224×224 image with 16×16 patches there are 196 patches and 197 total tokens. Doubling each image side while holding P fixed produces 784 patches and 785 tokens. Each head’s score matrix grows from 38,809 to 616,225 entries, nearly sixteenfold. Holding image size fixed and halving patch size has the same token-count effect.

The quadratic term does not describe all work in a block. With MLP hidden width F and fixed D, a simplified MAC count excluding biases, activations and normalization is:

Cblock≈4TD2+2T2D+2TDF.C_{\mathrm{block}}\approx4TD^2+2T^2D+2TDF.

The first term covers attention projections, the second the score/value products, and the third the MLP. Storing attention weights costs one T×T array per head in this explicit implementation. Other attention kernels may avoid materializing that array, so this is not a universal peak-memory formula.

The paper adjusts learned spatial position embeddings by 2D interpolation when fine-tuning at higher resolution. Changing the array length alone is not enough; the class position and spatial grid must be handled consistently. Interpolation is outside this program’s scope. ViT§3.2

Data conditions also matter. In the original§4.3 experiments, the relative advantage of larger ViT models changes across ImageNet, ImageNet-21k and JFT pretraining. A separate subset study uses fixed hyperparameters, early stopping and linear few-shot evaluation rather than the full fine-tuning metric. These results do not establish a universal minimum dataset size or prove that a bigger model always wins. Data-requirement experiments

Compared with a CNN, raw-patch ViT has fewer built-in locality constraints after patching; it does not have no inductive bias at all. Patch boundaries, shared transformations and position handling are still choices. Compare convolution and Swin before deciding which spatial assumptions suit a task.

Exercises with answers

1. Count the tokens

Answer: An 8×8 RGB image with patch side 2 gives 16 patches, each with 12 raw values. Projecting to width 8 gives 16×8; adding the class token makes 17×8. The channel count 3 affects patch-vector width, not the number of patches.

2. Shuffle patches without positional rows

Answer: The class output stays the same up to numerical tolerance because the encoder is permutation-equivariant and the class row is fixed. Pixels inside each patch are not shuffled, so this does not imply invariance to arbitrary pixel permutations.

3. Double both image sides

Answer: At patch side 16,224×224 gives 197 total tokens and 448×448 gives 785. Score entries per head are 38,809 and 616,225. The class token makes the ratio slightly different from exactly 16.

4. Interpret a data-scaling claim

Answer: Ask which pretraining data, regularization, early-stopping policy and downstream metric were used. The original subset experiment uses linear few-shot evaluation; it cannot be substituted for a claim about all fine-tuned models or all small datasets.

Sources and next steps

The paper version read here is arXiv v2, dated 2021-06-03 and labeled as the ICLR 2021 conference paper. The primary scope is§3–4.1 plus the bounded§4.3 discussion; the full appendix and all benchmark claims were not audited. Fixed paper version

The implementation reference is Google Research’s vit_jax/models_vit.py at commitc27af3e61245e9040ee27834d3e93e0ee2506301, dated 2026-07-09. Its checked path covers learned position rows, pre-LN encoder blocks, the raw-patch embedding and token classifier. The Apache-2.0 license was checked. The NumPy code is original; exact-erf GELU, random weights, fixed shape and a random linear head make it a teaching implementation, not a bit-identical JAX model. Fixed source

A next experiment is to inspect attention while changing one patch, keeping weights and positions fixed. Report both the changed probabilities and the changed internal tensors. An attention image alone is not evidence that the classifier learned a useful visual rule.

Make a prediction, then check

For an8×8 RGB image with patch side2, how many tokens enter the class-token ViT encoder?

Choose one answer

Learning objectives

  • Derive patch, embedding and attention tensor shapes.
  • Explain what patch permutation tests establish about position information.
  • Separate attention cost and data-dependent performance claims.

Prerequisites & connections

Explore related knowledge →

References

  1. An Image Is Worth 16x16 Words: Transformers for Image Recognition at Scale — arXiv v2 / ICLR 2021
    Alexey Dosovitskiy; Lucas Beyer; Alexander Kolesnikov; Dirk Weissenborn; Xiaohua Zhai; Thomas Unterthiner; Mostafa Dehghani; Matthias Minderer; Georg Heigold; Sylvain Gelly; Jakob Uszkoreit; Neil Houlsby · 2021
  2. Google Research Vision Transformer — fixed commit c27af3e (2026-07-09)
    Google Research contributors · 2026

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded original method passages and fixed official code, explicit NumPy teaching models, independent numerical references, boundary cases and corresponding bilingual reasoning. Not independent human or second-agent review; no full training or deployment benchmark reproduction.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • Verified exact patch order and literal strided projection, per-head scalar attention reference, class-token permutation invariance without positions, joint patch/position permutation and fixed-position counterexample, pre-LN residual/final-LN ordering, exact GELU relation and full two-block forward shapes. 9 article checks; fixed raw-patch model, no pretrained performance claim.
  • Both languages compared section by section for claims, caveats, definitions, examples, formulas and four answer explanations. English spacing edited only outside code, mathematics, tags and link destinations before freezing.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Final English read-through separated adjoining words and numerals such as An8 and permits576. Protected code, math, tags and link targets are identical; definitions, figures, numbers and exercise answers unchanged. Frozen wording retained; formal English SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.