11.5  비전 트랜스포머(ViT)

합성곱 신경망(6장, 7장)은 이미지에 관한 두 가지 기하학적 사전 지식을 아키텍처에 직접 내장합니다. 바로 공간적 국소성(spatial locality)(\(k \times k\) 커널이 이웃 픽셀들만 결합함)과 평행이동 등변성(translation equivariance)(동일한 커널 가중치가 모든 \((r, c)\) 위치를 가로질러 슬라이딩함)입니다. 그렇다면 2차원 격자 이웃이나 이동 등변성에 대한 내장 개념이 전혀 없는 표준 양방향 트랜스포머 인코더(11.4절)로도 이미지를 경쟁력 있게 분류할 수 있을까요?

개별 픽셀에 셀프 어텐션을 직접 적용하면 픽셀 수의 제곱으로 연산량이 불어납니다. 단 \(96 \times 96\) 이미지조차 \(9{,}216\) 개의 픽셀을 가져 헤드당 어텐션 쌍이 \(9216^2 \approx 8.5 \times 10^7\) 개에 달합니다. Dosovitskiy 기타 (2021년) 에서는 이미지를 겹치지 않는 \(p \times p\) 패치(patch) 격자로 토큰화하는 비전 트랜스포머(Vision Transformer, ViT)(그림 11.5.1)를 제안했습니다. 패치 크기 \(p = 16\) 을 쓰면 \(96 \times 96\) 이미지는 \(m = (96 / 16)^2 = 36\) 개의 패치 토큰으로 이루어진 짧은 시퀀스가 됩니다. 각 패치를 폭 \(d\) 로 투영하고 맨 앞에 학습 가능한 <cls> 토큰을 붙인 뒤 학습된 1차원 위치 임베딩을 더하면, 총 37개의 토큰이 \(L\) 개의 양방향 사전 정규화 트랜스포머 블록을 통과합니다.

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)\) 의 토큰 벡터 시퀀스로 평탄화(flattening)하는 것과 완전히 동일합니다.

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

패치 크기 \(p = 16\) 으로 \(96 \times 96\) 단일 채널 이미지 4장짜리 미니배치를 통과시키면 PatchEmbedding은 폭 \(d = 512\) 인 패치 토큰 \((96 / 16)^2 = 36\) 개를 출력합니다.

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 비전 트랜스포머 아키텍처

그림 11.5.1: \(96 \times 96\) 이미지 위의 비전 트랜스포머. 스트라이드 합성곱이 \(16 \times 16\) 패치들의 \(6 \times 6\) 격자를 36개의 토큰으로 변환합니다. 학습된 “<cls>” 토큰을 맨 앞에 붙이고 학습된 위치 임베딩을 더한 뒤, \(L\) 개의 사전 정규화 트랜스포머 블록이 37개 토큰 전체를 처리하며 선형 헤드가 “<cls>” 토큰의 최종 표현을 분류합니다.

11.5.2.1 인코더 블록(ViTBlock)

Dosovitskiy 기타 (2021년) 의 설계를 따라 ViTBlock은 설정 가능한 d2l.TransformerBlock(11.1절)을 상속받아 사전 정규화 LayerNorm과 사용자 지정 은닉 폭 mlp_num_hiddens를 갖는 2층 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 첫 번째 학습 실행

선형 웜업과 코사인 학습률 감쇠를 결합한 AdamW(\(\lambda = 0.05\))를 사용해 \(96 \times 96\) Fashion-MNIST에서 2-블록 ViT(\(d = 512, d_{\textrm{mlp}} = 2048, H = 8, L = 2, p = 16\), 약 \(\approx 6.5\textrm{M}\) 개 매개변수)를 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 공간 위치의 역할과 학습된 2차원 격자 위상

pos_embedding이 없다면 ViT는 \(m = 36\) 개 패치에 대해 순열 불변(permutation-invariant)입니다. 36개 패치를 어떻게 뒤섞어도 모든 어텐션 행렬의 \(1 \dots 36\) 번 행만 치환될 뿐 \(0\) 번 행(<cls>)은 문자 그대로 조금도 변하지 않기 때문입니다. 학습된 pos_embedding이 있으면 패치 \(k\) 는 자신이 놓인 슬롯 \(k\) 에 따라 위치 벡터 \(\mathbf{p}_k\) 를 부여받습니다. 테스트 시점에 각 검증 이미지의 36개 패치를 무작위 순열 5가지로 뒤섞어 봄으로써(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\) 패치 질감만으로도 “패치 가방(bag of patches)”처럼 대략적인 의류 부류 상당수를 식별할 수 있기 때문입니다.

그렇다면 구조가 부여되지 않은 1차원 위치 테이블 pos_embedding(\(36 \times d\))은 실제로 \(6 \times 6\) 이미지 격자의 2차원 기하학을 스스로 발견했을까요? \(6 \times 6\) 격자 위의 2차원 격자 거리 \(\max(|r - r'|, |c - c'|)\) 의 함수로 패치 위치 벡터 간 평균 코사인 유사도를 계산(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.03\) 대비 약 \(+0.05\))를 보일 뿐, 그 사이 구간에서 학습된 곡선은 0보다 살짝 아래에 머무르며 초기 잡음 위에 학습이 더한 변화량도 거리 5에서 가장 큽니다. 반면 2차원 사인파 코드는 거리 1의 약 \(0.75\) 에서 0 한참 아래까지 매끄럽게 떨어집니다. Dosovitskiy 기타 (2021년) 에서 ViT 위치 임베딩으로부터 확인한 선명한 2차원 구조는 훨씬 더 큰 데이터셋에서 훨씬 더 오래 학습할 때 비로소 나타납니다.

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에 하드코딩된 2차원 국소성과 평행이동 등변성은 소규모 데이터 영역에서 강력한 귀납적 편향(inductive bias)을 제공하는 반면, 비전 트랜스포머는 데이터로부터 공간적 관계를 유연하게 학습합니다. 그래서 증강 없는 소규모 데이터셋에서는 CNN에 뒤처지지만, 수천만 장의 이미지에서 사전학습하거나(또는 강력한 데이터 증강, 지식 증류 (Touvron 기타 2021년), 마스크 패치 복원 (He 기타 2022년) 으로 학습할 때) CNN과 대등해지거나 이를 능가합니다.

11.5.5 요약

비전 트랜스포머(ViT)는 스트라이드-\(p\) 합성곱(PatchEmbedding)으로 형상 \((C, H, W)\) 의 이미지를 길이 \(m = (H/p)(W/p)\) 의 토큰 시퀀스로 변환하고, <cls> 토큰을 맨 앞에 붙인 뒤 학습된 1차원 위치 임베딩을 더해 양방향 사전 정규화 트랜스포머 인코더를 적용합니다(그림 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. 패치 크기를 \(p = 8\)(\(m = 144\))로 절반 줄이거나 \(p = 4\)(\(m = 576\))로 4분의 1로 줄일 때 PatchEmbedding의 매개변수 수, pos_embedding의 매개변수 수, 그리고 \(L\) 개 ViTBlock 층의 매개변수 수는 각각 어떻게 변합니까?
    2. 층당 어텐션 점수 행렬 크기 \((m + 1)^2\) 은 \(p = 16\) 에서 \(p = 8\) 및 \(p = 4\) 로 갈 때 몇 배씩 커집니까? \(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을 모두 0으로 설정하고 model을 평가 모드로 전환하여 드롭아웃을 비활성화하십시오. \(\{0, \dots, 35\}\) 의 임의의 순열 perm에 대해 shuffle_patches(X, perm)를 적용해도 출력 로짓 model(X)가 전혀 변하지 않음을 대수적으로 증명하고, 검증 배치 위에서 \(10^{-6}\) 오차 이내로 수치 검증하십시오.

  4. 2차원 격자 발견에 대한 통계적 순열 검정. 학습된 model.pos_embedding에서 인접 패치(격자 거리 1)와 격자 거리 \(\ge 4\) 인 패치 사이의 grid_similarity 차이를 \(\Delta\) 라 합시다. pos_embedding의 36개 행을 무작위로 1,000번 치환하여 \(\Delta\) 의 귀무 분포를 구하고 경험적 \(p\)-값을 보고하십시오. 학습된 위치 임베딩의 희미한 격자 구조는 우연과 통계적으로 구별됩니까?

  5. 부패치(sub-patch) 이동 대 전체 패치 단위 평행이동 민감도. CNN에서 입력 이미지를 \(s\) 픽셀 이동시키면(풀링 스트라이드 범위 내에서) 내부 특성 맵도 \(s\) 픽셀 이동합니다. 반면 ViT(\(p = 16\))에서는 이미지를 \(s = 16\) 픽셀(패치 한 칸 전체 폭) 이동시키면 각 패치가 단순히 이웃 패치 슬롯으로 한 칸씩 밀릴 뿐이지만, \(s = 8\) 픽셀(반 패치) 이동시키면 모든 \(16 \times 16\) 패치 경계가 가로질러 잘립니다. 왼쪽 테두리를 0으로 패딩하면서 오른쪽으로 \(s \in \{0, 2, 4, 8, 12, 16\}\) 픽셀 이동시킨 검증 이미지들에서 학습된 ViT와 CompactResNet의 검증 정확도를 평가하십시오. 왜 ViT는 \(s = 16\) 에 비해 \(s = 8\) 에서 비단조적인 정확도 하락을 보입니까?

  6. 깊이에 따른 평균 어텐션 거리. Dosovitskiy 기타 (2021년) 에서는 헤드의 평균 어텐션 거리를 쿼리 패치 \(i\) 와 키 패치 \(j\) 사이의 어텐션 가중 평균 2차원 유클리드 픽셀 거리 \(\sum_{i,j=1}^{36} \alpha_{ij} \, d_{\textrm{pixel}}(i, j) / 36\) 으로 정의합니다. 학습된 ViT의 1번 및 2번 블록에 속한 8개 헤드 각각의 평균 어텐션 거리를 계산하십시오. CNN의 점진적으로 넓어지는 수용 영역과 유사하게 초기 층 헤드들이 깊은 층 헤드들보다 더 국소적으로 어텐션을 기울입니까?

토론