11.5  Vision Transformer(ViT)

畳み込みニューラルネットワーク(第 6 章、第 7 章)は、画像に関する 2 つの幾何学的な事前仮定をアーキテクチャに直接組み込んでいる。すなわち、空間的局所性(spatial locality、\(k \times k\) カーネルが隣接するピクセルのみを結合する性質)と平行移動同変性(translation equivariance、同じカーネルの重みがすべての \((r, c)\) 位置にわたってスライドする性質)である。では、2 次元グリッド上の近傍やシフト同変性という概念をまったく組み込んでいない標準的な双方向 Transformer エンコーダ(11.4 節)で、競争力のある画像分類ができるのだろうか。

個々のピクセルに直接自己アテンションを適用すると、計算量はピクセル数の二乗で増大する。\(96 \times 96\) の画像でさえ \(9{,}216\) ピクセルあり、ヘッドあたり \(9216^2 \approx 8.5 \times 10^7\) 個のアテンションペアが生じる。そこで Dosovitskiy ほか (2021年) は Vision Transformer(ViT)(図 11.5.1)を導入し、画像を重なりのない \(p \times p\) のパッチのグリッドへとトークン化した。\(96 \times 96\) の画像は、パッチサイズを \(p = 16\) とすると、\(m = (96 / 16)^2 = 36\) 個のパッチトークンからなる短い系列になる。各パッチを幅 \(d\) に射影し、学習可能な <cls> トークンを先頭に付加し、学習型の 1 次元位置埋め込み(position embedding)を加えたうえで、合計 37 個のトークンを \(L\) 個の双方向 Pre-Norm 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\) の 2 次元畳み込みを適用した後に、高さ \(H/p\)、幅 \(W/p\) の 2 次元空間グリッドを \(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])

4 枚の \(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 Vision Transformer のアーキテクチャ

図 11.5.1: \(96 \times 96\) 画像に対する Vision Transformer。ストライド付き畳み込みによって \(6 \times 6\) グリッドに並ぶ \(16 \times 16\) パッチが 36 個のトークンに変換される。学習された「<cls>」トークンが先頭に付加され、学習された位置埋め込みが加算される。続いて \(L\) 個の Pre-Norm Transformer ブロックが全 37 トークンを処理し、線形ヘッドが「<cls>」トークンの最終表現を分類する。

11.5.2.1 エンコーダブロック(ViTBlock)

Dosovitskiy ほか (2021年) に従い、ViTBlock は設定可能な d2l.TransformerBlock(11.1 節)を継承し、Pre-Norm の LayerNorm と、GELU を活性化関数とする 2 層の多層パーセプトロン(multilayer perceptron、MLP、隠れ層幅は mlp_num_hiddens)を用いる。デフォルトではアテンションの射影にバイアスを持たせない(use_bias=False)一方、MLP の 2 つの線形層と 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 は学習可能なパラメータベクトル cls_token(形状 \((1, 1, d)\))をインデックス \(0\) の先頭に付加し、学習可能な位置埋め込みテーブル pos_embedding(形状 \((1, m + 1, d)\))を \(m + 1\) 個の位置すべてに加算する。そのうえで \(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 最初の実行

2 ブロックの ViT(\(d = 512, d_{\textrm{mlp}} = 2048, H = 8, L = 2, p = 16\)、パラメータ数 \(\approx 6.5\textrm{M}\))を、\(96 \times 96\) の Fashion-MNIST 上で 10 エポック訓練する。最適化には線形ウォームアップとコサイン学習率減衰を伴う AdamW(\(\lambda = 0.05\))を用いる。

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

model を 10 エポックにわたり d2l.Trainer で適合させると、検証正解率は約 \(89\%\) に達する(アップサンプリングされた \(96 \times 96\) の Fashion-MNIST 画像での評価)。

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 空間位置の役割と学習された 2 次元グリッドのトポロジー

pos_embedding がなければ、ViT は \(m = 36\) 個のパッチに対して置換不変(permutation-invariant)である。36 個のパッチをどのように置換しても、すべてのアテンション行列の \(1 \dots 36\) 行目が同じように置換されるだけで、\(0\) 行目(<cls>)は文字通りまったく変化しないからである。学習された pos_embedding がある場合、パッチ \(k\) は位置ベクトル \(\mathbf{p}_k\) を配置先のスロット \(k\) に応じて受け取る。訓練済みの ViT が空間配置にどれだけ依存しているかを検証するため、テスト時に各検証画像の 36 個のパッチを 5 通りのランダムな順列で並べ替える(shuffled_accuracy)。

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()))

shuffled_accuracy を \(36\) 個のパッチに対する 5 通りの固定されたランダム順列にわたって評価し、テスト時に空間配置をかき混ぜたときに正解率がどれだけ急激に低下するかを計測する。

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\) パッチのテクスチャだけでも、「パッチの集合(bag of patches)」として大まかな衣類クラスの多くを識別できるからである。

構造を持たない 1 次元の位置テーブル pos_embedding(\(36 \times d\))は、\(6 \times 6\) の画像グリッドが持つ 2 次元の幾何構造を実際に発見しているのだろうか。パッチの位置ベクトル間の平均コサイン類似度を、2 次元グリッド距離 \(\max(|r - r'|, |c - c'|)\)(\(6 \times 6\) グリッド上)の関数として計算すれば(grid_similarity)、この問いに答えられる。比較のため、構造上グリッドを最初からエンコードしている 2 次元正弦波符号と、そうではないランダムなベクトルについても同じ曲線を計算する。

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

10 エポック後の答えは「ごくわずか」である。隣接するパッチ(距離 1)と反対側の端にあるパッチ(距離 5)は、ランダムなベクトルよりもわずかに類似度が高くなるが(約 \(+0.05\) 対 \(-0.03\))、その中間の距離では学習された曲線は 0 をわずかに下回り、初期ノイズに訓練が付け加えた変化量は距離 5 で最大となる。対照的に、2 次元正弦波符号は距離 1 での約 \(0.75\) から 0 を大きく下回る値まで低下する。Dosovitskiy ほか (2021年) が ViT の位置埋め込みに見出した明瞭な 2 次元構造は、はるかに大規模なデータセットではるかに長く訓練することで初めて現れるものである。

11.5.4 パラメータ数を揃えた畳み込みネットワークとの比較

この 6.5M パラメータの ViT は、60,000 枚の画像からなるこのデータセットにおいて、パラメータ数を揃えた ResNet 風の畳み込みベースライン(CompactResNet、パラメータ数 \(\approx 6.5\textrm{M}\))をまったく同じコサイン減衰付きの AdamW スケジュールで 10 エポック訓練した場合と比べるとどうなるだろうか。

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 を作成し、cnn をピーク学習率 \(10^{-3}\) でインスタンス化する。

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 の両方で 2 つ目のシードでも訓練し)、まったく同じ \(6.5\textrm{M}\) パラメータの予算で 2 つのアーキテクチャを比較する。

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

10 エポックにわたる ViT と CompactResNet の検証正解率の軌跡を重ねてプロットすると、訓練全体を通じたサンプル効率の差が浮き彫りになる。

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 にハードコードされた 2 次元の局所性と平行移動同変性は小規模データ領域において強力な帰納バイアス(inductive bias)を与える一方、Vision Transformer は空間的な関係をデータから柔軟に学習するため、データ拡張なしの小さなデータセットでは CNN に後れを取るものの、数千万枚の画像で事前学習した場合(あるいは強力なデータ拡張、蒸留 (Touvron ほか 2021年)、マスク付きパッチ再構成 (He ほか 2022年) を用いて訓練した場合)には CNN に匹敵するか、それを凌駕する。

11.5.5 まとめ

Vision Transformer(ViT)は、形状 \((C, H, W)\) の画像を \(m = (H/p)(W/p)\) 個のトークンからなる系列へとストライド \(p\) の畳み込み(PatchEmbedding)によって変換し、先頭に <cls> トークンを付加し、学習型の 1 次元位置埋め込みを加算したうえで、双方向の Pre-Norm Transformer エンコーダを適用する(図 11.5.1)。位置埋め込みがなければ、ViT はパッチに対して厳密に置換不変である。一方、学習型の 1 次元位置埋め込みを用いると、Fashion-MNIST 上での 10 エポックの訓練では位置テーブルに 2 次元グリッドがわずかに刻まれるにすぎないものの、訓練済みモデルはパッチ配置に強く依存するようになる。ViT は畳み込みのような組み込みの 2 次元の局所性や平行移動同変性を持たないため、データ拡張なしの小さなデータセットでゼロから訓練するとパラメータ数を揃えた ResNet の方が高い性能を示すが、大規模な事前学習スケールでは ViT が CNN を追い抜き、さらにマルチモーダルモデルに対する統一されたトークンインターフェースを提供する。

11.5.6 演習問題

  1. パッチサイズ \(p\)、パラメータ数、およびアテンションの FLOPs。本節の \(96 \times 96\) 画像向け ViT では、パッチサイズは \(p = 16\)(\(m = 36\) パッチ)である。

    1. PatchEmbedding のパラメータ数、pos_embedding のパラメータ数、および \(L\) 層の ViTBlock のパラメータ数は、パッチサイズを \(p = 8\)(\(m = 144\))に半減させたとき、あるいは \(p = 4\)(\(m = 576\))に 4 分の 1 にしたとき、それぞれどのように変化するか。
    2. 層あたりのアテンションスコア行列のサイズ \((m + 1)^2\) は、\(p = 16\) から \(p = 8\) および \(p = 4\) にすると何倍に増大するか。\(p = 8\) の ViT を 10 エポック訓練し、その実経過時間と検証正解率を \(p = 16\) の場合と比較せよ。
  2. <cls> 読み出し対グローバル平均プーリング。<cls> トークンによる ViT の読み出しを、\(m = 36\) 個のパッチトークンにわたるグローバル平均プーリングに置き換えよ(self.head(X[:, 1:].mean(1)) とするか、cls_token を完全に削除して全 36 個のトークンを平均する)。Fashion-MNIST 上で 10 エポック訓練し、検証正解率を <cls> 読み出しと比較せよ。

  3. 位置埋め込みなしでの厳密な置換不変性。model.pos_embedding をすべてゼロに設定し、model を評価モードに切り替えよ(ドロップアウトを無効化する)。次の性質を代数的に証明するとともに、検証バッチ上で誤差 \(10^{-6}\) 以内の精度で数値的に確認せよ。すなわち、shuffle_patches(X, perm) を任意の順列 perm(\(\{0, \dots, 35\}\) 上の置換)に対して適用しても、出力ロジット model(X) はまったく変化しない。

  4. 2 次元グリッド発見に関する統計的置換検定。\(\Delta\) を、隣接パッチ(グリッド距離 1)とグリッド距離 \(\ge 4\) のパッチとの間での grid_similarity の差(訓練済みの model.pos_embedding に対する値)とする。\(\Delta\) の帰無分布を、pos_embedding の 36 行に対する 1,000 通りのランダムな順列にわたって計算し、経験 \(p\) 値を報告せよ。学習された位置埋め込みの微弱なグリッド構造は、偶然と区別できるか。

  5. サブパッチ単位対パッチ単位の平行移動感度。CNN では、入力画像を \(s\) ピクセル平行移動させると、内部の特徴マップも(プーリングのストライドを除けば)\(s\) ピクセル平行移動する。一方、ViT(\(p = 16\))では、画像を \(s = 16\) ピクセル(1 パッチ幅ちょうど)平行移動させても各パッチが隣接するパッチスロットへ移るだけであるのに対し、\(s = 8\) ピクセル(半パッチ分)平行移動させるとすべての \(16 \times 16\) パッチ境界を横切ることになる。訓練済みの ViT と CompactResNet の検証正解率を、右へ \(s \in \{0, 2, 4, 8, 12, 16\}\) ピクセル平行移動させた検証画像(左端はゼロパディングする)上で評価せよ。なぜ ViT は \(s = 8\) において \(s = 16\) と比べ非単調な落ち込みを示すのか。

  6. 深さにわたる平均アテンション距離。@Dosovitskiy.Beyer.Kolesnikov.ea.2021 は、各ヘッドの平均アテンション距離を、アテンション重みで加重平均した 2 次元ユークリッドピクセル距離 \(\sum_{i,j=1}^{36} \alpha_{ij} \, d_{\textrm{pixel}}(i, j) / 36\)(クエリパッチ \(i\) とキーパッチ \(j\) の間の距離)として定義している。訓練済みの ViT のブロック 1 とブロック 2 に含まれる各 8 個のヘッドについて、平均アテンション距離を計算せよ。CNN で受容野が拡大していくのと同様に、浅い層のヘッドは深い層のヘッドよりも局所的にアテンションを向けているか。

ディスカッション