Tensors
Make a tensor Try it
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x.shape, x.dtype) Whole numbers → int64; any decimal → float32. .shape is (rows, columns).
Filled and random Try it
import torch
torch.manual_seed(0)
print(torch.zeros(2, 3).shape, torch.arange(5), torch.rand(2)) zeros / ones / full / arange / linspace; rand (0 to 1), randn (bell curve). Seed first.
Slice Try it
import torch
x = torch.arange(12).reshape(3, 4)
print(x[0], x[:, 1], x[1:, :2].shape, x[x > 9]) Row first, then column. A colon keeps a whole dimension; a mask keeps the True cells.
Broadcast Try it
import torch
col = torch.tensor([[0], [10], [20]])
row = torch.tensor([1, 2, 3])
print((col + row).shape) Line shapes up from the right; a size of 1 stretches. (3, 1) + (3,) → (3, 3).
Reshape Try it
import torch
x = torch.arange(6)
print(x.reshape(2, 3).shape, x.reshape(-1, 2).shape, x.unsqueeze(0).shape) -1 means "work it out". unsqueeze adds a size-1 dimension; squeeze drops them.
Reduce along a dim Try it
import torch
x = torch.tensor([[1., 2.], [3., 4.]])
print(x.sum(dim=0), x.mean(dim=1), x.argmax(dim=1)) The dim you name disappears. keepdim=True keeps it as size 1.
Matrix product Try it
import torch
W = torch.ones(3, 4)
x = torch.ones(4)
print((W @ x).shape, (torch.ones(8, 4) @ W.T).shape) Inner sizes must match: (3, 4) @ (4,) → (3,). This is what a layer does.
To and from NumPy Try it
import numpy as np
import torch
a = np.array([1.0, 2.0])
t = torch.from_numpy(a)
print(t, t.numpy(), torch.tensor(3.5).item()) from_numpy and .numpy() share memory; torch.tensor copies. .item() gives a plain number.
Autograd
A gradient Try it
import torch
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2 + 2 * x
y.backward()
print(x.grad) Mark the inputs with requires_grad=True, compute, call .backward() on the result: .grad holds dy/dx.
Several inputs Try it
import torch
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(0.5, requires_grad=True)
loss = (w * 3 + b - 7) ** 2
loss.backward()
print(w.grad, b.grad) One backward fills every leaf that requires grad: one partial derivative each.
Read the graph Try it
import torch
x = torch.tensor(2.0, requires_grad=True)
y = (x * 3).exp()
print(y.grad_fn.name(), x.is_leaf, y.is_leaf) Every result remembers the operation that made it (grad_fn); inputs you made are leaves.
Zero before the next backward Try it
import torch
w = torch.tensor(1.0, requires_grad=True)
for _ in range(3):
(w * 2).backward()
print(w.grad)
w.grad.zero_()
print(w.grad) Gradients add up across backward calls: zero them (or set to None) each step.
Non-scalar output Try it
import torch
x = torch.tensor([1.0, 2.0], requires_grad=True)
(x ** 2).sum().backward()
print(x.grad) backward() needs one number: sum (or mean) first, or pass gradient=.
Stop tracking Try it
import torch
w = torch.tensor(1.0, requires_grad=True)
with torch.no_grad():
v = w * 2
print(v.requires_grad, (w * 2).detach().requires_grad) no_grad for updates and evaluation; detach() for a value you want without its history.
The training loop
The five lines Try it
import torch
from torch import nn
torch.manual_seed(0)
X = torch.rand(50, 1)
y = 3 * X + 1
model = nn.Linear(1, 1)
loss_fn = nn.MSELoss()
opt = torch.optim.SGD(model.parameters(), lr=0.5)
for epoch in range(200):
loss = loss_fn(model(X), y)
opt.zero_grad()
loss.backward()
opt.step()
print(round(loss.item(), 4), round(model.weight.item(), 2), round(model.bias.item(), 2)) forward → loss → zero_grad → backward → step. Every model trains this way.
Gradient descent by hand Try it
import torch
w = torch.tensor(0.0, requires_grad=True)
for step in range(50):
loss = (w * 2 - 6) ** 2
loss.backward()
with torch.no_grad():
w -= 0.05 * w.grad
w.grad.zero_()
print(round(w.item(), 3)) Step against the slope inside no_grad, then zero the gradient.
Minibatches Try it
import torch
from torch.utils.data import TensorDataset, DataLoader
X, y = torch.arange(10.).unsqueeze(1), torch.arange(10.)
loader = DataLoader(TensorDataset(X, y), batch_size=4, shuffle=False)
print(len(loader), [len(xb) for xb, yb in loader]) One step per batch; an epoch is one pass over all batches. shuffle=True for training.
Train / validation split Try it
import torch
from torch.utils.data import TensorDataset, random_split
torch.manual_seed(0)
ds = TensorDataset(torch.rand(100, 1), torch.rand(100, 1))
train, val = random_split(ds, [80, 20])
print(len(train), len(val)) Choose settings on validation data; never on the test set.
Evaluate Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(1, 1)
X = torch.rand(5, 1)
model.eval()
with torch.no_grad():
print(model(X).shape) eval() mode and no_grad when you only want predictions.
Weight decay Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(3, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1, weight_decay=0.01)
print(opt.param_groups[0]['weight_decay']) Adds weight_decay × w to every gradient: weights shrink unless the data pushes back.
Classification
Softmax Try it
import torch
scores = torch.tensor([[2.0, 1.0, 0.1]])
p = torch.softmax(scores, dim=1)
print(p.round(decimals=3), round(p.sum().item(), 3)) Scores → probabilities that add up to 1 along the class dim. The biggest score gets the biggest share.
Cross-entropy Try it
import torch
from torch import nn
scores = torch.tensor([[2.0, 1.0, 0.1], [0.5, 2.5, -1.0]])
labels = torch.tensor([0, 1])
print(round(nn.CrossEntropyLoss()(scores, labels).item(), 4)) Give it raw scores (N, classes) and int64 class numbers (N,). It does the softmax itself: never softmax first.
A classifier Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(nn.Flatten(), nn.Linear(256, 10))
x = torch.rand(8, 16, 16)
print(model(x).shape) Flatten each 16 × 16 picture to 256 numbers, then one score per class: (8, 16, 16) → (8, 10).
Accuracy Try it
import torch
scores = torch.tensor([[0.1, 2.0], [1.5, 0.2], [0.3, 0.9]])
y = torch.tensor([1, 0, 0])
pred = scores.argmax(dim=1)
print(pred, round((pred == y).float().mean().item(), 3)) argmax over the class dim gives the predicted class; the mean of the matches is the accuracy.
Confusion matrix Try it
import torch
y = torch.tensor([0, 0, 1, 1, 2, 2])
pred = torch.tensor([0, 1, 1, 1, 2, 0])
cm = torch.bincount(y * 3 + pred, minlength=9).reshape(3, 3)
print(cm)
print(cm.diag()) Row = true class, column = predicted. The diagonal is what it got right; the rest shows what it mixes up.
Shift the test data Try it
import torch
img = torch.zeros(4, 4)
img[1, 1] = 1.0
print(torch.roll(img, 1, dims=1)) A test score holds only for data like the training data: move the pictures and a pixel model can fail.
Multilayer perceptrons
An MLP Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 10))
print(model(torch.rand(4, 16, 16)).shape, sum(p.numel() for p in model.parameters())) Linear → activation → Linear. Without the activation in between, two layers are one straight-line layer.
Activations Try it
import torch
x = torch.tensor([-2.0, 0.0, 2.0])
print(torch.relu(x), torch.sigmoid(x).round(decimals=3), torch.tanh(x).round(decimals=3)) ReLU keeps positives (slope 1); sigmoid and tanh squash, and their slopes fade at the ends.
Gradient size per layer Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 4), nn.Sigmoid(), nn.Linear(4, 4), nn.Sigmoid(), nn.Linear(4, 1))
model(torch.rand(8, 4)).sum().backward()
print([f'{model[i].weight.grad.norm().item():.0e}' for i in (0, 2, 4)]) Read .grad.norm() layer by layer: tiny near the input means vanishing gradients.
Initialise Try it
import torch
from torch import nn
torch.manual_seed(0)
layer = nn.Linear(256, 128)
nn.init.kaiming_uniform_(layer.weight, nonlinearity='relu')
nn.init.zeros_(layer.bias)
print(round(layer.weight.std().item(), 3)) Kaiming for ReLU, Xavier for tanh / sigmoid: a start that keeps the signal about the same size layer to layer.
Keep the best weights Try it
import copy
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(2, 1)
best = copy.deepcopy(model.state_dict())
with torch.no_grad():
model.weight += 1
model.load_state_dict(best)
print(model.weight) Early stopping: deepcopy the state_dict at the best validation loss, load it back when you stop.
Dropout Try it
import torch
from torch import nn
torch.manual_seed(0)
drop = nn.Dropout(0.5)
x = torch.ones(1, 8)
print(drop(x))
drop.eval()
print(drop(x)) Training: zero a random share p, scale the rest by 1/(1−p). After model.eval(): does nothing.
Building blocks
A module Try it
import torch
from torch import nn
class Net(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(2, 8)
self.out = nn.Linear(8, 2)
def forward(self, x):
return self.out(torch.relu(self.hidden(x)))
torch.manual_seed(0)
model = Net()
print(model(torch.zeros(4, 2)).shape) Make the layers in __init__ (super().__init__() first), use them in forward, and call model(x).
Containers Try it
import torch
from torch import nn
torch.manual_seed(0)
layers = nn.ModuleList([nn.Linear(4, 4) for _ in range(3)])
heads = nn.ModuleDict({'kind': nn.Linear(4, 10), 'size': nn.Linear(4, 1)})
print(len(layers), list(heads.keys()), sum(p.numel() for p in layers.parameters())) ModuleList / ModuleDict register their layers; a plain Python list hides them from parameters().
Count and freeze Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 2))
model[0].requires_grad_(False)
print([(n, tuple(p.shape)) for n, p in model.named_parameters()])
print(sum(p.numel() for p in model.parameters() if p.requires_grad)) requires_grad_(False) freezes a layer; give the optimiser only the parameters that still need gradients.
Initialise every layer Try it
import torch
from torch import nn
def init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_uniform_(m.weight, nonlinearity='relu')
nn.init.zeros_(m.bias)
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 2)).apply(init)
print(model[2].bias) model.apply(fn) calls fn on every submodule; nn.init.* fill weights in place.
Parameter and buffer Try it
import torch
from torch import nn
class Scale(nn.Module):
def __init__(self):
super().__init__()
self.gain = nn.Parameter(torch.ones(3))
self.register_buffer('calls', torch.zeros(1))
def forward(self, x):
self.calls += 1
return x * self.gain
m = Scale()
m(torch.ones(3))
print(list(m.state_dict().keys()), [n for n, _ in m.named_parameters()]) nn.Parameter is trained; a buffer is saved in the state_dict but never trained.
Save and load Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(3, 1)
torch.save(model.state_dict(), 'model.pt')
fresh = nn.Linear(3, 1)
print(fresh.load_state_dict(torch.load('model.pt')))
fresh.eval()
print(torch.equal(fresh.weight, model.weight)) Save the state_dict, not the model; build the same model, load, then eval() before predicting.
Device-agnostic code Try it
import torch
from torch import nn
device = 'cuda' if torch.cuda.is_available() else 'cpu'
torch.manual_seed(0)
model = nn.Linear(3, 1).to(device)
x = torch.zeros(2, 3, device=device)
print(model(x).device) Pick the device once; move the model and every batch to it.
Convolutions
Convolve Try it
import torch
import torch.nn.functional as F
x = torch.arange(16.).reshape(1, 1, 4, 4)
k = torch.tensor([[[[1., -1.], [1., -1.]]]])
print(F.conv2d(x, k)) Images are (N, C, H, W); a kernel is (out, in, kH, kW). Slide, multiply, add.
Output size Try it
import torch
from torch import nn
x = torch.zeros(1, 1, 16, 16)
for conv in [nn.Conv2d(1, 4, 5), nn.Conv2d(1, 4, 5, padding=2), nn.Conv2d(1, 4, 3, stride=2, padding=1)]:
print(tuple(conv(x).shape)) out = ⌊(n + 2·padding − kernel) / stride⌋ + 1 per side.
Channels and weights Try it
import torch
from torch import nn
torch.manual_seed(0)
conv = nn.Conv2d(3, 8, 3)
print(tuple(conv.weight.shape), sum(p.numel() for p in conv.parameters())) One 3 × 3 × in kernel per output channel, plus a bias each: 8 × 3 × 3 × 3 + 8.
Pooling Try it
import torch
from torch import nn
x = torch.arange(16.).reshape(1, 1, 4, 4)
print(nn.MaxPool2d(2)(x))
print(nn.AvgPool2d(2)(x)) Pooling shrinks each side (here by 2) and has no weights.
LeNet for glyphs Try it
import torch
from torch import nn
torch.manual_seed(0)
net = nn.Sequential(nn.Conv2d(1, 6, 5, padding=2), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(6, 16, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(16 * 2 * 2, 10))
x = torch.zeros(8, 1, 16, 16)
for layer in net:
x = layer(x)
print(layer.__class__.__name__, tuple(x.shape)) Print every layer's shape to find Flatten's size for the first Linear.
Make it work
Overfit one batch Try it
import torch
from torch import nn
torch.manual_seed(0)
X, y = torch.randn(8, 4), torch.randint(0, 3, (8,))
model = nn.Sequential(nn.Linear(4, 32), nn.ReLU(), nn.Linear(32, 3))
opt = torch.optim.Adam(model.parameters(), lr=0.05)
for step in range(200):
loss = nn.functional.cross_entropy(model(X), y)
opt.zero_grad()
loss.backward()
opt.step()
print(round(loss.item(), 3)) A working model drives the loss on one small batch close to 0. If it can't, look for a bug first.
Sum the loss as a number Try it
import torch
losses = [torch.tensor(0.5, requires_grad=True) * 2 for _ in range(3)]
total = 0.0
for loss in losses:
total += loss.item()
print(total) loss.item() gives a plain number; adding the tensors would keep every graph alive.
reshape, not view Try it
import torch
x = torch.arange(6).reshape(2, 3).t()
print(x.is_contiguous(), x.reshape(6)) After permute / transpose / .t(), use reshape (or .contiguous().view).
Reproducible runs Try it
import torch
from torch.utils.data import TensorDataset, DataLoader
ds = TensorDataset(torch.arange(6))
for _ in range(2):
g = torch.Generator().manual_seed(0)
print([b[0].tolist() for b in DataLoader(ds, batch_size=3, shuffle=True, generator=g)]) Seed with torch.manual_seed, and give the DataLoader its own seeded Generator.
Modern CNNs
A VGG block Try it
import torch
from torch import nn
def vgg_block(n, cin, cout):
layers = []
for i in range(n):
layers += [nn.Conv2d(cin if i == 0 else cout, cout, 3, padding=1), nn.ReLU()]
return nn.Sequential(*layers, nn.MaxPool2d(2))
torch.manual_seed(0)
net = nn.Sequential(vgg_block(1, 1, 8), vgg_block(2, 8, 16))
print(net(torch.zeros(4, 1, 16, 16)).shape) conv 3 × 3 (padding 1 keeps the size) → ReLU, repeated, then pool: a block you can stack.
Global average pooling Try it
import torch
from torch import nn
head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten())
print(head(torch.zeros(4, 10, 4, 4)).shape) One number per channel: 10 channels → 10 scores, no Linear layer needed.
Join branches Try it
import torch
a, b = torch.zeros(4, 8, 16, 16), torch.zeros(4, 16, 16, 16)
print(torch.cat([a, b], dim=1).shape) Concatenate along dim 1, the channels; every branch must keep the same height and width.
Batch normalisation Try it
import torch
from torch import nn
torch.manual_seed(0)
bn = nn.BatchNorm2d(3)
x = torch.randn(8, 3, 4, 4) * 5 + 2
y = bn(x)
print(round(y.mean().item(), 3), round(y.std().item(), 2), bn.running_mean.shape)
bn.eval() Training: normalise with the batch statistics and update the running ones. eval(): use the running ones.
A residual block Try it
import torch
from torch import nn
import torch.nn.functional as F
class Res(nn.Module):
def __init__(self, c):
super().__init__()
self.c1 = nn.Conv2d(c, c, 3, padding=1)
self.c2 = nn.Conv2d(c, c, 3, padding=1)
def forward(self, x):
return F.relu(self.c2(F.relu(self.c1(x))) + x)
torch.manual_seed(0)
print(Res(8)(torch.zeros(2, 8, 16, 16)).shape) Add the input back: the block only has to learn a correction. Shapes must match (else a 1 × 1 projection).
Count multiply-adds Try it
from torch import nn
conv = nn.Conv2d(8, 16, 3, padding=1)
h = w = 16
macs = h * w * conv.out_channels * conv.in_channels * 3 * 3
print(sum(p.numel() for p in conv.parameters()), macs) Weights and compute differ: every weight is used once per output pixel.
Optimisation
Momentum Try it
import torch
w = torch.tensor([2.0, -1.5], requires_grad=True)
opt = torch.optim.SGD([w], lr=0.02, momentum=0.9)
for _ in range(50):
loss = 10 * w[0] ** 2 + w[1] ** 2
opt.zero_grad()
loss.backward()
opt.step()
print(w.detach().round(decimals=3)) A running sum of past steps: it rolls along a ravine where plain SGD zig-zags.
Adam and AdamW Try it
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(4, 1)
adam = torch.optim.Adam(model.parameters(), lr=1e-3)
adamw = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
print(adam.defaults['betas'], adamw.defaults['weight_decay']) Adam: a step size per weight from two running averages. AdamW: weight decay applied separately.
A schedule as a curve Try it
import torch
w = torch.ones(1, requires_grad=True)
opt = torch.optim.SGD([w], lr=0.1)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=8)
lrs = []
for _ in range(8):
lrs.append(round(opt.param_groups[0]['lr'], 4))
opt.step()
sched.step()
print(lrs) Step a scheduler with a dummy optimiser to see its curve. Always optimizer.step() first.
Warm-up then decay Try it
import torch
from torch.optim import lr_scheduler as L
w = torch.ones(1, requires_grad=True)
opt = torch.optim.SGD([w], lr=0.1)
sched = L.SequentialLR(opt, [L.LinearLR(opt, start_factor=0.25, total_iters=3), L.CosineAnnealingLR(opt, T_max=5)], milestones=[3])
lrs = []
for _ in range(8):
lrs.append(round(opt.param_groups[0]['lr'], 4))
opt.step()
sched.step()
print(lrs) Start small, climb to the full rate, then come down.
Clip the gradient Try it
import torch
w = torch.zeros(2, requires_grad=True)
(w * torch.tensor([30.0, 40.0])).sum().backward()
print(torch.nn.utils.clip_grad_norm_([w], 1.0), w.grad) Returns the norm before clipping; rescales the gradient to at most max_norm.
Second derivative Try it
import torch
x = torch.tensor(1.5, requires_grad=True)
f = x ** 3 - 2 * x
g, = torch.autograd.grad(f, x, create_graph=True)
h, = torch.autograd.grad(g, x)
print(round(g.item(), 3), round(h.item(), 3)) create_graph=True keeps the gradient differentiable: the slope of the slope.
Sequences and RNNs
Windows for forecasting Try it
import torch
x = torch.arange(10.)
tau = 3
X = x.unfold(0, tau, 1)[:-1]
y = x[tau:]
print(X.shape, y.shape, X[0], y[0]) Each row is the last tau readings; the target is the next one.
A vocabulary Try it
text = 'the fox and the owl'
words = text.split()
vocab = ['<unk>'] + sorted(set(words))
stoi = {w: i for i, w in enumerate(vocab)}
print([stoi.get(w, 0) for w in 'the cat and the fox'.split()]) Map tokens to ids; anything unseen becomes <unk>.
nn.RNN shapes Try it
import torch
from torch import nn
torch.manual_seed(0)
rnn = nn.RNN(input_size=8, hidden_size=16, batch_first=True)
out, h = rnn(torch.zeros(4, 10, 8))
print(out.shape, h.shape) batch_first=True: (batch, seq, feature) in, (batch, seq, hidden) out; h_n is (layers, batch, hidden).
LSTM and GRU Try it
import torch
from torch import nn
torch.manual_seed(0)
lstm = nn.LSTM(8, 16, batch_first=True)
out, (h, c) = lstm(torch.zeros(4, 10, 8))
gru = nn.GRU(8, 16, num_layers=2, batch_first=True)
out2, h2 = gru(torch.zeros(4, 10, 8))
print(h.shape, c.shape, h2.shape) An LSTM carries (h, c); a GRU just h. num_layers stacks them.
Sample with temperature Try it
import torch
torch.manual_seed(0)
logits = torch.tensor([2.0, 1.0, 0.1])
for t in (0.5, 1.0, 2.0):
p = torch.softmax(logits / t, dim=0)
print(t, torch.multinomial(p, 8, replacement=True).tolist()) Low temperature: safe and repetitive. High: varied and wild.
Carry the hidden state Try it
import torch
from torch import nn
torch.manual_seed(0)
rnn = nn.GRU(4, 8, batch_first=True)
h = None
for chunk in torch.randn(3, 2, 5, 4):
out, h = rnn(chunk, h)
h = h.detach()
print(h.shape, h.requires_grad) detach() between batches keeps the state but cuts the history backward() would walk.
Encoder–decoder
Pad a batch Try it
import torch
from torch.nn.utils.rnn import pad_sequence
seqs = [torch.tensor([5, 7, 2]), torch.tensor([4, 2]), torch.tensor([9, 3, 8, 2])]
batch = pad_sequence(seqs, batch_first=True, padding_value=0)
print(batch)
print(batch != 0) Pad with <pad> = 0 to the longest; the mask marks the real tokens.
A loss that skips padding Try it
import torch
import torch.nn.functional as F
torch.manual_seed(0)
logits = torch.randn(2, 5, 3)
target = torch.tensor([[1, 4, 0], [2, 0, 0]])
print(round(F.cross_entropy(logits, target, ignore_index=0).item(), 4)) Scores are (batch, vocab, steps); ignore_index=0 leaves the padding out of the average.
Encoder and decoder Try it
import torch
from torch import nn
torch.manual_seed(0)
enc = nn.GRU(8, 16, batch_first=True)
dec = nn.GRU(8, 16, batch_first=True)
_, h = enc(torch.zeros(2, 6, 8))
out, _ = dec(torch.zeros(2, 4, 8), h)
print(h.shape, out.shape) The encoder's final hidden state starts the decoder.
Greedy decoding Try it
import torch
probs = torch.tensor([[0.1, 0.6, 0.3], [0.7, 0.2, 0.1]])
print(probs.argmax(dim=1), probs.max(dim=1).values.log().sum().round(decimals=4)) Take the most likely token at each step; the sentence score is the sum of log-probabilities.
Top k for a beam Try it
import torch
scores = torch.tensor([-1.2, -0.3, -2.0, -0.9])
print(scores.topk(2)) Beam search keeps the k best partial translations at every step.
Attention and transformers
Attention by hand Try it
import math
import torch
torch.manual_seed(0)
q, k, v = torch.randn(1, 2, 4), torch.randn(1, 3, 4), torch.randn(1, 3, 4)
w = torch.softmax(q @ k.transpose(1, 2) / math.sqrt(4), dim=-1)
print(w.round(decimals=3), (w @ v).shape) Score every key, softmax over the keys (each row sums to 1), average the values.
The built-in Try it
import torch
import torch.nn.functional as F
torch.manual_seed(0)
q, k, v = torch.randn(1, 2, 4), torch.randn(1, 3, 4), torch.randn(1, 3, 4)
print(F.scaled_dot_product_attention(q, k, v).shape) The same sum in one call; is_causal=True or attn_mask= for masks.
A causal mask Try it
from torch import nn
print(nn.Transformer.generate_square_subsequent_mask(4)) −inf above the diagonal: position t can only look at positions ≤ t.
Multi-head attention Try it
import torch
from torch import nn
torch.manual_seed(0)
mha = nn.MultiheadAttention(embed_dim=8, num_heads=2, batch_first=True)
x = torch.randn(2, 5, 8)
out, w = mha(x, x, x)
print(out.shape, w.shape) batch_first=True: (batch, seq, embed). The weights are averaged over heads unless average_attn_weights=False.
Positional encoding Try it
import torch
pos = torch.arange(4.).unsqueeze(1)
i = torch.arange(0, 8, 2.)
pe = torch.zeros(4, 8)
pe[:, 0::2] = torch.sin(pos / 10000 ** (i / 8))
pe[:, 1::2] = torch.cos(pos / 10000 ** (i / 8))
print(pe.round(decimals=2)) Each position gets a unique pattern of waves; add it to the token embeddings.
A transformer block Try it
import torch
from torch import nn
torch.manual_seed(0)
layer = nn.TransformerEncoderLayer(d_model=16, nhead=4, dim_feedforward=32, dropout=0.0, batch_first=True)
print(layer(torch.zeros(2, 5, 16)).shape, sum(p.numel() for p in layer.parameters())) Attention + feed-forward, each with a residual and LayerNorm.
Top-k sampling Try it
import torch
torch.manual_seed(0)
logits = torch.tensor([2.0, 1.5, 0.3, -1.0])
kth = logits.topk(2).values[-1]
probs = torch.softmax(logits.masked_fill(logits < kth, float('-inf')), dim=0)
print(probs.round(decimals=3), torch.multinomial(probs, 5, replacement=True).tolist()) Keep the k most likely tokens, renormalise, sample.
Vision in practice
Augment a picture Try it
import torch
from torchvision.transforms import v2
torch.manual_seed(0)
aug = v2.Compose([v2.RandomHorizontalFlip(p=0.5), v2.RandomCrop(16, padding=2)])
img = torch.rand(1, 16, 16)
print(aug(img).shape) A fresh random change every call. Augment the training set only; one call on a whole batch draws once for all of it.
Freeze a body, new head Try it
import torch
from torch import nn
model = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 3))
for p in model[0].parameters():
p.requires_grad_(False)
model[2] = nn.Linear(16, 5)
print(sum(p.numel() for p in model.parameters() if p.requires_grad)) Frozen weights get no gradient; only the new head learns.
Two learning rates Try it
import torch
from torch import nn
model = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 5))
opt = torch.optim.Adam([{'params': model[0].parameters(), 'lr': 1e-4},
{'params': model[2].parameters(), 'lr': 1e-2}])
print([g['lr'] for g in opt.param_groups]) Fine-tune the whole net: a small lr for the pretrained body, a bigger one for the new head.
Box formats and IoU Try it
import torch
from torchvision.ops import box_convert, box_iou
a = torch.tensor([[0., 0., 10., 10.]])
b = torch.tensor([[5., 5., 15., 15.]])
print(box_convert(a, 'xyxy', 'cxcywh'))
print(box_iou(a, b)) IoU = overlap ÷ union: 25 ÷ 175 here. box_iou gives every pair at once, (n, m).
Non-max suppression Try it
import torch
from torchvision.ops import nms, batched_nms
boxes = torch.tensor([[0., 0., 10., 10.], [1., 1., 11., 11.], [20., 20., 30., 30.]])
scores = torch.tensor([0.9, 0.8, 0.7])
print(nms(boxes, scores, 0.5))
print(batched_nms(boxes, scores, torch.tensor([1, 2, 1]), 0.5)) Keep the best box, drop the ones overlapping it; batched_nms only lets boxes of the same class compete.
RoI align Try it
import torch
from torchvision.ops import roi_align
feat = torch.arange(64.).view(1, 1, 8, 8)
boxes = [torch.tensor([[0., 0., 16., 16.]])]
print(roi_align(feat, boxes, output_size=2, spatial_scale=0.25, aligned=True)) Crop a box from a feature map into a fixed grid; spatial_scale turns pixel boxes into map cells.
Transposed convolution Try it
import torch
from torch import nn
up = nn.ConvTranspose2d(8, 4, kernel_size=4, stride=2, padding=1)
print(up(torch.zeros(1, 8, 8, 8)).shape, up.weight.shape) Grows a map: (n − 1)·s − 2p + k = 16. Weights are (in, out, k, k).
Per-pixel loss Try it
import torch
import torch.nn.functional as F
scores = torch.zeros(2, 5, 4, 4)
masks = torch.zeros(2, 4, 4, dtype=torch.long)
print(F.cross_entropy(scores, masks).item(), scores.argmax(dim=1).shape) Classes on dim 1: (B, C, H, W) scores against (B, H, W) class ids.
Language in practice
An embedding table Try it
import torch
from torch import nn
torch.manual_seed(0)
emb = nn.Embedding(10, 4, padding_idx=0)
ids = torch.tensor([[3, 7, 0]])
print(emb(ids).shape, emb(ids)[0, 2]) A lookup: one row per id. padding_idx stays zero and never learns.
Cosine similarity Try it
import torch
import torch.nn.functional as F
a = torch.tensor([1., 2., 3.])
b = torch.tensor([2., 4., 6.5])
print(round(F.cosine_similarity(a, b, dim=0).item(), 4))
V = F.normalize(torch.stack([a, b]), dim=1)
print((V @ V.T).round(decimals=4)) Angle, not length. Normalise once, then one matmul gives every pair.
Negative sampling Try it
import torch
import torch.nn.functional as F
torch.manual_seed(0)
counts = torch.tensor([50., 20., 5., 1.])
noise = counts ** 0.75 / (counts ** 0.75).sum()
neg = torch.multinomial(noise, 6, replacement=True)
scores = torch.zeros(1, 4)
print(neg.tolist(), round(F.binary_cross_entropy_with_logits(scores, torch.tensor([[1., 0., 0., 0.]])).item(), 4)) One real pair against a few noise words: a yes/no loss, not a softmax over the vocabulary.
A bag of pieces Try it
import torch
from torch import nn
torch.manual_seed(0)
bag = nn.EmbeddingBag(10, 3, mode='sum')
pieces = torch.tensor([1, 4, 2, 7])
print(bag(pieces, torch.tensor([0, 2])).shape) Sum (or mean) the vectors of each word's pieces; offsets say where each word starts.
A text-CNN Try it
import torch
from torch import nn
emb = torch.zeros(2, 12, 16)
conv = nn.Conv1d(16, 8, kernel_size=3)
h = conv(emb.transpose(1, 2))
print(h.shape, h.amax(dim=2).shape) Conv1d wants (B, d, T): transpose first, then max over time.
A padding mask Try it
import torch
ids = torch.tensor([[2, 9, 5, 3, 0, 0]])
pad = ids == 0
scores = torch.zeros(1, 1, 6, 6).masked_fill(pad[:, None, None, :], float('-inf'))
print(torch.softmax(scores, dim=-1)[0, 0, 0]) −inf before the softmax: nobody attends to [PAD].
Mean of real tokens Try it
import torch
h = torch.ones(1, 4, 3)
h[0, 2:] = 9
keep = torch.tensor([[1., 1., 0., 0.]])[..., None]
print((h * keep).sum(1) / keep.sum(1)) Pool over the real tokens only, so padding doesn't water the vector down.
Load what fits Try it
import torch
from torch import nn
body = nn.Linear(4, 4)
model = nn.Sequential(body, nn.Linear(4, 2))
state = {'0.weight': torch.zeros(4, 4), '0.bias': torch.zeros(4)}
print(model.load_state_dict(state, strict=False)) strict=False loads a pretrained body and reports the new head as missing.
Beyond
One GAN step Try it
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0)
G = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2))
D = nn.Sequential(nn.Linear(2, 16), nn.LeakyReLU(0.2), nn.Linear(16, 1))
opt_g = torch.optim.Adam(G.parameters(), lr=1e-3, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(D.parameters(), lr=1e-3, betas=(0.5, 0.999))
real, fake = torch.randn(8, 2) + 3, G(torch.randn(8, 2))
loss_d = F.binary_cross_entropy_with_logits(D(real), torch.ones(8, 1)) + F.binary_cross_entropy_with_logits(D(fake.detach()), torch.zeros(8, 1))
opt_d.zero_grad(); loss_d.backward(); opt_d.step()
loss_g = F.binary_cross_entropy_with_logits(D(fake), torch.ones(8, 1))
opt_g.zero_grad(); loss_g.backward(); opt_g.step()
print(round(loss_d.item(), 4), round(loss_g.item(), 4)) D learns real → 1, fake → 0 on a detached fake; then G learns to make D say 1.
A generator that grows a picture Try it
import torch
from torch import nn
G = nn.Sequential(nn.Linear(16, 64 * 4 * 4), nn.Unflatten(1, (64, 4, 4)),
nn.ConvTranspose2d(64, 32, 4, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
nn.ConvTranspose2d(32, 1, 4, stride=2, padding=1), nn.Tanh())
print(G(torch.zeros(2, 16)).shape) 16 numbers → 4 × 4 → 8 × 8 → 16 × 16; Tanh keeps pixels in [-1, 1]. eval() before sampling.
Random search Try it
import random
r = random.Random(0)
trials = [{'lr': 10 ** r.uniform(-4, -1), 'width': r.choice([8, 16, 32])} for _ in range(4)]
print([(round(t['lr'], 5), t['width']) for t in trials]) Sample each knob at random (lr on a log scale); score on validation, never on test.
Value iteration Try it
import torch
R = torch.tensor([0., 0., 0., 1.]) # a 4-cell corridor, the goal on the right
V = torch.zeros(4)
for _ in range(10):
left, right = V[[0, 0, 1, 2]], V[[1, 2, 3, 3]]
V = R + 0.9 * torch.maximum(left, right)
V[3] = 1.0
print(V.round(decimals=3)) Each value = reward + discount × the best neighbour; repeat until nothing changes.
The Q-learning update Try it
import torch
Q = torch.zeros(4, 2)
s, a, r, s2 = 2, 1, 1.0, 3
alpha, gamma = 0.5, 0.9
Q[s, a] += alpha * (r + gamma * Q[s2].max() - Q[s, a])
print(Q) Nudge Q(s, a) towards the reward plus the best value of where you landed.
Matrix factorisation Try it
import torch
from torch import nn
torch.manual_seed(0)
users, items = nn.Embedding(300, 5), nn.Embedding(200, 5)
u, i = torch.tensor([0, 1]), torch.tensor([10, 42])
print((users(u) * items(i)).sum(1).shape) A rating ≈ reader vector · story vector (+ biases); train with MSE on the ratings you have.
Sparse embeddings Try it
import torch
from torch import nn
emb = nn.Embedding(1000, 8, sparse=True)
opt = torch.optim.SparseAdam(emb.parameters(), lr=0.01)
emb(torch.tensor([3, 7])).sum().backward()
print(emb.weight.grad.is_sparse, emb.weight.grad.coalesce().indices()) Only the looked-up rows get a gradient; SparseAdam updates just those.
Compile and wrap Try it
import torch
from torch import nn
model = nn.Linear(4, 2)
print(type(torch.compile(model)).__name__, type(nn.DataParallel(model).module).__name__, torch.cuda.is_available()) On a GPU machine: compile for speed, autocast for mixed precision, DDP for many GPUs.