Vision Transformer in PyTorch: Fine-Tune a Small ViT Step by Step

How do you fine-tune a vision transformer in PyTorch?
To fine-tune a vision transformer in PyTorch (an image model that reads a photo as small square pieces), load one pretrained on general photos and give it a new last layer for your classes.
In our run, the cheap option won: train only the new layer first, and retrain the whole model only if it clearly beats it on photos the model has not seen.
That is how a photo-sorting app learns your labels, here 37 pet breeds. On our MacBook Air M4, training only the new layer labelled 90.73 % of the test photos correctly; retraining the whole model, 89.72 %.
An image classifier is built in stages: someone pre-trains a model on a large general photo set, you fine-tune it (continue its training on your own smaller set), and your app calls it on new photos. This guide is the middle stage, for a vision transformer.
How a ViT reads an image: how image patches replaced convolutions. Its parts: patch embeddings, class tokens and positional encoding.
The task: sort pet photos by breed
The example app sorts cat and dog photos from the Oxford-IIIT Pet set (licence CC BY-SA 4.0, commercial and research use; the copyright of the images stays with their owners) into 37 breeds.
A linear probe trains only a new final layer on top of a frozen model, whose weights stay fixed. A full fine-tune retrains every weight, every number the network learned.
What you need
Save this block as requirements.txt; the complete train.py is under The full script.
numpy==2.5.5
pillow==13.0.0
timm==1.0.31
torch==2.15.0
torchvision==0.29.2
# install (Python 3.13.14, macOS 26.4.1, MacBook Air M4):
# python3 -m venv venv && ./venv/bin/pip install -r requirements.txt
# run (the dataset downloads into ./data on the first run):
# ./venv/bin/python train.py --mode probe --seed 0
# ./venv/bin/python train.py --mode finetune --seed 0
Step 1: Load the pretrained ViT with a new 37-class head
torchvision ships ViT only from the base size up; the tiny one comes from timm, a PyTorch library of pretrained image models. One call downloads it from the Hugging Face Hub (a public store of model files) and swaps its head, the final layer that scores each breed:
TAG = 'vit_tiny_patch16_224.augreg_in21k_ft_in1k'
model = timm.create_model(TAG, pretrained=True, num_classes=37)
The unauthenticated-request warning is harmless.
Step 2: Prepare the photos with the model’s own transforms
A pretrained model expects photos resized and colour-scaled as in its training. Ask the model for those settings:
cfg = timm.data.resolve_model_data_config(model)
tf_train = timm.data.create_transform(**cfg, is_training=True)
tf_eval = timm.data.create_transform(**cfg, is_training=False)
The script prints them. Only training photos get random crops, flips and colour jitter.
device mps params 5531557 cfg {'input_size': (3, 224, 224), 'interpolation': 'bicubic', 'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5), 'crop_pct': 0.9, 'crop_mode': 'center'}
Then split them. Training photos teach. Validation photos, a fixed slice of each breed, pick the best epoch (one pass over the training photos). The official test photos are scored once, at the end.
full_tr = OxfordIIITPet('data', split='trainval', transforms=None, download=True)
labels = np.array(full_tr._labels)
rng = np.random.RandomState(0) # the split seed never changes
val_idx = []
for c in range(37):
idx = rng.permutation(np.where(labels == c)[0])
val_idx += list(idx[:max(1, round(0.1 * len(idx)))])
tr_idx = sorted(set(range(len(labels))) - set(val_idx))
test = OxfordIIITPet('data', split='test', download=True)
The script prints the split sizes:
train 3311 val 369 test 3669
Step 3: Train only the head (the linear probe)
Freeze every weight except the head’s:
if a.mode == 'probe':
for n, q in model.named_parameters(): q.requires_grad = n.startswith('head')
Run ./venv/bin/python train.py --mode probe --seed 0. These two lines of the log show how few weights train and the test score:
trainable 7141 lr 0.001 wd 0.05 bs 32 epochs 5 warmup 50
RESULT mode=probe seed=0 test_acc=90.73
Step 4: Fine-tune the whole model
Same script, nothing frozen. The learning rate (the size of each weight update) is smaller than the probe’s. It rises during a short warm-up, then falls along a cosine curve:
lr = a.lr or (1e-3 if a.mode == 'probe' else 1e-4)
opt = torch.optim.AdamW(params, lr=lr, weight_decay=a.wd)
total = a.epochs * len(tr_dl)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: (s + 1) / a.warmup if s < a.warmup else 0.5 * (1 + math.cos(math.pi * (s - a.warmup) / (total - a.warmup))))
Run ./venv/bin/python train.py --mode finetune --seed 0. We tuned none of these values.
Step 5: Compare both with a trivial baseline on the test set
The trivial baseline always answers the most common training breed:
tr_labels = labels[tr_idx]; maj = np.bincount(tr_labels).argmax()
print('majority class acc on test: %.2f' % (100 * np.mean(np.array(test._labels) == maj)))
Both runs print it before training:
majority class acc on test: 2.67
| Method | What trains | Labelled correctly: validation, 369 photos (one photo = 0.27 points) | Test, 3,669 photos |
|---|---|---|---|
| Always the most common breed | nothing | – | 2.67 % |
| Linear probe | the head, 7,141 weights | 91.60 % | 90.73 % |
| Full fine-tune | all 5,531,557 weights | 92.68 % | 89.72 % |
Guessing earns almost nothing, so both trained models learned breeds. On the test photos, the probe edged ahead.
Step 6: Decide which one to keep
On validation the order flipped, by 4 photos (1.08 points). With a gap that small, a handful of photos decides the ranking, so we do not read anything into it.
Our advice from this run: start with the probe, it trains faster and leaves the pretrained model untouched. Fine-tune everything only when it clearly beats the probe on enough held-out photos. Our result holds for this set, model and settings only.
Mistakes that skew the score or crash the run
- Copied colour-scaling numbers. torchvision’s ViT scales colours with different numbers than this timm model. Fix: use
resolve_model_data_config. - Checking the test score repeatedly. You start tuning toward those photos. Fix: score it once, at the end.
- Judging on a tiny validation split. See Step 6. Fix: decide on more held-out photos.
DataLoaderworkers on macOS. Withoutif __name__ == "__main__":, they do not start cleanly, because Python on macOS usesspawnby default (Python docs). Fix: callmain()under that guard, with the dataset class at module level.
If you only wanted to fine-tune a small vision transformer on your own photos, you can stop here.
Our run’s setup and timing
- Python 3.11 or newer (torch 2.15.0 requires it; we used 3.13.14). The install command pins the versions we used on 2026-12-01.
- An Apple-silicon Mac on macOS 15 or newer, where PyTorch uses the GPU through its
mpsdevice, or a CPU, which we did not run. - On our M4 the probe trained in 40 to 56 s, the full fine-tune in 138 to 170 s.
What the head actually reads
Inside, the model cuts each photo into patches, small squares of the image, and turns each patch into a token, a list of numbers. Every token then weighs every other token and mixes in what it finds relevant; that step is attention. One extra learned token, the class token, collects the result, and the head reads its final numbers.
That explains the probe’s 7,141 weights. The class token of this model ends as 192 numbers, and the new head has one weight per number per breed plus one offset per breed: 192 × 37 + 37.
Other model designs, such as state-space models, have their own topic pages.
How much the numbers move between runs
A seed is the starting number of the random generator. It sets the head’s random start, the order of the training photos and the random crops; the validation slice keeps its own fixed seed.
Two full fine-tunes with seed 0 on MPS printed the same loss, validation and test numbers to the shown decimals. We did not compare the weights bit by bit.
Seed 1 moved the full fine-tune’s test score by 0.92 points (89.72 % to 88.80 %, which is 34 photos) and the probe’s by 0.41 points (90.73 % to 90.32 %).
The probe led with both seeds, by 1.0 and 1.5 points. That gap is larger than the seed shift, but two runs per method are too few to measure the spread.
Training time varied by 23 % (full fine-tune, 138 to 170 s) to 38 % (probe, 40 to 56 s) between runs on the same laptop; one probe run shared the machine with other work. Treat our times as a range.
What larger published runs reached
The ViT authors (Dosovitskiy et al., ICLR 2021) fine-tuned ViT-B/16 pre-trained on ImageNet-21k, a set of 14 million labelled photos. At 384-pixel resolution it reached 94.43 % on Oxford-IIIT Pets and 98.95 % on CIFAR-10, a set of small photos in ten classes.
That model has about 86 million weights against our 5.5 million and saw larger images, so the numbers do not compare directly with ours.
Their recipe differs too: cosine decay, a batch of 512 photos per update, no weight decay (a pull of the weights toward zero), and a learning rate picked from four values for Pets. We used a batch of 32, weight decay 0.05, and no search.
The same authors write that fine-tuning at a higher resolution than pre-training is often beneficial.
Why start from a pretrained model at all? The AugReg authors (Steiner et al., 2022) searched training recipes for ViT-B/32 and ViT-B/16 on Pets, which has about 3,000 training images. They write that, however long the training, it does not seem possible to train ViT models from scratch to reach accuracy anywhere near that of transferred models.
They also recommend ImageNet-21k checkpoints, which is why we chose a timm model pre-trained on that set (then fine-tuned on ImageNet-1k). The pet photos and their licence are on the Oxford-IIIT Pet page.
Whether a ViT is the right model at all, and what it needs that a CNN (a network that slides small filters over the image) does not, is in what a ViT needs that a CNN does not.
The full script
This is train.py exactly as it ran on our M4:
import argparse, copy, math, random, time
import numpy as np, timm, torch
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import OxfordIIITPet
class T(torch.utils.data.Dataset):
def __init__(s, base, idx, tf): s.b, s.i, s.tf = base, idx, tf
def __len__(s): return len(s.i)
def __getitem__(s, k):
img, y = s.b[s.i[k]]
return s.tf(img.convert('RGB')), y
def main():
p = argparse.ArgumentParser()
p.add_argument('--mode', choices=['probe', 'finetune'], required=True)
p.add_argument('--seed', type=int, default=0)
p.add_argument('--epochs', type=int, default=5)
p.add_argument('--lr', type=float, default=None)
p.add_argument('--wd', type=float, default=0.05)
p.add_argument('--bs', type=int, default=32)
p.add_argument('--warmup', type=int, default=50) # steps
a = p.parse_args()
lr = a.lr or (1e-3 if a.mode == 'probe' else 1e-4)
random.seed(a.seed); np.random.seed(a.seed); torch.manual_seed(a.seed)
dev = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
TAG = 'vit_tiny_patch16_224.augreg_in21k_ft_in1k'
model = timm.create_model(TAG, pretrained=True, num_classes=37)
cfg = timm.data.resolve_model_data_config(model)
print('device', dev, 'params', sum(p.numel() for p in model.parameters()), 'cfg', cfg)
tf_train = timm.data.create_transform(**cfg, is_training=True)
tf_eval = timm.data.create_transform(**cfg, is_training=False)
full_tr = OxfordIIITPet('data', split='trainval', transforms=None, download=True)
labels = np.array(full_tr._labels)
rng = np.random.RandomState(0) # the split seed never changes
val_idx = []
for c in range(37):
idx = rng.permutation(np.where(labels == c)[0])
val_idx += list(idx[:max(1, round(0.1 * len(idx)))])
tr_idx = sorted(set(range(len(labels))) - set(val_idx))
test = OxfordIIITPet('data', split='test', download=True)
ld = lambda ds, sh: DataLoader(ds, batch_size=a.bs, shuffle=sh, num_workers=4, persistent_workers=True)
tr_dl = ld(T(full_tr, tr_idx, tf_train), True)
va_dl = ld(T(full_tr, sorted(val_idx), tf_eval), False)
te_dl = ld(T(test, list(range(len(test))), tf_eval), False)
print('train', len(tr_idx), 'val', len(val_idx), 'test', len(test))
# (a) majority class on test
tr_labels = labels[tr_idx]; maj = np.bincount(tr_labels).argmax()
print('majority class acc on test: %.2f' % (100 * np.mean(np.array(test._labels) == maj)))
model.to(dev)
if a.mode == 'probe':
for n, q in model.named_parameters(): q.requires_grad = n.startswith('head')
params = [q for q in model.parameters() if q.requires_grad]
print('trainable', sum(q.numel() for q in params), 'lr', lr, 'wd', a.wd, 'bs', a.bs, 'epochs', a.epochs, 'warmup', a.warmup)
opt = torch.optim.AdamW(params, lr=lr, weight_decay=a.wd)
total = a.epochs * len(tr_dl)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: (s + 1) / a.warmup if s < a.warmup else 0.5 * (1 + math.cos(math.pi * (s - a.warmup) / (total - a.warmup))))
@torch.no_grad()
def acc(dl):
model.eval(); ok = n = 0
for x, y in dl:
ok += (model(x.to(dev)).argmax(1).cpu() == y).sum().item(); n += len(y)
return 100 * ok / n
best, best_sd, t0, seen = -1, None, time.time(), 0
for ep in range(a.epochs):
model.train()
if a.mode == 'probe': model.eval() # frozen backbone, no dropout
te = time.time(); tl = 0
for x, y in tr_dl:
x, y = x.to(dev), y.to(dev)
loss = torch.nn.functional.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward(); opt.step(); sched.step()
tl += loss.item() * len(y); seen += len(y)
va = acc(va_dl)
print('epoch %d loss %.4f val_acc %.2f time %.1fs (%.0f img/s train+val)' % (ep + 1, tl / len(tr_idx), va, time.time() - te, (len(tr_idx)) / (time.time() - te)), flush=True)
if va > best: best, best_ep, best_sd = va, ep + 1, copy.deepcopy(model.state_dict())
model.load_state_dict(best_sd)
print('best val %.2f at epoch %d; train time %.1fs' % (best, best_ep, time.time() - t0))
print('RESULT mode=%s seed=%d test_acc=%.2f' % (a.mode, a.seed, acc(te_dl)))
if __name__ == '__main__':
main()
When it breaks: the AugReg authors describe Pets as relatively similar to ImageNet-1k, the set our model was last tuned on. Our expectation, not tested: on photos unlike ImageNet, such as screenshots or line drawings, a frozen model may fall behind the full fine-tune. Our run does not cover that case.
Cheat sheet
The article on one page: open it full size, save it or share it.

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors