PyTorch Snippets: 100 Short, Copy-Paste Examples for Tensors, Autograd, Models, Training, Data, GPUs and Saving
100 short, self-contained PyTorch code snippets that cover what you use every day: creating and reshaping tensors, broadcasting, autograd, building models with nn.Module, loss functions and optimizers, a complete training loop, Dataset and DataLoader, GPU and Apple Silicon (MPS) devices, mixed precision, torch.compile, saving and loading checkpoints, and debugging. Every snippet runs on its own on a CPU (GPU snippets fall back to CPU), uses synthetic data, and prints something you can check. It is for Python developers learning PyTorch, students, and practitioners who want a quick, correct reference instead of searching through docs and forum threads.
Last reviewed: December 2026. Written for PyTorch 2.x; see Versions for the few snippets that depend on a recent release.
pip install torch # see https://pytorch.org/get-started/locally/ for the right command for your GPU
python -m unittest discover -s tests -v # checks all 100 snippets (runs them if torch is installed)
Table of Contents
- 1. Tensor basics (1-15)
- 2. Indexing, shapes and broadcasting (16-28)
- 3. Autograd (29-38)
- 4. Building models (39-52)
- 5. Losses and optimizers (53-60)
- 6. Training loops (61-72)
- 7. Data loading (73-80)
- 8. Devices and performance (81-90)
- 9. Saving, loading and export (91-96)
- 10. Debugging and utilities (97-100)
- Versions
- Common errors and fixes
- How the tests work
- Further learning
- FAQ
- Where to go next
- Contributing
- More free resources
1. Tensor basics
1. Create tensors from data
import torch
a = torch.tensor([1, 2, 3]) # int64
b = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) # float32
print(a.dtype, b.dtype, b.shape) # torch.int64 torch.float32 torch.Size([2, 2])
2. Create filled tensors
import torch
print(torch.zeros(2, 3))
print(torch.ones(2, 3, dtype=torch.int32))
print(torch.full((2, 2), 7.0))
print(torch.eye(3))
print(torch.empty(2, 2).shape) # uninitialized memory; values are arbitrary
3. Ranges and evenly spaced values
import torch
print(torch.arange(0, 10, 2)) # tensor([0, 2, 4, 6, 8])
print(torch.linspace(0, 1, steps=5)) # tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
print(torch.logspace(0, 3, steps=4)) # tensor([ 1., 10., 100., 1000.])
4. Random tensors with a fixed seed
import torch
torch.manual_seed(0)
u = torch.rand(2, 3) # uniform [0, 1)
n = torch.randn(2, 3) # standard normal
i = torch.randint(0, 10, (2, 3)) # integers in [0, 10)
p = torch.randperm(5) # random permutation of 0..4
print(u.shape, n.shape, i.dtype, sorted(p.tolist()))
5. Tensors shaped like another tensor
import torch
x = torch.randn(4, 5)
print(torch.zeros_like(x).shape, torch.ones_like(x).dtype, torch.rand_like(x).shape)
y = x.new_zeros(2, 2) # same dtype and device as x, new shape
print(y.dtype, y.device)
6. Data types and conversion
import torch
x = torch.tensor([1.7, -2.3])
print(x.to(torch.int64)) # tensor([ 1, -2]) truncates toward zero
print(x.half().dtype, x.double().dtype, x.bool())
print(torch.tensor([1, 2]) / 2) # true division gives float: tensor([0.5000, 1.0000])
print(torch.tensor([5, 7]) // 2) # floor division keeps int: tensor([2, 3])
7. Default dtype and type promotion
import torch
print(torch.get_default_dtype()) # torch.float32
print((torch.tensor([1]) + torch.tensor([1.5])).dtype) # int64 + float32 -> torch.float32
print(torch.result_type(torch.tensor([1], dtype=torch.int8), 2.5)) # torch.float32
8. NumPy interop (shared memory)
import numpy as np
import torch
arr = np.array([1.0, 2.0, 3.0])
t = torch.from_numpy(arr) # shares memory with arr
arr[0] = 100.0
print(t) # tensor([100., 2., 3.], dtype=torch.float64)
back = t.numpy() # also shares memory (CPU tensors only)
copy = torch.tensor(arr) # torch.tensor() always copies
print(back is arr, copy[0].item())
9. Python scalars and lists
import torch
x = torch.tensor([[1.5, 2.5], [3.5, 4.5]])
print(x.sum().item()) # 12.0, a Python float (only for one-element tensors)
print(x.tolist()) # nested Python lists
print(float(x[0, 0]), int(x[1, 1]))
10. Elementwise math
import torch
x = torch.tensor([1.0, 4.0, 9.0])
print(x + 1, x * 2, x ** 2)
print(torch.sqrt(x), torch.exp(torch.tensor([0.0])), torch.log(x))
print(torch.clamp(x, min=2.0, max=5.0)) # tensor([2., 4., 5.])
print(torch.where(x > 3, x, torch.zeros_like(x)))
11. Reductions
import torch
x = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(x.sum(), x.mean(), x.max(), x.min())
print(x.sum(dim=0)) # column sums: tensor([5., 7., 9.])
print(x.mean(dim=1, keepdim=True)) # shape (2, 1)
print(x.std(), x.var(correction=0)) # correction=0: population variance
values, indices = x.max(dim=1)
print(values, indices) # tensor([3., 6.]) tensor([2, 2])
12. argmax, topk and sort
import torch
scores = torch.tensor([[0.1, 0.7, 0.2], [0.5, 0.3, 0.2]])
print(scores.argmax(dim=1)) # tensor([1, 0])
top_vals, top_idx = scores.topk(2, dim=1)
print(top_idx) # tensor([[1, 2], [0, 1]])
sorted_vals, order = torch.sort(scores[0], descending=True)
print(order) # tensor([1, 2, 0])
13. Matrix multiplication
import torch
A = torch.randn(3, 4)
B = torch.randn(4, 5)
print((A @ B).shape) # torch.Size([3, 5])
print(torch.matmul(A, B).shape)
batch = torch.randn(8, 3, 4) @ torch.randn(8, 4, 5) # batched matmul
print(batch.shape) # torch.Size([8, 3, 5])
v = torch.randn(4)
print((A @ v).shape, torch.dot(v, v).shape) # torch.Size([3]) torch.Size([])
14. einsum
import torch
A, B = torch.randn(2, 3), torch.randn(3, 4)
print(torch.allclose(torch.einsum("ij,jk->ik", A, B), A @ B)) # True
x = torch.randn(5, 3)
print(torch.einsum("ij->j", x).shape) # sum over rows: torch.Size([3])
q, k = torch.randn(2, 4, 8), torch.randn(2, 6, 8)
print(torch.einsum("bqd,bkd->bqk", q, k).shape) # torch.Size([2, 4, 6])
15. Comparisons and boolean logic
import torch
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([1.0, 2.5, 3.0])
print(a == b, a < b)
print(torch.equal(a, b), torch.allclose(a, b, atol=0.6)) # False True
print((a > 1) & (a < 3), torch.any(a > 2), torch.all(a > 0))
print(torch.isnan(torch.tensor([float("nan"), 1.0])))
2. Indexing, shapes and broadcasting
16. Basic indexing and slicing
import torch
x = torch.arange(12).reshape(3, 4)
print(x[0]) # first row
print(x[:, 1]) # second column
print(x[1:, :2]) # rows 1-2, columns 0-1
print(x[-1, -1]) # tensor(11)
print(x[..., 0]) # ellipsis: first element of last dim
17. Boolean masks
import torch
x = torch.tensor([3, -1, 4, -1, 5])
print(x[x > 0]) # tensor([3, 4, 5])
x[x < 0] = 0 # in-place assignment through a mask
print(x) # tensor([3, 0, 4, 0, 5])
print(torch.nonzero(x).flatten()) # indices of nonzero values: tensor([0, 2, 4])
18. Fancy indexing and gather
import torch
x = torch.tensor([[10, 11, 12], [20, 21, 22]])
print(x[[0, 1, 1], [2, 0, 2]]) # tensor([12, 20, 22])
idx = torch.tensor([[2], [0]]) # pick one column per row
print(torch.gather(x, dim=1, index=idx)) # tensor([[12], [20]])
19. reshape vs view
import torch
x = torch.arange(6)
print(x.view(2, 3)) # needs contiguous memory; shares data
print(x.reshape(3, -1)) # -1 is inferred; copies only if needed
y = x.view(2, 3).t() # transpose makes it non-contiguous
print(y.is_contiguous()) # False
print(y.reshape(6)) # works
print(y.contiguous().view(6)) # view needs .contiguous() first
20. squeeze and unsqueeze
import torch
x = torch.randn(1, 3, 1, 5)
print(x.squeeze().shape) # torch.Size([3, 5])
print(x.squeeze(0).shape) # torch.Size([3, 1, 5])
v = torch.randn(3)
print(v.unsqueeze(0).shape, v.unsqueeze(-1).shape) # (1, 3) and (3, 1)
print(v[None, :, None].shape) # torch.Size([1, 3, 1])
21. permute and transpose
import torch
img = torch.randn(32, 32, 3) # H, W, C (as loaded from an image file)
chw = img.permute(2, 0, 1) # C, H, W (what PyTorch conv layers expect)
print(chw.shape) # torch.Size([3, 32, 32])
x = torch.randn(2, 5, 7)
print(x.transpose(1, 2).shape, x.mT.shape) # both swap the last two dims: (2, 7, 5)
22. flatten and unflatten
import torch
x = torch.randn(8, 3, 4, 4)
print(x.flatten(start_dim=1).shape) # torch.Size([8, 48])
print(torch.flatten(x).shape) # torch.Size([384])
y = torch.randn(8, 12)
print(y.unflatten(1, (3, 4)).shape) # torch.Size([8, 3, 4])
23. Concatenate and stack
import torch
a, b = torch.zeros(2, 3), torch.ones(2, 3)
print(torch.cat([a, b], dim=0).shape) # torch.Size([4, 3]) joins an existing dim
print(torch.cat([a, b], dim=1).shape) # torch.Size([2, 6])
print(torch.stack([a, b], dim=0).shape) # torch.Size([2, 2, 3]) adds a new dim
24. Split and chunk
import torch
x = torch.arange(10)
print(torch.split(x, 4)) # sizes 4, 4, 2
print(torch.chunk(x, 3)) # 3 chunks: sizes 4, 4, 2
a, b = x.split([3, 7])
print(a, b.shape)
q, k, v = torch.randn(2, 9).chunk(3, dim=-1) # common for fused QKV projections
print(q.shape) # torch.Size([2, 3])
25. Broadcasting rules
import torch
# Align shapes from the right; dims must be equal or 1 (missing dims count as 1).
x = torch.randn(4, 3)
row = torch.tensor([1.0, 2.0, 3.0]) # (3,) -> broadcast to (4, 3)
col = torch.randn(4, 1) # (4, 1) -> broadcast to (4, 3)
print((x + row).shape, (x * col).shape)
print((torch.randn(5, 1, 3) + torch.randn(1, 4, 3)).shape) # torch.Size([5, 4, 3])
26. Normalize features with broadcasting
import torch
X = torch.randn(100, 5) * 3 + 10
mean = X.mean(dim=0, keepdim=True) # (1, 5)
std = X.std(dim=0, keepdim=True)
Z = (X - mean) / (std + 1e-8)
print(Z.mean(dim=0).abs().max() < 1e-5, Z.std(dim=0))
27. Pairwise distances
import torch
a = torch.randn(5, 3)
b = torch.randn(7, 3)
d = torch.cdist(a, b) # (5, 7) Euclidean distances
manual = ((a[:, None, :] - b[None, :, :]) ** 2).sum(-1).sqrt()
print(d.shape, torch.allclose(d, manual, atol=1e-5))
28. In-place operations
import torch
x = torch.ones(3)
x.add_(1) # trailing underscore = in place
x.mul_(3)
print(x) # tensor([6., 6., 6.])
x.zero_()
print(x)
# Avoid in-place ops on tensors autograd needs for backward; PyTorch raises an error if you do.
3. Autograd
29. Gradients of a scalar function
import torch
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2 + 2 * x # dy/dx = 2x + 2
y.backward()
print(x.grad) # tensor(8.)
30. Gradients for a tensor of parameters
import torch
w = torch.randn(3, requires_grad=True)
x = torch.tensor([1.0, 2.0, 3.0])
loss = (w * x).sum() ** 2
loss.backward()
print(torch.allclose(w.grad, 2 * (w * x).sum() * x)) # True
31. Gradients accumulate: zero them
import torch
w = torch.tensor(1.0, requires_grad=True)
for _ in range(3):
(w * 2).backward()
print(w.grad) # tensor(6.) accumulated over 3 calls
w.grad = None # or w.grad.zero_(); optimizers do this with zero_grad()
(w * 2).backward()
print(w.grad) # tensor(2.)
32. Turn off gradient tracking
import torch
w = torch.randn(3, requires_grad=True)
with torch.no_grad():
y = w * 2
print(y.requires_grad) # False
with torch.inference_mode(): # stricter and slightly faster, for pure inference
z = w * 2
print(z.requires_grad) # False
d = w.detach() # same data, cut from the graph
print(d.requires_grad) # False
33. Non-scalar outputs need a gradient argument
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2 # vector output
y.backward(gradient=torch.ones_like(y)) # same as y.sum().backward()
print(x.grad) # tensor([2., 4., 6.])
34. torch.autograd.grad without touching .grad
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3
(dy_dx,) = torch.autograd.grad(y, x, create_graph=True) # keep graph for higher order
(d2y_dx2,) = torch.autograd.grad(dy_dx, x)
print(dy_dx.item(), d2y_dx2.item()) # 12.0 12.0
35. Jacobian and Hessian
import torch
from torch.autograd.functional import hessian, jacobian
def f(x):
return torch.stack([x[0] * x[1], x[0] ** 2])
x = torch.tensor([2.0, 3.0])
print(jacobian(f, x)) # [[3., 2.], [4., 0.]]
print(hessian(lambda v: (v ** 2).sum() + v[0] * v[1], x)) # [[2., 1.], [1., 2.]]
36. Per-sample gradients with torch.func
import torch
from torch.func import grad, vmap
def loss_fn(w, x, y):
return ((x @ w - y) ** 2).mean()
w = torch.randn(3)
X, Y = torch.randn(8, 3), torch.randn(8)
per_sample = vmap(grad(loss_fn), in_dims=(None, 0, 0))(w, X, Y)
print(per_sample.shape) # torch.Size([8, 3]): one gradient per example
37. Gradient check against finite differences
import torch
from torch.autograd import gradcheck
def f(x):
return torch.sin(x) * x
x = torch.randn(4, dtype=torch.float64, requires_grad=True) # use float64 for gradcheck
print(gradcheck(f, (x,), eps=1e-6, atol=1e-4)) # True
38. A custom autograd Function
import torch
class ClampGrad(torch.autograd.Function):
"""Identity in the forward pass, clips the gradient in the backward pass."""
@staticmethod
def forward(ctx, x):
return x.clone()
@staticmethod
def backward(ctx, grad_out):
return grad_out.clamp(-1.0, 1.0)
x = torch.tensor([1.0, 2.0], requires_grad=True)
(ClampGrad.apply(x) * 10).sum().backward()
print(x.grad) # tensor([1., 1.])
4. Building models
39. A minimal nn.Module
import torch
from torch import nn
class MLP(nn.Module):
def __init__(self, in_dim, hidden, out_dim):
super().__init__()
self.fc1 = nn.Linear(in_dim, hidden)
self.fc2 = nn.Linear(hidden, out_dim)
def forward(self, x):
return self.fc2(torch.relu(self.fc1(x)))
model = MLP(10, 32, 2)
print(model(torch.randn(4, 10)).shape) # torch.Size([4, 2])
40. nn.Sequential
import torch
from torch import nn
model = nn.Sequential(
nn.Linear(10, 64),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(64, 3),
)
print(model(torch.randn(5, 10)).shape) # torch.Size([5, 3])
print(model[0]) # index into layers
41. Count parameters
from torch import nn
model = nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 3))
total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(total, trainable) # 899 899 (10*64+64 + 64*3+3)
42. Inspect named parameters and modules
from torch import nn
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
for name, p in model.named_parameters():
print(name, tuple(p.shape)) # 0.weight (8, 4), 0.bias (8,), 2.weight (2, 8), 2.bias (2,)
print([type(m).__name__ for m in model.modules()])
43. ModuleList and ModuleDict
import torch
from torch import nn
class Tower(nn.Module):
def __init__(self, depth=3, dim=16):
super().__init__()
self.blocks = nn.ModuleList([nn.Linear(dim, dim) for _ in range(depth)]) # registered
self.heads = nn.ModuleDict({"cls": nn.Linear(dim, 5), "reg": nn.Linear(dim, 1)})
def forward(self, x, task="cls"):
for block in self.blocks:
x = torch.relu(block(x))
return self.heads[task](x)
m = Tower()
print(m(torch.randn(2, 16)).shape, m(torch.randn(2, 16), task="reg").shape)
# A plain Python list would NOT register the layers: their parameters would be missing.
44. A small CNN
import torch
from torch import nn
cnn = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 32 -> 16
nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 16 -> 8
nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Linear(32, 10),
)
print(cnn(torch.randn(4, 3, 32, 32)).shape) # torch.Size([4, 10])
45. Residual block
import torch
from torch import nn
class ResidualBlock(nn.Module):
def __init__(self, channels):
super().__init__()
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(channels)
def forward(self, x):
out = torch.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
return torch.relu(out + x)
print(ResidualBlock(8)(torch.randn(2, 8, 16, 16)).shape) # torch.Size([2, 8, 16, 16])
46. LSTM sequence classifier
import torch
from torch import nn
class SeqClassifier(nn.Module):
def __init__(self, vocab=1000, emb=32, hidden=64, classes=4):
super().__init__()
self.embed = nn.Embedding(vocab, emb, padding_idx=0)
self.lstm = nn.LSTM(emb, hidden, batch_first=True)
self.out = nn.Linear(hidden, classes)
def forward(self, tokens): # tokens: (batch, seq_len) int64
_, (h_n, _) = self.lstm(self.embed(tokens)) # h_n: (num_layers, batch, hidden)
return self.out(h_n[-1])
print(SeqClassifier()(torch.randint(1, 1000, (8, 20))).shape) # torch.Size([8, 4])
47. Transformer encoder
import torch
from torch import nn
layer = nn.TransformerEncoderLayer(d_model=64, nhead=4, dim_feedforward=128,
batch_first=True, norm_first=True)
encoder = nn.TransformerEncoder(layer, num_layers=2)
x = torch.randn(3, 10, 64) # (batch, seq, d_model)
pad_mask = torch.zeros(3, 10, dtype=torch.bool)
pad_mask[0, 7:] = True # True = padding to ignore
print(encoder(x, src_key_padding_mask=pad_mask).shape) # torch.Size([3, 10, 64])
48. Scaled dot-product attention with a causal mask
import torch
import torch.nn.functional as F
B, H, T, D = 2, 4, 6, 16
q, k, v = (torch.randn(B, H, T, D) for _ in range(3))
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # uses fused kernels when available
manual_scores = (q @ k.transpose(-2, -1)) / D ** 0.5
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
manual = manual_scores.masked_fill(mask, float("-inf")).softmax(-1) @ v
print(out.shape, torch.allclose(out, manual, atol=1e-5))
49. Custom weight initialization
import torch
from torch import nn
def init_weights(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
nn.init.zeros_(m.bias)
model = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Linear(32, 1))
model.apply(init_weights) # calls init_weights on every submodule
print(model[0].bias.abs().sum().item()) # 0.0
50. Freeze layers for transfer learning
import torch
from torch import nn
backbone = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Linear(32, 32))
head = nn.Linear(32, 2)
model = nn.Sequential(backbone, head)
for p in backbone.parameters():
p.requires_grad_(False)
optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=1e-3)
print(sum(p.numel() for p in model.parameters() if p.requires_grad)) # 66 (head only)
51. Buffers: state that is saved but not trained
import torch
from torch import nn
class RunningMean(nn.Module):
def __init__(self, dim):
super().__init__()
self.register_buffer("mean", torch.zeros(dim)) # moves with .to(), saved in state_dict
self.register_buffer("count", torch.tensor(0))
def forward(self, x):
if self.training:
self.count += x.shape[0]
self.mean += (x.sum(0) - x.shape[0] * self.mean) / self.count
return x - self.mean
m = RunningMean(3)
m(torch.ones(4, 3))
print(m.mean, list(m.state_dict().keys()), len(list(m.parameters()))) # ... ['mean', 'count'] 0
52. train() vs eval() mode
import torch
from torch import nn
model = nn.Sequential(nn.Linear(4, 4), nn.Dropout(p=0.5))
x = torch.ones(1, 4)
model.train()
print(model.training, model(x)) # dropout active: some zeros, others scaled by 2
model.eval()
print(model.training, torch.equal(model(x), model(x))) # deterministic: True
5. Losses and optimizers
53. Cross-entropy for classification (takes logits)
import torch
from torch import nn
logits = torch.tensor([[2.0, 0.5, -1.0], [0.1, 0.2, 3.0]]) # raw scores, no softmax
targets = torch.tensor([0, 2]) # class indices
loss = nn.CrossEntropyLoss()(logits, targets)
manual = -torch.log_softmax(logits, dim=1)[torch.arange(2), targets].mean()
print(loss.item(), torch.allclose(loss, manual))
54. Binary and multi-label classification
import torch
from torch import nn
logits = torch.tensor([[1.2, -0.3, 0.8], [-2.0, 0.5, 0.0]]) # 3 independent labels
targets = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0]]) # float targets
loss = nn.BCEWithLogitsLoss()(logits, targets) # sigmoid + BCE, numerically stable
pos_weighted = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([1.0, 3.0, 1.0]))(logits, targets)
print(loss.item(), pos_weighted.item())
preds = (torch.sigmoid(logits) > 0.5).int()
print(preds)
55. Regression losses
import torch
from torch import nn
pred = torch.tensor([2.5, 0.0, 2.0, 8.0])
target = torch.tensor([3.0, -0.5, 2.0, 7.0])
print(nn.MSELoss()(pred, target).item()) # 0.375
print(nn.L1Loss()(pred, target).item()) # 0.5
print(nn.HuberLoss(delta=1.0)(pred, target).item())
56. Class weights and label smoothing
import torch
from torch import nn
weights = torch.tensor([1.0, 5.0, 1.0]) # upweight a rare class
criterion = nn.CrossEntropyLoss(weight=weights, label_smoothing=0.1, ignore_index=-100)
logits = torch.randn(6, 3)
targets = torch.tensor([0, 1, 2, 1, -100, 0]) # -100 entries are ignored (e.g. padding)
print(criterion(logits, targets).item())
57. Optimizer step basics
import torch
from torch import nn
model = nn.Linear(3, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
x, y = torch.randn(16, 3), torch.randn(16, 1)
before = model.weight.clone()
optimizer.zero_grad()
loss = nn.functional.mse_loss(model(x), y)
loss.backward()
optimizer.step()
print(not torch.equal(before, model.weight)) # True: weights changed
58. AdamW with parameter groups (no weight decay on biases and norms)
import torch
from torch import nn
model = nn.Sequential(nn.Linear(16, 32), nn.LayerNorm(32), nn.Linear(32, 4))
decay, no_decay = [], []
for name, p in model.named_parameters():
(no_decay if p.ndim < 2 else decay).append(p) # biases and norm weights are 1-D
optimizer = torch.optim.AdamW(
[{"params": decay, "weight_decay": 0.01}, {"params": no_decay, "weight_decay": 0.0}],
lr=3e-4, betas=(0.9, 0.999),
)
print([len(g["params"]) for g in optimizer.param_groups]) # [2, 4]
59. Learning rate scheduler: warmup then cosine
import torch
from torch import nn
from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR
model = nn.Linear(4, 1)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
warmup = LinearLR(opt, start_factor=0.01, total_iters=100)
cosine = CosineAnnealingLR(opt, T_max=900, eta_min=1e-5)
sched = SequentialLR(opt, schedulers=[warmup, cosine], milestones=[100])
lrs = []
for step in range(1000):
opt.step() # (after loss.backward() in real training)
sched.step() # call after optimizer.step()
lrs.append(sched.get_last_lr()[0])
print(f"{lrs[0]:.2e} {max(lrs):.2e} {lrs[-1]:.2e}")
60. Change the learning rate manually
import torch
from torch import nn
opt = torch.optim.SGD(nn.Linear(2, 1).parameters(), lr=0.1)
for group in opt.param_groups:
group["lr"] *= 0.5
print(opt.param_groups[0]["lr"]) # 0.05
6. Training loops
61. Complete training loop (regression)
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(512, 3)
y = X @ torch.tensor([[2.0], [-1.0], [0.5]]) + 0.3 + 0.01 * torch.randn(512, 1)
model = nn.Linear(3, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.MSELoss()
for epoch in range(100):
opt.zero_grad()
loss = loss_fn(model(X), y)
loss.backward()
opt.step()
print(f"loss {loss.item():.5f}", model.weight.data.round(decimals=2), model.bias.data.round(decimals=2))
62. Mini-batch training with a DataLoader
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
torch.manual_seed(0)
X = torch.randn(1000, 20)
y = (X[:, 0] + X[:, 1] > 0).long()
loader = DataLoader(TensorDataset(X, y), batch_size=64, shuffle=True)
model = nn.Sequential(nn.Linear(20, 32), nn.ReLU(), nn.Linear(32, 2))
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
for epoch in range(5):
total = 0.0
for xb, yb in loader:
opt.zero_grad()
loss = nn.functional.cross_entropy(model(xb), yb)
loss.backward()
opt.step()
total += loss.item() * len(xb)
print(epoch, round(total / len(X), 4))
63. Evaluation loop with accuracy
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
def evaluate(model, loader):
model.eval()
correct = count = 0
loss_sum = 0.0
with torch.no_grad():
for xb, yb in loader:
logits = model(xb)
loss_sum += nn.functional.cross_entropy(logits, yb, reduction="sum").item()
correct += (logits.argmax(1) == yb).sum().item()
count += len(yb)
model.train()
return loss_sum / count, correct / count
model = nn.Linear(4, 3)
data = DataLoader(TensorDataset(torch.randn(50, 4), torch.randint(0, 3, (50,))), batch_size=16)
print(evaluate(model, data))
64. Train/validation split
import torch
from torch.utils.data import TensorDataset, random_split
ds = TensorDataset(torch.randn(1000, 8), torch.randint(0, 2, (1000,)))
train_ds, val_ds = random_split(ds, [0.8, 0.2], generator=torch.Generator().manual_seed(42))
print(len(train_ds), len(val_ds)) # 800 200
65. Early stopping and keeping the best model
import copy
import torch
from torch import nn
model = nn.Linear(4, 1)
best_loss, best_state, patience, bad_epochs = float("inf"), None, 3, 0
val_losses = [0.9, 0.7, 0.65, 0.66, 0.67, 0.70, 0.5] # pretend validation results
for epoch, val_loss in enumerate(val_losses):
if val_loss < best_loss - 1e-4:
best_loss, best_state, bad_epochs = val_loss, copy.deepcopy(model.state_dict()), 0
else:
bad_epochs += 1
if bad_epochs >= patience:
print(f"stopping at epoch {epoch}, best {best_loss}")
break
model.load_state_dict(best_state)
66. Gradient clipping
import torch
from torch import nn
model = nn.Linear(10, 1)
loss = (model(torch.randn(8, 10) * 1000) ** 2).mean()
loss.backward()
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # returns norm before clipping
after = torch.sqrt(sum(p.grad.pow(2).sum() for p in model.parameters()))
print(norm.item() > 1.0, round(after.item(), 4)) # True 1.0
67. Gradient accumulation (bigger effective batch)
import torch
from torch import nn
model = nn.Linear(10, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.01)
accum_steps = 4
batches = [(torch.randn(8, 10), torch.randn(8, 1)) for _ in range(8)]
opt.zero_grad()
for i, (xb, yb) in enumerate(batches):
loss = nn.functional.mse_loss(model(xb), yb) / accum_steps # average over accumulated batches
loss.backward()
if (i + 1) % accum_steps == 0:
opt.step()
opt.zero_grad()
print("updates:", len(batches) // accum_steps)
68. Mixed precision training (autocast)
import torch
from torch import nn
device = "cuda" if torch.cuda.is_available() else "cpu"
amp_dtype = torch.float16 if device == "cuda" else torch.bfloat16
model = nn.Linear(64, 10).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
scaler = torch.amp.GradScaler(device, enabled=(amp_dtype == torch.float16)) # needed for fp16 only
x, y = torch.randn(32, 64, device=device), torch.randint(0, 10, (32,), device=device)
with torch.autocast(device_type=device, dtype=amp_dtype):
loss = nn.functional.cross_entropy(model(x), y)
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()
opt.zero_grad()
print(device, amp_dtype, loss.item())
69. Reproducibility
import random
import numpy as np
import torch
def seed_everything(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed) # seeds CPU and all GPUs
torch.use_deterministic_algorithms(True, warn_only=True)
torch.backends.cudnn.benchmark = False
seed_everything(0)
a = torch.randn(3)
seed_everything(0)
print(torch.equal(a, torch.randn(3))) # True
# On CUDA, some deterministic ops also need: export CUBLAS_WORKSPACE_CONFIG=:4096:8
70. Progress logging every N steps
import time
import torch
from torch import nn
model = nn.Linear(4, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.05)
running, t0 = 0.0, time.perf_counter()
for step in range(1, 301):
x, y = torch.randn(32, 4), torch.randn(32, 1)
opt.zero_grad()
loss = nn.functional.mse_loss(model(x), y)
loss.backward()
opt.step()
running += loss.item()
if step % 100 == 0:
print(f"step {step} loss {running / 100:.4f} {100 / (time.perf_counter() - t0):.0f} it/s")
running, t0 = 0.0, time.perf_counter()
71. Training a classifier end to end (two moons style data)
import math
import torch
from torch import nn
torch.manual_seed(0)
n = 400
t = torch.rand(n) * math.pi
upper = torch.stack([torch.cos(t), torch.sin(t)], 1)
lower = torch.stack([1 - torch.cos(t), 0.5 - torch.sin(t)], 1)
X = torch.cat([upper, lower]) + 0.1 * torch.randn(2 * n, 2)
y = torch.cat([torch.zeros(n), torch.ones(n)]).long()
model = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 2))
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for _ in range(300):
opt.zero_grad()
loss = nn.functional.cross_entropy(model(X), y)
loss.backward()
opt.step()
acc = (model(X).argmax(1) == y).float().mean().item()
print(f"train accuracy {acc:.3f}") # close to 1.0
72. Overfit one batch to test your pipeline
import torch
from torch import nn
torch.manual_seed(0)
xb, yb = torch.randn(16, 10), torch.randint(0, 3, (16,))
model = nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 3))
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for _ in range(200):
opt.zero_grad()
loss = nn.functional.cross_entropy(model(xb), yb)
loss.backward()
opt.step()
print(f"{loss.item():.4f}") # should approach 0; if not, something is wrong
7. Data loading
73. A custom map-style Dataset
import torch
from torch.utils.data import Dataset
class SquaresDataset(Dataset):
def __init__(self, n):
self.x = torch.arange(n, dtype=torch.float32)
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
x = self.x[idx]
return x, x ** 2
ds = SquaresDataset(10)
print(len(ds), ds[3]) # 10 (tensor(3.), tensor(9.))
74. DataLoader options
import torch
from torch.utils.data import DataLoader, TensorDataset
ds = TensorDataset(torch.randn(100, 5), torch.randint(0, 2, (100,)))
loader = DataLoader(
ds,
batch_size=32,
shuffle=True, # reshuffle every epoch (training)
drop_last=True, # drop the final incomplete batch
num_workers=0, # >0 loads in background processes; guard with `if __name__ == "__main__"` in scripts
pin_memory=torch.cuda.is_available(), # faster host-to-GPU copies
)
xb, yb = next(iter(loader))
print(xb.shape, yb.shape, len(loader)) # torch.Size([32, 5]) torch.Size([32]) 3
75. Custom collate_fn for variable-length sequences
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
sequences = [torch.tensor([1, 2, 3]), torch.tensor([4, 5]), torch.tensor([6]), torch.tensor([7, 8, 9, 10])]
labels = [0, 1, 0, 1]
def collate(batch):
seqs, ys = zip(*batch)
lengths = torch.tensor([len(s) for s in seqs])
padded = pad_sequence(seqs, batch_first=True, padding_value=0)
return padded, lengths, torch.tensor(ys)
loader = DataLoader(list(zip(sequences, labels)), batch_size=2, collate_fn=collate)
for padded, lengths, ys in loader:
print(padded, lengths)
76. Packed sequences for RNNs
import torch
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
lstm = nn.LSTM(input_size=4, hidden_size=8, batch_first=True)
x = torch.randn(3, 5, 4) # padded batch
lengths = torch.tensor([5, 3, 2])
packed = pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
out, (h, c) = lstm(packed) # RNN skips the padding
out, out_lengths = pad_packed_sequence(out, batch_first=True)
print(out.shape, out_lengths, h.shape) # torch.Size([3, 5, 8]) tensor([5, 3, 2]) torch.Size([1, 3, 8])
77. Weighted sampling for imbalanced classes
import torch
from torch.utils.data import DataLoader, TensorDataset, WeightedRandomSampler
y = torch.tensor([0] * 90 + [1] * 10)
class_counts = torch.bincount(y)
sample_weights = (1.0 / class_counts.float())[y]
sampler = WeightedRandomSampler(sample_weights, num_samples=len(y), replacement=True)
loader = DataLoader(TensorDataset(torch.randn(100, 3), y), batch_size=100, sampler=sampler)
_, yb = next(iter(loader))
print(torch.bincount(yb)) # roughly balanced, e.g. tensor([52, 48])
78. An IterableDataset for streams
import torch
from torch.utils.data import DataLoader, IterableDataset
class LineStream(IterableDataset):
def __init__(self, lines):
self.lines = lines
def __iter__(self):
for line in self.lines: # could be reading a huge file lazily
yield torch.tensor([len(line)])
loader = DataLoader(LineStream(["a", "bb", "ccc", "dddd"]), batch_size=2)
print([b.flatten().tolist() for b in loader]) # [[1, 2], [3, 4]]
79. Image transforms with torchvision
# requires: torchvision
import torch
from torchvision.transforms import v2
transform = v2.Compose([
v2.RandomResizedCrop(size=(224, 224), antialias=True),
v2.RandomHorizontalFlip(p=0.5),
v2.ToDtype(torch.float32, scale=True), # uint8 [0, 255] -> float [0, 1]
v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
img = torch.randint(0, 256, (3, 300, 400), dtype=torch.uint8) # a fake image (C, H, W)
print(transform(img).shape) # torch.Size([3, 224, 224])
80. ImageFolder layout and loader
# requires: torchvision (and an image folder on disk) # skip-test
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import v2
import torch
# data/train/cat/001.jpg, data/train/dog/002.jpg, ... -> class indices from folder names
tf = v2.Compose([v2.Resize((128, 128)), v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])
train = datasets.ImageFolder("data/train", transform=tf)
loader = DataLoader(train, batch_size=32, shuffle=True, num_workers=4)
print(train.classes, train.class_to_idx)
8. Devices and performance
81. Pick the best available device
import torch
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available(): # Apple Silicon GPU
device = torch.device("mps")
else:
device = torch.device("cpu")
print(device)
82. Move models and data to a device
import torch
from torch import nn
device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Linear(8, 2).to(device) # modules move in place
x = torch.randn(4, 8).to(device) # tensors return a new tensor
y = torch.randn(4, 8, device=device) # or create directly on the device
print(next(model.parameters()).device, model(x).device, y.device)
83. GPU info and memory
import torch
if torch.cuda.is_available():
print(torch.cuda.device_count(), torch.cuda.get_device_name(0))
x = torch.randn(1024, 1024, device="cuda")
print(f"{torch.cuda.memory_allocated() / 2**20:.1f} MiB allocated")
print(f"{torch.cuda.max_memory_allocated() / 2**20:.1f} MiB peak")
del x
torch.cuda.empty_cache() # returns cached blocks to the driver
else:
print("no CUDA device")
84. Time GPU code correctly
import time
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
a = torch.randn(2048, 2048, device=device)
for _ in range(3):
a @ a # warm up
if device == "cuda":
torch.cuda.synchronize() # GPU ops are asynchronous
t0 = time.perf_counter()
for _ in range(10):
a @ a
if device == "cuda":
torch.cuda.synchronize()
print(f"{(time.perf_counter() - t0) / 10 * 1000:.2f} ms per matmul on {device}")
85. torch.compile
import torch
from torch import nn
model = nn.Sequential(nn.Linear(64, 256), nn.GELU(), nn.Linear(256, 64))
compiled = torch.compile(model) # first call compiles (slow); later calls are faster
x = torch.randn(32, 64)
print(torch.allclose(compiled(x), model(x), atol=1e-5))
# Needs a working C++ compiler on CPU; use mode="reduce-overhead" or "max-autotune" to trade compile time for speed.
86. TF32 and matmul precision on NVIDIA GPUs
import torch
# Allow TensorFloat-32 for float32 matmuls on Ampere and newer GPUs: much faster, slightly less precise.
torch.set_float32_matmul_precision("high") # "highest" (default), "high", or "medium"
print(torch.get_float32_matmul_precision())
87. Activation checkpointing to save memory
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
block = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Linear(2048, 512))
x = torch.randn(16, 512, requires_grad=True)
y = checkpoint(block, x, use_reentrant=False) # activations recomputed during backward
y.sum().backward()
print(x.grad.shape)
88. Multi-GPU basics (DistributedDataParallel skeleton)
# skip-test: run with `torchrun --nproc_per_node=NUM_GPUS train.py`
import os
import torch
import torch.distributed as dist
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed import DistributedSampler
dist.init_process_group(backend="nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
model = DDP(nn.Linear(10, 1).cuda(local_rank), device_ids=[local_rank])
ds = TensorDataset(torch.randn(1024, 10), torch.randn(1024, 1))
sampler = DistributedSampler(ds) # each process gets a different shard
loader = DataLoader(ds, batch_size=32, sampler=sampler)
opt = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(3):
sampler.set_epoch(epoch) # different shuffle each epoch
for xb, yb in loader:
opt.zero_grad()
nn.functional.mse_loss(model(xb.cuda()), yb.cuda()).backward()
opt.step()
dist.destroy_process_group()
89. Profile a model
import torch
from torch import nn
from torch.profiler import ProfilerActivity, profile
model = nn.Sequential(nn.Linear(256, 1024), nn.ReLU(), nn.Linear(1024, 256))
x = torch.randn(64, 256)
with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:
for _ in range(5):
model(x)
print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=5))
90. Inference fast path
import torch
from torch import nn
model = nn.Sequential(nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 4))
model.eval() # dropout off, BatchNorm uses running stats
with torch.inference_mode(): # no autograd bookkeeping
probs = model(torch.randn(8, 32)).softmax(dim=-1)
print(probs.sum(dim=-1)) # all ones
9. Saving, loading and export
91. Save and load a state_dict (recommended)
import os
import tempfile
import torch
from torch import nn
model = nn.Linear(4, 2)
path = os.path.join(tempfile.mkdtemp(), "model.pt")
torch.save(model.state_dict(), path)
restored = nn.Linear(4, 2) # rebuild the same architecture
restored.load_state_dict(torch.load(path, weights_only=True))
print(torch.equal(model.weight, restored.weight)) # True
92. Save a full training checkpoint and resume
import os
import tempfile
import torch
from torch import nn
model = nn.Linear(4, 2)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=10)
path = os.path.join(tempfile.mkdtemp(), "ckpt.pt")
torch.save({"epoch": 5, "model": model.state_dict(), "optimizer": opt.state_dict(),
"scheduler": sched.state_dict()}, path)
ckpt = torch.load(path, weights_only=True)
model.load_state_dict(ckpt["model"])
opt.load_state_dict(ckpt["optimizer"])
sched.load_state_dict(ckpt["scheduler"])
start_epoch = ckpt["epoch"] + 1
print(start_epoch) # 6
93. Load a GPU checkpoint on a CPU machine
import io
import torch
from torch import nn
buffer = io.BytesIO()
torch.save(nn.Linear(2, 2).state_dict(), buffer)
buffer.seek(0)
state = torch.load(buffer, map_location="cpu", weights_only=True) # remaps tensors saved on GPU
print({k: v.device for k, v in state.items()})
94. Load weights with mismatched keys
import torch
from torch import nn
old = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3))
new = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 5)) # new head size
state = {k: v for k, v in old.state_dict().items() if not k.startswith("2.")}
result = new.load_state_dict(state, strict=False)
print(result.missing_keys, result.unexpected_keys) # ['2.weight', '2.bias'] []
95. Export with torch.export
import torch
from torch import nn
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2)).eval()
example = (torch.randn(1, 4),)
exported = torch.export.export(model, example) # a whole-graph, ahead-of-time representation
print(exported.module()(torch.randn(1, 4)).shape) # torch.Size([1, 2])
96. Export to ONNX
# requires: onnx, onnxscript # skip-test
import torch
from torch import nn
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2)).eval()
onnx_program = torch.onnx.export(model, (torch.randn(1, 4),), dynamo=True)
onnx_program.save("model.onnx") # run with onnxruntime or other ONNX runtimes
10. Debugging and utilities
97. Print shapes with forward hooks
import torch
from torch import nn
model = nn.Sequential(nn.Conv2d(3, 8, 3), nn.ReLU(), nn.Flatten(), nn.Linear(8 * 30 * 30, 10))
def show_shape(module, inputs, output):
print(f"{type(module).__name__:<8} {tuple(inputs[0].shape)} -> {tuple(output.shape)}")
handles = [m.register_forward_hook(show_shape) for m in model]
model(torch.randn(2, 3, 32, 32))
for h in handles:
h.remove()
98. Find where NaNs come from
import torch
with torch.autograd.detect_anomaly(): # slow: use only while debugging
x = torch.tensor([0.0], requires_grad=True)
y = torch.sqrt(x) * 0 # sqrt'(0) is inf, inf * 0 = nan in backward
try:
y.backward()
except RuntimeError as e:
print("caught:", str(e).splitlines()[0])
print(torch.isfinite(torch.tensor([1.0, float("inf"), float("nan")]))) # tensor([ True, False, False])
99. Check gradient flow per layer
import torch
from torch import nn
model = nn.Sequential(*[m for _ in range(6) for m in (nn.Linear(32, 32), nn.Sigmoid())], nn.Linear(32, 1))
model(torch.randn(64, 32)).pow(2).mean().backward()
for name, p in model.named_parameters():
if name.endswith("weight"):
print(f"{name:<10} grad norm {p.grad.norm():.2e}") # early layers much smaller: vanishing gradients
100. Model summary and environment report
import platform
import torch
from torch import nn
model = nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 2))
print(model)
print(f"params: {sum(p.numel() for p in model.parameters()):,}")
print("torch", torch.__version__, "| python", platform.python_version())
print("cuda", torch.cuda.is_available(), "| mps", torch.backends.mps.is_available())
# For bug reports, run: python -m torch.utils.collect_env
Versions
All snippets use stable PyTorch 2.x APIs. A few depend on newer releases:
| Snippet | Needs |
|---|---|
36 (torch.func) |
PyTorch 2.0+ |
64 (random_split with fractions) |
PyTorch 1.13+ |
68 (torch.amp.GradScaler(device)) |
PyTorch 2.3+ (older: torch.cuda.amp.GradScaler()) |
85 (torch.compile) |
PyTorch 2.0+, plus a C++ compiler for the CPU backend |
91 to 93 (weights_only=True) |
PyTorch 1.13+; it is the default from 2.6, and passing it explicitly is clearer |
95 (torch.export) |
PyTorch 2.1+ |
96 (dynamo=True ONNX export) |
PyTorch 2.5+ with onnx and onnxscript installed |
79, 80 (torchvision.transforms.v2) |
torchvision 0.16+ |
Check your version with python -c "import torch; print(torch.__version__)".
Common errors and fixes
| Error message (abbreviated) | Cause | Fix |
|---|---|---|
mat1 and mat2 shapes cannot be multiplied (AxB and CxD) |
input features B do not match the layer’s in_features C |
print shapes (snippet 97); fix nn.Linear(in, out) or flatten correctly |
Expected all tensors to be on the same device |
model on GPU, data on CPU or vice versa | move both with .to(device) (snippet 82) |
expected scalar type Long but found Float |
CrossEntropyLoss targets must be integer class indices |
targets.long() |
Target size must be the same as input size |
BCEWithLogitsLoss needs float targets with the same shape as logits |
targets.float().view_as(logits) |
element 0 of tensors does not require grad |
calling backward() on something computed without gradients |
remove no_grad(), check requires_grad, do not .detach() |
Trying to backward through the graph a second time |
reusing a graph after backward() freed it |
recompute the forward pass, or retain_graph=True if truly needed |
one of the variables needed for gradient computation has been modified by an inplace operation |
in-place op on a tensor needed by backward | replace x += ... with x = x + ... in the model |
view size is not compatible with input tensor's size and stride |
view on a non-contiguous tensor |
.reshape(...) or .contiguous().view(...) (snippet 19) |
CUDA out of memory |
batch or model too large | smaller batch, mixed precision (68), gradient accumulation (67), checkpointing (87) |
Can't pickle local object with num_workers > 0 |
worker processes cannot import a lambda or local function | define collate functions and datasets at module level; use if __name__ == "__main__": |
Weights only load failed |
checkpoint contains arbitrary Python objects | save only tensors and plain containers; load untrusted files only with weights_only=True |
How the tests work
tests/test_snippets.py reads this README, extracts every numbered snippet and:
- Checks there are exactly 100 snippets, numbered 1 to 100.
- Parses each one with Python’s
astmodule (catches syntax errors without PyTorch). - If PyTorch is installed, executes each snippet in a fresh namespace. Snippets that need extra packages (marked
# requires: ...) are skipped if those packages are missing, and snippets marked# skip-test(multi-GPU, files on disk) are only syntax-checked.
python -m unittest discover -s tests -v
Further learning
- PyTorch tutorials (official)
- PyTorch documentation (official API reference)
- Dive into Deep Learning (free book with PyTorch code)
- Deep Learning with PyTorch: A 60 Minute Blitz (official)
FAQ
How do I check if PyTorch is using my GPU? torch.cuda.is_available() for NVIDIA, torch.backends.mps.is_available() for Apple Silicon (snippet 81), then check next(model.parameters()).device.
What is the difference between view and reshape? view never copies and needs contiguous memory; reshape returns a view when it can and copies otherwise (snippet 19).
Why do I need optimizer.zero_grad()? Gradients accumulate by default (snippet 31). Without zeroing, each step uses the sum of all previous gradients.
What does model.eval() do? It switches dropout off and makes BatchNorm use running statistics. It does not disable gradients; use torch.no_grad() or torch.inference_mode() for that (snippets 32, 52, 90).
torch.no_grad() or torch.inference_mode()? inference_mode is stricter and slightly faster for pure inference; use no_grad when tensors created inside may later be used in autograd.
Should I save the whole model or the state_dict? The state_dict (snippet 91). Pickling the whole model ties the file to your exact code and needs unsafe loading.
Why is my loss NaN? Usually a learning rate that is too high, log of zero, or fp16 overflow. Lower the LR, use logit-based losses, clip gradients (snippet 66), and find the source with anomaly detection (snippet 98).
How do I make results reproducible? Seed everything and enable deterministic algorithms (snippet 69). Bitwise reproducibility across different GPUs or library versions is not guaranteed.
Is torch.compile worth it? Often for training and repeated inference on GPUs, with speedups that depend on the model. The first call is slow while it compiles; measure on your workload (snippet 85).
PyTorch or TensorFlow in 2026? Most research code and open models use PyTorch, and Hugging Face transformers v5 is PyTorch-only. Keras 3 can also run on a PyTorch backend.
Where to go next
- Learn the Basics, the official tutorial series.
- PyTorch recipes for focused how-tos.
- The deep learning cheat sheet in this collection for the math behind the snippets.
- The Hugging Face transformers cheat sheet in this collection for pretrained models and fine-tuning.
- Rebuild a classic model from scratch (an MLP on MNIST, a small CNN on CIFAR-10, a character-level Transformer) using only snippets from this page.
Contributing
PRs are welcome. Every snippet must stay self-contained (its own imports), run on CPU in a few seconds, use synthetic data or no data, and print something checkable. Keep the count at 100: propose replacements rather than additions. Run the tests before opening a PR, and mention the PyTorch version you used.
If these snippets saved you time, a star helps others find them.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.