掩码自编码器
Masked autoencoders
用四图块模型追踪可见编码、位置恢复与隐藏像素梯度。
masked-autoencoders从问题出发
盖住一张图片的四分之三,让模型补出缺失部分。要补得有依据,模型就得利用可见与隐藏内容之间的关系。掩码自编码器把这件事做成预训练任务:编码器只看可见图块,解码器恢复完整的位置布局并预测像素。原始 MAE 使用不对称的 Transformer 编码器与解码器。Masked Autoencoders Are Scalable Vision Learners
这里有两种不同的掩码。输入掩码决定编码器能看见什么;损失掩码决定哪些预测直接接受监督。隐藏像素混入编码器,就是泄露答案;只在隐藏图块上算损失,则意味着可见图块的解码输出没有直接受到像素匹配监督。
下面用四个图块把两种掩码写清楚。这个小解码器通过均值混合 token,不使用注意力;它解释数据流与梯度,不复现论文中视觉 Transformer 的准确率或速度。
定义与推导
设 V 为可见图块的编号集合,M 为其余隐藏编号,每个图块 含 p 个像素值。只收集 的像素,拼接已知的位置指示向量后编码;解码前恢复原始顺序:
m 是所有隐藏位置共享的可学习掩码向量,不是隐藏图像的测量值。解码器另有可学习位置向量 。本例的均值混合解码器与隐藏像素目标为:
掩码去掉可见输出的直接像素梯度,却不会切断编码器梯度。令 为经过解码器 tanh 导数后的梯度,均值混合会把各输出的信号传给各输入 token:
将隐藏 token 的梯度相加得到共享掩码向量梯度;可见 token 的梯度继续经过编码器;外积累加得到 D 的梯度。程序对 4 张图、每张图 4 种单可见图块掩码,共 16 种情况取平均,计算的是一个有限集合的精确掩码期望,不是每步重新随机抽样。原论文同样恢复位置并计算隐藏像素 MSE,但使用 Transformer,也研究了归一化像素目标。Masked Autoencoders Are Scalable Vision Learners
动手计算
使用 CPython 3.12.4、NumPy 1.26.4。每张构造图像有 4 个图块,每块 2 个像素;只保留 1 块,对应 75% 掩码率。39 个参数包括编码器 18 个、共享掩码 3 个、解码位置 12 个和输出映射 6 个。以 0.05 学习率更新 1,800 步,隐藏像素 MSE 从 0.430531732 降到 0.002074965。打印的是原始解码输出,其中包括未被直接监督的可见位置。展示重建图时,应保留真实可见图块,只填补隐藏块。
import numpy as np
def initial():return np.random.default_rng(7).normal(0,.2,39)
def unpack(theta):return theta[:18].reshape(6,3),theta[18:21],theta[21:33].reshape(4,3),theta[33:39].reshape(3,2)
def predict(patches,visible,theta,cache=False):
patches=np.asarray(patches,dtype=float);ids=np.asarray(visible,dtype=int)
if patches.shape!=(4,2) or not 1<=len(ids)<=3 or len(set(ids.tolist()))!=len(ids) or np.any(ids<0) or np.any(ids>=4):raise ValueError('Use four two-pixel patches and 1..3 unique visible patch IDs.')
e,mask,pos,d=unpack(theta);features=np.c_[patches[ids],np.eye(4)[ids]];encoded=np.tanh(features@e);tokens=np.tile(mask,(4,1));tokens[ids]=encoded;hidden=np.tanh(tokens+tokens.mean(axis=0)+pos);prediction=hidden@d
return (prediction,(features,encoded,tokens,hidden,ids)) if cache else prediction
def objective(theta):
e,mask,pos,d=unpack(theta);loss=0.;gradient=np.zeros(39);count=0
offsets=np.array([[-.3,.1],[-.1,-.1],[.1,.2],[.3,-.2]])
for signal in ([ -.8,-.4],[-.4,.7],[.5,-.6],[.8,.6]):
patches=np.array(signal)+offsets
for visible in range(4):
pred,(features,encoded,tokens,hidden,ids)=predict(patches,[visible],theta,True);masked=np.ones(4,dtype=bool);masked[ids]=False;error=(pred-patches)*masked[:,None];loss+=np.sum(error**2)/6;gp=2*error/6;gd=hidden.T@gp;gh=(gp@d.T)*(1-hidden**2);gt=gh+gh.sum(axis=0)/4;ge=features.T@(gt[ids]*(1-encoded**2));gm=gt[masked].sum(axis=0);gradient+=np.r_[ge.ravel(),gm,gh.ravel(),gd.ravel()];count+=1
return loss/count,gradient/count
def train(steps=1800):
theta=initial();start=objective(theta)[0]
for _ in range(steps):theta-=.05*objective(theta)[1]
return theta,start,objective(theta)[0]
if __name__=='__main__':
t,start,end=train();patches=np.array([.5,-.6])+np.array([[-.3,.1],[-.1,-.1],[.1,.2],[.3,-.2]]);out=predict(patches,[2],t);print('masked pixel MSE before/after',round(start,9),round(end,9));print('visible IDs',[2],'encoded tokens',1,'decoder tokens',4,'prediction',out.round(6).tolist())
corrupted=patches.copy();corrupted[[0,1,3]]+=100;print('hidden-input leakage discrepancy',float(np.max(np.abs(predict(corrupted,[2],t)-out))))
masked pixel MSE before/after 0.430531732 0.002074965
visible IDs [2] encoded tokens 1 decoder tokens 4 prediction [[0.192277, -0.388868], [0.403135, -0.589391], [2.017513, -2.040388], [0.816682, -0.702959]]
hidden-input leakage discrepancy 0.0
什么时候会失效
打印示例中的可见图块实际为 ,解码器在该位置却预测约 。这与只监督隐藏位置的目标并不矛盾。若暗中把可见预测当作同样受过监督的输出评分,就会误导读者。
训练重建误差低,也不能证明编码器适合识别任务。解码器可能利用简单的图像规律,像素 MSE 还会对多个合理答案取平均。应当在独立任务与留出数据上评估编码器,不能让隐藏值参与编码输入。
真实注意力编码器有 P 个图块、可见比例 v 时,token 两两计算项与 有关,但投影、前馈层和解码器仍有成本。token 数降至四分之一,不代表已测得十六倍加速。本例均值解码器在宽度固定时随 token 数线性增长,不是注意力性能基准。可对照去噪自编码器,它的损失不一定只覆盖受损位置。Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion
练习与答案
- 为什么改变隐藏输入像素不会改变预测?
答案1: 编码器只收集可见编号;隐藏像素只在损失中充当目标。
- 一种掩码下,损失包含几个像素值?
答案2: 3 个隐藏图块乘每块 2 个像素,共 6 个,MSE 除以 6。
- 可见输出没有损失,编码器还能学习吗?
答案3: 能。可见 token 影响公共均值,进而影响隐藏输出。
- 补全图在可见位置应该显示什么?
答案4: 显示实际观察像素,只在隐藏位置使用预测;需要时另行报告原始解码输出的评测。
来源与延伸
先读 MAE 第 3 节的可见 token 编码、共享掩码与逆置换,再对照堆叠去噪自编码器中的损坏与重建关系。扩展本例时,可以在训练中留出一种完整底层信号,在评估中枚举其掩码,并与均值像素预测器比较。这样检验的是泛化,而不是 39 个参数能否拟合四张构造图。Masked Autoencoders Are Scalable Vision Learners;Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion
先判断,再看解释
重建展示应在哪里保留观察到的像素?
学习目标
- 实现相互区分的输入与损失掩码,避免隐藏像素泄露。
- 解释隐藏损失如何训练可见 token,以及怎样展示重建结果。
先修与延伸
查看知识关联图 →参考文献
- Masked Autoencoders Are Scalable Vision Learners
Kaiming He; Xinlei Chen; Saining Xie; Yanghao Li; Piotr Dollár; Ross Girshick · 2022 - Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion
Pascal Vincent; Hugo Larochelle; Isabelle Lajoie; Yoshua Bengio; Pierre-Antoine Manzagol · 2010
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- 单AI作者技术检查:限定范围的一手来源阅读、明确假设、原创计算、可运行示例及对应双语公式、程序和习题。不冒充人工或第二代理独立审校。
- 每篇四项CPython 3.12.4检查通过,按主题核验有限差分梯度、样本协方差、教师与中心更新顺序、隐藏输入隔离、独立最小二乘、半正定投影、间隔可行性、共享分支导数和变换后的因素作用,并检查双语结构。八个程序均使用NumPy 1.26.4,属于教学计算,不冒充图像基准。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 双语Matplotlib 3.9.1图绑定SVG与数值样本SHA。教师概率、仅填隐藏位置的重建图、指定基底雅可比均由正文函数实际计算,明确共同色阶与解释限制。
- 最终MAE图在600px以下使用纵向手机版,由相同数值样本生成。公式、程序、输出与习题未改,重新绑定双语正文SHA与手机SVG依赖。
核对的来源位置:
- Masked Autoencoders Are Scalable Vision Learners · Physical pages 3–4, Section 3: visible-only encoder, shared mask tokens, decoder positions, hidden-only pixel MSE and inverse shuffling.
- Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion · Sections 2–3: corruption, reconstruction and denoising criterion; distinction from hidden-position-only loss.
相关主题