Lesson 5 of 8 · 2 min
Train it
Transformers have little built-in sense of pictures, so augmentation matters a lot on small data.
# run locally: train.py
import torch, torchvision as tv, torchvision.transforms as T
from vit import ViT
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
norm = T.Normalize((0.49, 0.48, 0.45), (0.25, 0.24, 0.26))
train_tf = T.Compose([T.RandomCrop(32, 4), T.RandomHorizontalFlip(), T.RandAugment(), T.ToTensor(), norm])
test_tf = T.Compose([T.ToTensor(), norm])
load = lambda train, tf: torch.utils.data.DataLoader(tv.datasets.CIFAR10("data", train, tf, download=True), 256, shuffle=train, num_workers=2)
if __name__ == "__main__":
tr, te = load(True, train_tf), load(False, test_tf)
net = ViT().to(device)
epochs = 60
opt = torch.optim.AdamW(net.parameters(), lr=1e-3, weight_decay=0.05)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, 1e-3, total_steps=epochs * len(tr))
loss_fn = torch.nn.CrossEntropyLoss(label_smoothing=0.1)
best = 0
for epoch in range(epochs):
net.train()
for x, y in tr:
opt.zero_grad()
loss_fn(net(x.to(device)), y.to(device)).backward()
torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0)
opt.step(); sched.step()
net.eval()
with torch.no_grad():
right = sum((net(x.to(device)).argmax(1).cpu() == y).sum().item() for x, y in te)
if right > best:
best = right
torch.save(net.state_dict(), "vit.pt")
print(epoch, f"{right / 100:.2f}%")