11.5  视觉 Transformer(ViT)

卷积神经网络(第 6 章、第 7 章)将关于图像的两个几何先验直接烘焙进架构之中:空间局部性(\(k \times k\) 卷积核只耦合相邻像素)与平移等变性(同一卷积核权重在每个 \((r, c)\) 位置上滑动)。那么,没有任何内置二维网格邻域或平移等变性概念的标准双向 Transformer 编码器(11.4 节),能否在图像分类上与之匹敌?

直接对单个像素施加自注意力会随像素数量呈二次增长:即便是 \(96 \times 96\) 的图像也有 \(9{,}216\) 个像素(每头 \(9216^2 \approx 8.5 \times 10^7\) 个注意力对)。Dosovitskiy 等 (2021年) 提出了视觉 Transformer(ViT)(图 11.5.1),将图像切分为互不重叠的 \(p \times p\) 图像块网格作为词元:一张 \(96 \times 96\) 的图像在图像块大小 \(p = 16\) 下变成仅含 \(m = (96 / 16)^2 = 36\) 个图像块词元的短序列。每个图像块投影至宽度 \(d\),前端拼接一个可学习的 <cls> 词元,加上学习得到的一维位置嵌入,再将全部 37 个词元送入 \(L\) 个双向前置规范化 Transformer 块。

11.5.1 图像块即词元(PatchEmbedding)

将形状为 \((B, C, H, W)\) 的图像张量划分为互不重叠的 \(p \times p\) 图像块并对每个图像块施加共享线性投影 \(\mathbb{R}^{C p^2} \to \mathbb{R}^d\),完全等价于一次卷积核大小 \(p \times p\)、步幅 \(p\)、输出通道数 \(d\) 的二维卷积,再将高 \(H/p\)、宽 \(W/p\) 的二维空间网格展平为 \(m = (H/p)(W/p)\) 个词元向量的序列:

class PatchEmbedding(nn.Module):
    """Image-to-sequence stem of the vision transformer."""
    def __init__(self, img_size=96, patch_size=16, num_hiddens=512,
                 num_channels=3):
        super().__init__()
        # A partial trailing patch would silently shrink the token grid
        assert img_size % patch_size == 0, 'patches must tile the image'
        self.num_patches = (img_size // patch_size) ** 2
        self.conv = nn.Conv2d(num_channels, num_hiddens,
                              kernel_size=patch_size, stride=patch_size)

    def forward(self, X):  # (batch, c, h, w) -> (batch, patches, d)
        return self.conv(X).flatten(2).transpose(1, 2)
class PatchEmbedding(nnx.Module):
    """Image-to-sequence stem of the vision transformer."""
    def __init__(self, img_size=96, patch_size=16, num_hiddens=512,
                 num_channels=3, *, rngs):
        # A partial trailing patch would silently shrink the token grid
        assert img_size % patch_size == 0, 'patches must tile the image'
        self.num_patches = (img_size // patch_size) ** 2
        # PyTorch's default initialization: U(-a, a), a = 1/sqrt(fan_in)
        a = (num_channels * patch_size ** 2) ** -0.5
        init = lambda key, shape, dtype=jnp.float32: jax.random.uniform(
            key, shape, dtype, -a, a)
        self.conv = nnx.Conv(num_channels, num_hiddens,
                             kernel_size=(patch_size, patch_size),
                             strides=patch_size, padding='VALID',
                             kernel_init=init, bias_init=init, rngs=rngs)

    def __call__(self, X):  # (batch, h, w, c) -> (batch, patches, d)
        X = self.conv(X)
        return X.reshape(X.shape[0], -1, X.shape[-1])

在由四张 \(96 \times 96\) 单通道图像组成的小批量上,当图像块大小 \(p = 16\) 时,PatchEmbedding 输出 \((96 / 16)^2 = 36\) 个宽度为 \(d = 512\) 的图像块词元:

img_size, patch_size, num_hiddens, batch_size = 96, 16, 512, 4
patch_emb = PatchEmbedding(img_size, patch_size, num_hiddens, num_channels=1)
X = torch.zeros(batch_size, 1, img_size, img_size)
d2l.check_shape(patch_emb(X),
                (batch_size, (img_size//patch_size)**2, num_hiddens))
img_size, patch_size, num_hiddens, batch_size = 96, 16, 512, 4
patch_emb = PatchEmbedding(img_size, patch_size, num_hiddens, num_channels=1,
                           rngs=nnx.Rngs(d2l.get_key()))
X = jnp.zeros((batch_size, img_size, img_size, 1))
d2l.check_shape(patch_emb(X),
                (batch_size, (img_size//patch_size)**2, num_hiddens))

11.5.2 视觉 Transformer 架构

图 11.5.1: 作用在 \(96 \times 96\) 图像上的视觉 Transformer。步幅卷积将 \(6 \times 6\) 网格的 \(16 \times 16\) 图像块转为 36 个词元。前端拼接一个可学习的“<cls>”词元并加上学习得到的位置嵌入;\(L\) 个前置规范化 Transformer 块处理全部 37 个词元,最后由线性头对“<cls>”词元的最终表示进行分类。

11.5.2.1 编码器块(ViTBlock)

遵循 Dosovitskiy 等 (2021年),ViTBlock 继承可配置的 d2l.TransformerBlock(11.1 节),采用前置规范化 LayerNorm 以及自定义隐藏宽度 mlp_num_hiddens 的两层 GELU MLP。注意力投影默认不带偏置(use_bias=False),而 MLP 的两层线性层与 LayerNorm 保留偏置:

class ViTBlock(d2l.TransformerBlock):
    """Pre-norm block with LayerNorm and an exact-GELU MLP."""
    def __init__(self, num_hiddens, mlp_num_hiddens, num_heads, dropout,
                 use_bias=False):
        super().__init__(
            num_hiddens, num_heads, dropout=dropout, norm='layer',
            bias=use_bias, ffn_factory=lambda: nn.Sequential(
                nn.Linear(num_hiddens, mlp_num_hiddens),
                nn.GELU(),  # Exact GELU
                nn.Dropout(dropout),
                nn.Linear(mlp_num_hiddens, num_hiddens)))
class ViTBlock(d2l.TransformerBlock):
    """Pre-norm block with LayerNorm and an exact-GELU MLP."""
    def __init__(self, num_hiddens, mlp_num_hiddens, num_heads, dropout,
                 use_bias=False, *, rngs):
        super().__init__(
            num_hiddens, num_heads, dropout=dropout, norm='layer',
            bias=use_bias, rngs=rngs, ffn_factory=lambda rngs: nnx.Sequential(
                d2l.Linear(num_hiddens, mlp_num_hiddens, rngs=rngs),
                lambda X: jax.nn.gelu(X, approximate=False),  # Exact GELU
                nnx.Dropout(dropout, rngs=rngs),
                d2l.Linear(mlp_num_hiddens, num_hiddens, rngs=rngs)))

11.5.2.2 <cls> 词元、位置嵌入与 ViT

为了在不偏袒任何空间位置的前提下将 \(m\) 个图像块表示聚合为单个图像级向量,ViT 在索引 \(0\) 处拼接一个形状为 \((1, 1, d)\) 的可学习参数向量 cls_token,在全部 \(m + 1\) 个位置上加上形状为 \((1, m + 1, d)\) 的可学习位置嵌入表 pos_embedding,经过 \(L\) 层 ViTBlock 后用 LayerNorm 规范化,并将索引 \(0\)(X[:, 0])送入线性分类头:

class ViT(d2l.Classifier):
    """Vision transformer."""
    def __init__(self, *, img_size, patch_size, num_hiddens, mlp_num_hiddens,
                 num_heads, num_blks, num_steps, emb_dropout=0.0,
                 blk_dropout=0.0, lr=1e-3, use_bias=False, num_classes=10,
                 num_channels=1):
        super().__init__()
        self.save_hyperparameters()
        self.patch_embedding = PatchEmbedding(
            img_size, patch_size, num_hiddens, num_channels)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, num_hiddens))
        num_tokens = self.patch_embedding.num_patches + 1  # Add the cls token
        # Positional embeddings are learnable, initialized to small noise
        self.pos_embedding = nn.Parameter(
            torch.randn(1, num_tokens, num_hiddens) * 0.02)
        self.dropout = nn.Dropout(emb_dropout)
        self.blks = nn.ModuleList([
            ViTBlock(num_hiddens, mlp_num_hiddens, num_heads, blk_dropout,
                     use_bias=use_bias) for _ in range(num_blks)])
        self.head = nn.Sequential(nn.LayerNorm(num_hiddens, eps=1e-5),
                                  nn.Linear(num_hiddens, num_classes))

    def forward(self, X):
        X = self.patch_embedding(X)  # (batch, patches, d)
        cls = self.cls_token.expand(X.shape[0], -1, -1)
        X = self.dropout(torch.cat((cls, X), 1) + self.pos_embedding)
        for blk in self.blks:
            X = blk(X)
        return self.head(X[:, 0])

    def configure_optimizers(self):
        # AdamW decays weight matrices and kernels; it exempts biases, norm
        # parameters, the class token, and the position embeddings
        named = list(self.named_parameters())
        decay = lambda n, p: p.ndim >= 2 and n not in ('cls_token',
                                                        'pos_embedding')
        optim = torch.optim.AdamW(
            [{'params': [p for n, p in named if decay(n, p)]},
             {'params': [p for n, p in named if not decay(n, p)],
              'weight_decay': 0.0}], lr=self.lr, weight_decay=0.05)
        # Linear warmup over the first tenth of the steps, then cosine
        return optim, torch.optim.lr_scheduler.LambdaLR(optim, lambda t: (
            d2l.cosine_warmup(t, self.num_steps, self.num_steps // 10)))
class ViT(d2l.Classifier):
    """Vision transformer."""
    def __init__(self, *, img_size, patch_size, num_hiddens, mlp_num_hiddens,
                 num_heads, num_blks, num_steps, emb_dropout=0.0,
                 blk_dropout=0.0, lr=1e-3, use_bias=False, num_classes=10,
                 num_channels=1, rngs):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        self.patch_embedding = PatchEmbedding(
            img_size, patch_size, num_hiddens, num_channels, rngs=rngs)
        self.cls_token = nnx.Param(jnp.zeros((1, 1, num_hiddens)))
        num_tokens = self.patch_embedding.num_patches + 1  # Add the cls token
        # Positional embeddings are learnable, initialized to small noise
        self.pos_embedding = nnx.Param(
            rngs.params.normal((1, num_tokens, num_hiddens)) * 0.02)
        self.dropout = nnx.Dropout(emb_dropout, rngs=rngs)
        self.blks = nnx.List([
            ViTBlock(num_hiddens, mlp_num_hiddens, num_heads, blk_dropout,
                     use_bias=use_bias, rngs=rngs) for _ in range(num_blks)])
        self.head = nnx.Sequential(
            nnx.LayerNorm(num_hiddens, epsilon=1e-5, rngs=rngs),
            d2l.Linear(num_hiddens, num_classes, rngs=rngs))

    def forward(self, X):
        X = self.patch_embedding(X)  # (batch, patches, d)
        cls = jnp.broadcast_to(self.cls_token[...], (len(X), 1, X.shape[2]))
        X = self.dropout(jnp.concatenate((cls, X), 1) + self.pos_embedding)
        for blk in self.blks:
            X = blk(X)
        return self.head(X[:, 0])

    def configure_optimizers(self):
        # AdamW decays weight matrices and kernels; it exempts biases, norm
        # parameters, the class token, and the position embeddings
        decay = lambda params: jax.tree_util.tree_map_with_path(
            lambda path, p: p.ndim >= 2 and path[0].key not in (
                'cls_token', 'pos_embedding'), params)
        # Linear warmup over the first tenth of the steps, then cosine
        return optax.adamw(lambda t: self.lr * d2l.cosine_warmup(
            t, self.num_steps, self.num_steps // 10), weight_decay=0.05,
            mask=decay)

11.5.3 在 Fashion-MNIST 上训练

11.5.3.1 首次运行

我们在 \(96 \times 96\) 的 Fashion-MNIST 上训练一个 2 块 ViT(\(d = 512, d_{\textrm{mlp}} = 2048, H = 8, L = 2, p = 16\),\(\approx 6.5\textrm{M}\) 个参数),使用带线性预热与余弦学习率衰减的 AdamW(\(\lambda = 0.05\))训练 10 个周期:

data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
num_steps = 10 * len(data.train_dataloader())  # Ten epochs of minibatches
hparams = dict(img_size=96, patch_size=16, num_hiddens=512,
               mlp_num_hiddens=2048, num_heads=8, num_blks=2,
               emb_dropout=0.1, blk_dropout=0.1, num_steps=num_steps)
data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
num_steps = 10 * len(data.train_dataloader())  # Ten epochs of minibatches
hparams = dict(img_size=96, patch_size=16, num_hiddens=512,
               mlp_num_hiddens=2048, num_heads=8, num_blks=2,
               emb_dropout=0.1, blk_dropout=0.1, num_steps=num_steps)

训练前,我们实例化 model = vit() 并保存其初始随机图像块位置嵌入的副本 pos_init,以便稍后衡量训练在初始化之上究竟注入了多少空间结构:

vit = lambda: ViT(**hparams, lr=3e-4)  # A fresh model at the tuned rate
model = vit()
pos_init = model.pos_embedding[0, 1:].detach().clone()  # The initial noise
vit = lambda: ViT(**hparams, lr=3e-4, rngs=nnx.Rngs(d2l.get_key()))
model = vit()  # A fresh model at the tuned rate
pos_init = model.pos_embedding[0, 1:]  # The initial noise, a new array

使用 d2l.Trainer 拟合 model 10 个周期,在上采样至 \(96 \times 96\) 的 Fashion-MNIST 图像上可达到约 \(89\%\) 的验证准确率:

trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)
vit_history = trainer.history
vit_params, vit_acc = d2l.num_params(model), vit_history['val_acc'][-1]
print(f'ViT: {vit_params/1e6:.1f}M parameters, '
      f'validation accuracy {vit_acc:.2f}')

ViT: 6.5M parameters, validation accuracy 0.89
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)
vit_history = trainer.history
vit_params, vit_acc = d2l.num_params(model), vit_history['val_acc'][-1]
print(f'ViT: {vit_params/1e6:.1f}M parameters, '
      f'validation accuracy {vit_acc:.2f}')

ViT: 6.5M parameters, validation accuracy 0.89

11.5.3.2 空间位置的作用与学到的二维网格拓扑

若没有 pos_embedding,ViT 对 \(m = 36\) 个图像块是置换不变的:对 36 个图像块做任意置换,只会置换每个注意力矩阵的第 \(1 \dots 36\) 行,而第 \(0\) 行(<cls>)丝毫不变。加入可学习的 pos_embedding 后,图像块 \(k\) 会根据其所处槽位 \(k\) 获得位置向量 \(\mathbf{p}_k\)。我们可以通过在测试时用 5 个随机置换打乱每张验证图像的 36 个图像块(shuffled_accuracy),来检验训练好的 ViT 有多依赖空间布局:

def shuffle_patches(X, perm, p=16):
    """Move the p x p blocks of images X: block perm[k] goes to grid cell k."""
    n, c, h, w = X.shape
    B = X.reshape(n, c, h // p, p, w // p, p).transpose(3, 4)  # Grid of blocks
    B = B.reshape(n, c, -1, p, p)[:, :, perm]  # Blocks in raster order, moved
    B = B.reshape(n, c, h // p, w // p, p, p).transpose(3, 4)
    return B.reshape(X.shape)

def shuffled_accuracy(model, data, perm):
    """Validation accuracy on images whose blocks are moved by perm."""
    return d2l.evaluate_accuracy(model, ((shuffle_patches(X, perm), y)
                                         for X, y in data.val_dataloader()))
def shuffle_patches(X, perm, p=16):
    """Move the p x p blocks of images X: block perm[k] goes to grid cell k."""
    n, h, w, c = X.shape
    B = X.reshape(n, h // p, p, w // p, p, c).swapaxes(2, 3)  # Grid of blocks
    B = B.reshape(n, -1, p, p, c)[:, perm]  # Blocks in raster order, moved
    B = B.reshape(n, h // p, w // p, p, p, c).swapaxes(2, 3)
    return B.reshape(X.shape)

def shuffled_accuracy(model, data, perm):
    """Validation accuracy on images whose blocks are moved by perm."""
    return d2l.evaluate_accuracy(model, ((shuffle_patches(X, perm), y)
                                         for X, y in data.val_dataloader()))

在 \(36\) 个图像块的五个固定随机置换上评估 shuffled_accuracy,度量测试时打乱空间布局后准确率下降的幅度:

rng = np.random.default_rng(0)
perms = [rng.permutation(36) for _ in range(5)]  # Five fixed shuffles
accs = [shuffled_accuracy(model, data, perm) for perm in perms]
print(f'trained ViT: {vit_acc:.3f} as is, '
      f'{min(accs):.2f} to {max(accs):.2f} with its patches shuffled')
trained ViT: 0.888 as is, 0.25 to 0.40 with its patches shuffled
rng = np.random.default_rng(0)
perms = [rng.permutation(36) for _ in range(5)]  # Five fixed shuffles
accs = [shuffled_accuracy(model, data, perm) for perm in perms]
print(f'trained ViT: {vit_acc:.3f} as is, '
      f'{min(accs):.2f} to {max(accs):.2f} with its patches shuffled')
trained ViT: 0.887 as is, 0.36 to 0.45 with its patches shuffled

打乱 \(6 \times 6\) 图像块排列会使验证准确率从约 0.89 骤降至大约 0.25–0.45(视具体置换而定),说明训练好的 ViT 高度依赖每个图像块所在的位置。不过它仍远高于随机猜测的 0.1,因为局部 \(16 \times 16\) 图像块纹理(如鞋跟或衣领形状)本身就能像“图像块袋”一样辨认出许多粗粒度服装类别。

无结构的一维位置表 pos_embedding(\(36 \times d\))真的发现了 \(6 \times 6\) 图像网格的二维几何吗?计算图像块位置向量之间的平均余弦相似度随 \(6 \times 6\) 网格上二维网格距离 \(\max(|r - r'|, |c - c'|)\) 的变化(grid_similarity)即可作答;作为参照,我们对按构造编码了网格的二维正弦编码以及不含网格信息的随机向量计算同一曲线:

def grid_similarity(P):
    """Mean cosine similarity of 36 position embeddings, by grid distance."""
    P = P - P.mean(0)                    # Drop the part shared by all
    P = P / torch.linalg.vector_norm(P, dim=1, keepdim=True)
    sim = P @ P.T                        # (36, 36) cosine similarities
    rows, cols = torch.meshgrid(torch.arange(6), torch.arange(6),
                                indexing='ij')
    ij = torch.stack((rows.flatten(), cols.flatten()), 1)  # Grid cells
    dist = (ij[:, None] - ij[None]).abs().amax(-1)  # Max of the two offsets
    return [float(sim[dist == k].mean()) for k in range(1, 6)]

S = d2l.sinusoidal_encoding(6, 256)      # 1-D codes of the 6 rows/columns
rows, cols = torch.meshgrid(torch.arange(6), torch.arange(6), indexing='ij')
fixed = torch.cat((S[rows.flatten()], S[cols.flatten()]), 1)  # (36, 512)
learned = model.pos_embedding[0, 1:].detach().cpu()  # Drop the cls slot
noise = torch.randn(36, 512)
curves = {'learned': grid_similarity(learned),
          'learned - initial': grid_similarity(learned - pos_init),
          '2-D sinusoidal': grid_similarity(fixed),
          'random': grid_similarity(noise)}
for name, curve in curves.items():
    print(f'{name:>17}:', '  '.join(f'{c:+.2f}' for c in curve))
d2l.plot(list(range(1, 6)), list(curves.values())[:3], 'grid distance',
         'mean cosine similarity', legend=list(curves)[:3])
          learned: +0.04  -0.07  -0.05  -0.05  +0.05
learned - initial: +0.08  -0.10  -0.06  -0.05  +0.15
   2-D sinusoidal: +0.76  +0.21  -0.30  -0.46  -0.36
           random: -0.03  -0.03  -0.03  -0.02  -0.03

def grid_similarity(P):
    """Mean cosine similarity of 36 position embeddings, by grid distance."""
    P = P - P.mean(0)                    # Drop the part shared by all
    P = P / jnp.linalg.norm(P, axis=1, keepdims=True)
    sim = P @ P.T                        # (36, 36) cosine similarities
    rows, cols = jnp.meshgrid(jnp.arange(6), jnp.arange(6), indexing='ij')
    ij = jnp.stack((rows.flatten(), cols.flatten()), 1)  # Grid cells
    dist = jnp.abs(ij[:, None] - ij[None]).max(-1)  # Max of the two offsets
    return [float(sim[dist == k].mean()) for k in range(1, 6)]

S = d2l.sinusoidal_encoding(6, 256)      # 1-D codes of the 6 rows/columns
rows, cols = jnp.meshgrid(jnp.arange(6), jnp.arange(6), indexing='ij')
fixed = jnp.concatenate((S[rows.flatten()], S[cols.flatten()]), 1)  # (36, 512)
learned = model.pos_embedding[0, 1:]     # Drop the cls slot
noise = jax.random.normal(d2l.get_key(), (36, 512))
curves = {'learned': grid_similarity(learned),
          'learned - initial': grid_similarity(learned - pos_init),
          '2-D sinusoidal': grid_similarity(fixed),
          'random': grid_similarity(noise)}
for name, curve in curves.items():
    print(f'{name:>17}:', '  '.join(f'{c:+.2f}' for c in curve))
d2l.plot(list(range(1, 6)), list(curves.values())[:3], 'grid distance',
         'mean cosine similarity', legend=list(curves)[:3])
          learned: +0.05  -0.06  -0.06  -0.05  +0.04
learned - initial: +0.09  -0.09  -0.07  -0.04  +0.13
   2-D sinusoidal: +0.76  +0.21  -0.30  -0.46  -0.36
           random: -0.02  -0.03  -0.03  -0.03  -0.02

经过十个周期后,答案是:几乎没有。相邻图像块(距离 1)与相对边界上的图像块(距离 5)仅比随机向量略相似一点(约 \(+0.05\) 对比 \(-0.03\));中间距离上,学到的曲线略低于零,而且训练在初始噪声之上增加的成分在距离 5 处最大。相比之下,二维正弦编码从距离 1 处的约 \(0.75\) 陡降至远低于零。Dosovitskiy 等 (2021年) 在 ViT 位置嵌入中观察到的清晰二维结构,是在大得多的数据集上经过长得多的训练才涌现出来的。

11.5.4 与参数量匹配的卷积网络对比

在这个 60,000 张图像的数据集上,6.5M 参数的 ViT 与使用完全相同余弦 AdamW 调度训练 10 个周期、参数量匹配的 ResNet 风格卷积基线(CompactResNet,\(\approx 6.5\textrm{M}\) 个参数)相比表现如何?

class CompactResNet(d2l.Classifier):
    """A ResNet-style CNN parameter-matched to the ViT above."""
    configure_optimizers = ViT.configure_optimizers  # The same recipe

    def __init__(self, num_steps, lr=1e-3, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.LazyConv2d(64, kernel_size=7, stride=2, padding=3, bias=False),
            nn.LazyBatchNorm2d(), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
            d2l.Residual(64), d2l.Residual(64),
            d2l.Residual(128, strides=2), d2l.Residual(128),
            d2l.Residual(256, strides=2), d2l.Residual(256),
            d2l.Residual(512, strides=2),
            nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
            nn.LazyLinear(num_classes))

    def forward(self, X):
        return self.net(X)

    def weight_init(self, module):
        # The Trainer calls this after the first minibatch fixed the shapes
        if type(module) in (nn.Linear, nn.Conv2d):
            nn.init.kaiming_normal_(module.weight, nonlinearity='relu')  # He
            if module.bias is not None:
                nn.init.zeros_(module.bias)
class CompactResNet(d2l.Classifier):
    """A ResNet-style CNN parameter-matched to the ViT above."""
    configure_optimizers = ViT.configure_optimizers  # The same recipe

    def __init__(self, num_steps, lr=1e-3, num_classes=10, *, rngs):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        he = nnx.initializers.variance_scaling(2.0, 'fan_in', 'normal')
        self.net = nnx.Sequential(
            # Pad 3 on every side: with stride 2 on even sizes, 'same' pads
            # one more row and column at the bottom and right
            nnx.Conv(1, 64, kernel_size=(7, 7), strides=(2, 2), padding=3,
                     use_bias=False, kernel_init=he, rngs=rngs),
            nnx.BatchNorm(64, momentum=0.9, use_fast_variance=False,
                          rngs=rngs), nnx.relu,
            lambda x: nnx.max_pool(x, window_shape=(3, 3), strides=(2, 2),
                                   padding=((1, 1), (1, 1))),
            d2l.Residual(64, in_channels=64, rngs=rngs),
            d2l.Residual(64, in_channels=64, rngs=rngs),
            d2l.Residual(128, strides=(2, 2), in_channels=64, rngs=rngs),
            d2l.Residual(128, in_channels=128, rngs=rngs),
            d2l.Residual(256, strides=(2, 2), in_channels=128, rngs=rngs),
            d2l.Residual(256, in_channels=256, rngs=rngs),
            d2l.Residual(512, strides=(2, 2), in_channels=256, rngs=rngs),
            lambda x: x.mean(axis=(1, 2)),
            nnx.Linear(512, num_classes, kernel_init=he, rngs=rngs))

    def forward(self, X):
        return self.net(X)

我们创建工厂函数 compact_cnn,并以峰值学习率 \(10^{-3}\) 实例化 cnn:

compact_cnn = lambda: CompactResNet(num_steps, lr=1e-3)  # A fresh CNN
cnn = compact_cnn()
compact_cnn = lambda: CompactResNet(num_steps, lr=1e-3,
                                    rngs=nnx.Rngs(d2l.get_key()))
cnn = compact_cnn()  # A fresh CNN

训练 CompactResNet 10 个周期(并对 CompactResNet 与 ViT 各加跑一个随机种子以检验运行稳定性),在完全相同的 \(6.5\textrm{M}\) 参数预算下对比两种架构:

def final_accuracy(model, data):
    """Validation accuracy after the ten epochs of the first run."""
    trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
    trainer.board.display = False  # No progress plot for the repeats
    trainer.fit(model, data)
    return trainer.history['val_acc'][-1]

trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(cnn, data)
cnn_history = trainer.history
cnn_params, cnn_acc = d2l.num_params(cnn), cnn_history['val_acc'][-1]
cnn_runs = [cnn_acc, final_accuracy(compact_cnn(), data)]  # Run-to-run range
learned_runs = [vit_acc, final_accuracy(vit(), data)]  # A second ViT run
print(f'CNN: {cnn_params/1e6:.1f}M parameters, validation accuracy',
      ', '.join(f'{a:.3f}' for a in cnn_runs))
print(f'ViT: {vit_params/1e6:.1f}M parameters, validation accuracy',
      ', '.join(f'{a:.3f}' for a in learned_runs))

CNN: 6.5M parameters, validation accuracy 0.939, 0.939
ViT: 6.5M parameters, validation accuracy 0.888, 0.889
def final_accuracy(model, data):
    """Validation accuracy after the ten epochs of the first run."""
    trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
    trainer.board.display = False  # No progress plot for the repeats
    trainer.fit(model, data)
    return trainer.history['val_acc'][-1]

trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(cnn, data)
cnn_history = trainer.history
cnn_params, cnn_acc = d2l.num_params(cnn), cnn_history['val_acc'][-1]
cnn_runs = [cnn_acc, final_accuracy(compact_cnn(), data)]  # Run-to-run range
learned_runs = [vit_acc, final_accuracy(vit(), data)]  # A second ViT run
print(f'CNN: {cnn_params/1e6:.1f}M parameters, validation accuracy',
      ', '.join(f'{a:.3f}' for a in cnn_runs))
print(f'ViT: {vit_params/1e6:.1f}M parameters, validation accuracy',
      ', '.join(f'{a:.3f}' for a in learned_runs))

CNN: 6.5M parameters, validation accuracy 0.940, 0.938
ViT: 6.5M parameters, validation accuracy 0.887, 0.892

将 ViT 与 CompactResNet 在 10 个周期内的验证准确率轨迹叠加绘制,可以清楚看到贯穿全程的样本效率差距:

d2l.plot(list(range(1, 11)), [vit_history['val_acc'], cnn_history['val_acc']],
         'epoch', 'validation accuracy', legend=['ViT', 'CNN'])

d2l.plot(list(range(1, 11)), [vit_history['val_acc'], cnn_history['val_acc']],
         'epoch', 'validation accuracy', legend=['ViT', 'CNN'])

在没有数据增强或大规模预训练的 60,000 张图像小数据集上,CompactResNet 收敛更快,最终领先 ViT 约 5 个百分点。这体现了 Dosovitskiy 等 (2021年) 指出的根本权衡:CNN 硬编码的二维局部性与平移等变性在小数据区间提供了强大的归纳偏置,而视觉 Transformer 则从数据中灵活学习空间关系——在无增强小数据集上落后于 CNN,但在数千万张图像上预训练(或结合强数据增强、蒸馏 (Touvron 等 2021年) 或掩蔽图像块重构 (He 等 2022年))时便能追平甚至超越 CNN。

11.5.5 小结

视觉 Transformer(ViT)通过步幅为 \(p\) 的卷积(PatchEmbedding)将形状为 \((C, H, W)\) 的图像转换为 \(m = (H/p)(W/p)\) 个词元的序列,在前端拼接 <cls> 词元,加上学习得到的一维位置嵌入,再送入双向前置规范化 Transformer 编码器(图 11.5.1)。没有位置嵌入时,ViT 对图像块严格置换不变;加入学习的一维位置嵌入后,训练好的模型高度依赖图像块布局,即便在 Fashion-MNIST 上训练十个周期只在位置表上印下了微弱的二维网格痕迹。由于 ViT 缺少卷积内置的二维局部性与平移等变性,在无增强小数据集上从零训练时参数量匹配的 ResNet 表现更优,但 ViT 在大规模预训练下能反超 CNN,并为多模态模型提供统一的词元接口。

11.5.6 练习

  1. 图像块大小 \(p\)、参数量与注意力浮点运算。在我们的 \(96 \times 96\) ViT 中,图像块大小为 \(p = 16\)(\(m = 36\) 块)。

    1. 将图像块大小减半至 \(p = 8\)(\(m = 144\))或缩至四分之一 \(p = 4\)(\(m = 576\))时,PatchEmbedding 的参数量、pos_embedding 的参数量以及 \(L\) 层 ViTBlock 的参数量分别如何变化?
    2. 从 \(p = 16\) 变为 \(p = 8\) 和 \(p = 4\) 时,每层注意力分数矩阵大小 \((m + 1)^2\) 增大多少倍?训练 \(p = 8\) 的 ViT 10 个周期,并将挂钟时间与验证准确率与 \(p = 16\) 对比。
  2. <cls> 读出对比全局平均池化。将 ViT 中的 <cls> 词元读出替换为对 \(m = 36\) 个图像块词元的全局平均池化(self.head(X[:, 1:].mean(1)),或完全移除 cls_token 并对全部 36 个词元求平均)。在 Fashion-MNIST 上训练 10 个周期,并与 <cls> 读出的验证准确率对比。

  3. 无位置嵌入时的精确置换不变性。将 model.pos_embedding 全部置零并将 model 切换至评估模式(关闭暂退法)。在代数上证明并在一个验证批量上以 \(10^{-6}\) 以内的精度数值验证:对 \(\{0, \dots, 35\}\) 的任意置换 perm 施加 shuffle_patches(X, perm),输出对数几率 model(X) 完全不变。

  4. 二维网格发现的统计置换检验。令 \(\Delta\) 表示训练好的 model.pos_embedding 中相邻图像块(网格距离 1)与网格距离 \(\ge 4\) 的图像块在 grid_similarity 上的差值。通过对 pos_embedding 的 36 行做 1,000 次随机置换计算 \(\Delta\) 的零分布,并报告经验 \(p\) 值。学到的位置嵌入中微弱的网格结构是否能与随机机会区分开来?

  5. 亚图像块对比整图像块平移敏感性。在 CNN 中,将输入图像平移 \(s\) 个像素会使内部特征图平移 \(s\) 个像素(在池化步幅意义下)。而在 ViT(\(p = 16\))中,将图像平移 \(s = 16\) 像素(整块宽度)只是把每个图像块移入相邻槽位,而平移 \(s = 8\) 像素(半块)则会切穿每一个 \(16 \times 16\) 图像块边界。在向右平移 \(s \in \{0, 2, 4, 8, 12, 16\}\) 像素(左边界补零)的验证图像上评估已训练的 ViT 与 CompactResNet 的验证准确率。为什么 ViT 在 \(s = 8\) 处相对 \(s = 16\) 出现非单调下凹?

  6. 跨深度的平均注意力距离。Dosovitskiy 等 (2021年) 将一个头的平均注意力距离定义为查询图像块 \(i\) 与键图像块 \(j\) 之间的注意力加权平均二维欧氏像素距离 \(\sum_{i,j=1}^{36} \alpha_{ij} \, d_{\textrm{pixel}}(i, j) / 36\)。计算已训练 ViT 第 1 块与第 2 块中全部 8 个头的平均注意力距离。浅层注意力头是否比深层更偏向局部关注,类似于 CNN 逐步扩大的感受野?

讨论