Lesson 4 of 8 · 2 min
The model
# run locally: vit.py
import torch, torch.nn as nn
class Block(nn.Module):
def __init__(self, d, heads, drop=0.1):
super().__init__()
self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.heads = heads
self.qkv, self.out = nn.Linear(d, 3 * d), nn.Linear(d, d)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Dropout(drop), nn.Linear(4 * d, d))
def attend(self, x):
b, n, d = x.shape
q, k, v = self.qkv(x).reshape(b, n, 3, self.heads, d // self.heads).permute(2, 0, 3, 1, 4)
weights = (q @ k.transpose(-1, -2) / (d // self.heads) ** 0.5).softmax(-1)
return self.out((weights @ v).transpose(1, 2).reshape(b, n, d))
def forward(self, x):
x = x + self.attend(self.n1(x))
return x + self.mlp(self.n2(x))
class ViT(nn.Module):
def __init__(self, size=32, patch=4, d=192, depth=8, heads=6, classes=10):
super().__init__()
n = (size // patch) ** 2
self.patch = nn.Conv2d(3, d, patch, patch)
self.cls = nn.Parameter(torch.zeros(1, 1, d))
self.pos = nn.Parameter(torch.randn(1, n + 1, d) * 0.02)
self.blocks = nn.Sequential(*[Block(d, heads) for _ in range(depth)])
self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, classes))
def forward(self, x):
x = self.patch(x).flatten(2).transpose(1, 2)
x = torch.cat([self.cls.expand(len(x), -1, -1), x], 1) + self.pos
return self.head(self.blocks(x)[:, 0])