视觉Transformer:从图像块到分类token
Vision Transformers
运行完整小ViT,检验patch顺序对称性,跟踪token数量、注意力成本和数据假设。
vision-transformers先做一个预测
把一张图像切成小方块,打乱方块顺序,再交给分类器,答案应该变化吗?对于原始ViT构造,如果去掉位置编码,整块token的置换不会改变分类token的输出。模型仍然看得到每个块内部的像素,却缺少区分各块全局排列的办法。
这个预测可以从注意力的性质推导出来,下面的程序也会检验它。相比笼统地说“把图像当语言”,这样的入口更有用:patch是像素组成的数值数组,不是词,也不一定对应一个物体,边界可能直接切过物体。
原始视觉Transformer把固定大小的图像块投影为向量,加入可学习的位置编码和分类token,再让序列经过Transformer编码器。它复用了编码器的计算结构,针对图像专门写入的结构约束相对较少。ViT方法,§3.1
本文讨论原始的像素分块、分类token架构。视觉Transformer是更大的家族;例如Swin会改变注意力邻域,并逐阶段降低空间分辨率。
跟踪张量与公式
设H×W图像有C个通道,方形patch边长P能够整除H与W。按固定的像素、通道顺序把每个块展平,得到N个patch,再用嵌入矩阵E把每个P²C维行向量映射到宽度D:
在序列前加入可学习的分类向量,再给每个token加入一个可学习的位置行,分类token也有自己的位置行:
这条紧凑公式省略了偏置,程序中包含偏置。核大小P、步幅P、无填充的卷积可以完成相同的patch投影,前提是权重遵守相同展平顺序。它不是每次移动一个像素的滑窗。固定官方实现正是先做这种投影,再把网格展平成序列。ViT源码的原始patch路径
序列长度T=N+1,若共有n_h个等宽注意力头,每头宽度为d_h=D/n_h。单头计算为:
拼接各头后,再做输出投影。A的每一行和为1,它们是混合value的权重,不是“该patch导致预测结果”的校准概率。分类token也参与query、key和value计算,不是在网络外单独做一次平均。
编码器在注意力和两层MLP之前分别做归一化,之后各加一次残差;末端归一化给出分类token表示:
MLP的两次线性变换之间使用GELU。论文预训练时采用带隐藏层的分类头,微调时使用线性头。本例使用随机线性头,让未训练的输出也有区别,没有复现论文零初始化的微调分类头。公式1–4与微调方法
现在解释开头的预测。用Π只置换patch行,固定分类行。共享线性投影、逐行LN和MLP都能与这种置换交换顺序;注意力分数变为ΠQKᵀΠᵀ,因此输出行也按相同方式置换,分类行保持不变。固定位置编码通常会打破这种对称性;若连对应位置行一起置换,对称性又会恢复。位置标签允许模型区分位置,却不会让随机初始化的模型自动理解几何关系。
完整的小型前向计算
本例运行完整的两块分类器,不只是展示patch重排。环境为Python3.12.4、NumPy1.26.4:固定8×8 RGB输入、patch边长2、宽度8、两个注意力头、MLP隐藏宽度16,远小于论文模型。GELU按erf精确公式计算,关闭dropout,也不训练任何参数。
| 步骤 | 形状 |
|---|---|
| RGB输入 | 8×8×3 |
| 展平patch | 16×12 |
| 投影后的patch行 | 16×8 |
| 加入分类token和位置 | 17×8 |
| 每个编码器块的注意力分数 | 2×17×17 |
| 最终类别概率 | 3 |
"""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)
预期输出:
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
置换差距的零值保留十二位小数;测试还按数值容差检查实际logit与token行。第二个测试固定不同的位置行,只打乱patch,观察到输出变化;第三个同时打乱patch与对应位置,又恢复了分类输出。这些受控情况把架构自带的性质与需要学习的内容分开了。
8×8数值斜坡是合成输入,不是带标签的图像数据集,输出概率不能说明识别质量。改变图像尺寸时需要匹配的模型与位置表;本实现会明确报错,不静默裁剪或缩放。
局限与比较
Patch大小同时影响token内部可见的细节与序列长度。224×224图像配16×16 patch,得到196个patch、197个总token。固定P,把图像两边都加倍,会得到784个patch、785个token;每头分数矩阵从38,809项增加到616,225项,接近十六倍。固定图像尺寸、把patch边长减半,也有相同的token数量效果。
二次项并不代表块内全部工作。设MLP隐藏宽度F、模型宽度D固定,忽略偏置、激活与归一化后的简化MAC为:
第一项来自注意力投影,第二项来自分数/value乘积,第三项来自MLP。本显式实现还为每个头保存一个T×T权重数组。其他注意力计算核可能不物化整个数组,因此这不是普适的峰值内存公式。
论文在更高分辨率上微调时,对学到的空间位置编码做二维插值。只改数组长度不够,还必须一致地处理分类位置与空间网格。本文程序没有实现插值。ViT§3.2
数据条件也很重要。原论文§4.3的实验中,较大ViT模型的相对优势随ImageNet、ImageNet-21k和JFT预训练设置变化。另一组子集实验使用固定超参数、早停和线性少样本评测,并非完整微调指标。这些结果没有确定普适的最小数据量,也没有证明模型越大总越好。数据需求实验
与CNN相比,原始像素分块ViT在分块后写入的局部性约束更少,但不是毫无归纳偏置:patch边界、共享变换和位置处理仍是设计选择。可以对照卷积与Swin,再判断任务需要什么空间假设。
练习与答案
1. 数一数token
答案:8×8 RGB图像、patch边长2,得到16个patch,每块12个原始数值。投影到宽度8得到16×8,加入分类token后为17×8。RGB的3通道影响patch向量宽度,不影响patch数量。
2. 去掉位置行后打乱patch
答案:分类输出在数值容差内不变,因为编码器对token置换等变,分类行又保持固定。每个patch内部像素没有打乱,因此不能推成任意像素置换都不影响结果。
3. 把图像两边都加倍
答案:patch边长16时,224×224得到197个总token,448×448得到785个;每头分数项数为38,809和616,225。由于还有分类token,倍率并不恰好等于16。
4. 判断数据规模结论
答案:先问预训练数据、正则化、早停方式和下游指标是什么。原论文的子集实验使用线性少样本评测,不能直接替换成关于所有微调模型或所有小数据集的结论。
来源与下一步
本文核读的论文版本是2021-06-03的arXiv v2,正文标为ICLR2021会议论文。主要范围是§3–4.1及限定的§4.3讨论,没有审查全部附录或全部基准主张。固定论文版本
实现参考为Google Research的vit_jax/models_vit.py,固定提交c27af3e61245e9040ee27834d3e93e0ee2506301,日期2026-07-09。核查路径涵盖可学习位置行、预LN编码器块、原始patch嵌入和token分类器,已核看Apache-2.0许可。NumPy代码原创;精确erf GELU、随机权重、固定形状和随机线性头,使它成为教学实现,不是逐位等同的JAX模型。固定源码
下一步可以固定权重和位置,仅改变一个patch,同时观察类别概率与内部张量的变化。单看一张注意力图,不能证明分类器学到了有用的视觉规则。
先判断,再看解释
8×8 RGB图像、patch边长2,带分类token的ViT编码器接收多少token?
学习目标
- 推导patch、嵌入与注意力张量形状。
- 解释patch置换实验能说明的位置性质。
- 区分注意力成本与依赖数据条件的性能主张。
先修与延伸
查看知识关联图 →参考文献
- 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 - Google Research Vision Transformer — fixed commit c27af3e (2026-07-09)
Google Research contributors · 2026
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 单个AI作者进行技术检查:可运行示例、精确或字面参照、明确假设及对应的双语公式与习题。实际执行和渲染结果另行记录。
- 核对精确分块顺序与字面步幅投影、逐头标量注意力参照、无位置编码的分类token置换不变性、patch/位置同步置换及固定位置反例、预LN残差和末端LN顺序、精确GELU关系与完整两块前向尺寸。9项正文检查,固定原始patch模型,未宣称预训练性能。
- 逐节对照中英文论点、限制、定义、例子、公式与四组答案。冻结前仅在代码、数学、标签和链接目标之外调整英文间距。
- 完整双语正文与对应习题迁入,正式文章状态及SHA绑定。算法篇测试读取正式MDX;历史篇不虚列可执行程序或计算测试。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
- 最终英文复读修正An8、permits576等词数粘连;代码、数学、标签和链接目标保持完全相同,定义、图、数字和答案未改。保留冻结措辞,重新绑定正式英文SHA。
核对的来源位置:
- An Image Is Worth 16x16 Words: Transformers for Image Recognition at Scale — arXiv v2 / ICLR 2021 · arXiv2010.11929v2 (2021-06-03), physical pages3–5, sections3–4.1; bounded section4.3 pages6–7; equations1–4 visually checked.
- Google Research Vision Transformer — fixed commit c27af3e (2026-07-09) · Pinned c27af3e (2026-07-09), AddPositionEmbs lines37–63, Encoder1DBlock/Encoder lines132–207 and raw-patch/token-classifier path258–307.
相关主题