PyTorch Essentials
PyTorch rounds test two things: that you can write a model part as a clean nn.Module, and that you know what
autograd does for you and what it doesn't. Most bugs candidates hit are not about the math. They are about
gradients that pile up, parameters PyTorch can't see, a model left in training mode, or a tensor on the wrong
device.
This page covers the pieces in the order you use them. If you know NumPy, most of the tensor API is the same with
dim= in place of axis=; the parts that differ are the ones below.
Tensors
A tensor is a NumPy array with two extras: it can live on a GPU, and it can record the operations applied to it
so gradients can be computed. The API mirrors NumPy's, but two defaults differ. New float tensors are float32,
not float64. And torch.from_numpy shares memory with the array, so changing one changes the other.
import numpy as np
import torch
t = torch.tensor([1.0, 2.0, 3.0])
assert t.dtype == torch.float32 # NumPy would give float64
a = np.arange(3.0)
s = torch.from_numpy(a) # shares memory, keeps float64
a[0] = 10.0
assert s[0].item() == 10.0 and s.dtype == torch.float64
x = torch.randn(2, 3, 4) # (B, T, D)
assert x.sum(dim=-1).shape == (2, 3) # dim= plays the role of axis=
assert x.transpose(-2, -1).shape == (2, 4, 3)
assert x.mean(dim=1, keepdim=True).shape == (2, 1, 4) # keepdim, not keepdims
Mixing float32 and float64 tensors in one operation still works for most ops, but the result's precision
surprises people, and some ops refuse it. Pick one dtype per model: float32 for training, .double() on the model
and inputs when running a gradient check. Use .item() to turn a one-element
tensor into a Python number, for logging or comparisons.
Autograd
Autograd records every operation on tensors that have requires_grad=True and, on .backward(), walks that
record backward to fill each leaf tensor's .grad. You write only the forward pass. The rule that catches people
is that .backward() adds to .grad rather than replacing it.
w = torch.tensor([2.0, -1.0], requires_grad=True) # a leaf: we want d loss / dw
x = torch.tensor([3.0, 4.0])
loss = ((w * x).sum() - 1.0) ** 2 # (6 - 4 - 1)^2 = 1
loss.backward() # d loss / dw = 2 (w.x - 1) x = [6, 8]
assert torch.allclose(w.grad, torch.tensor([6.0, 8.0]))
loss = ((w * x).sum() - 1.0) ** 2
loss.backward() # a second backward ADDS
assert torch.allclose(w.grad, torch.tensor([12.0, 16.0]))
w.grad = None # what optimizer.zero_grad() does
loss = ((w * x).sum() - 1.0) ** 2
loss.backward()
with torch.no_grad(): # an update must not be recorded
w -= 0.01 * w.grad
assert torch.allclose(w, torch.tensor([1.94, -1.08]))
Accumulation is a feature: it is how you sum gradients over several small batches before one update. But if
you forget to clear .grad, every step uses the sum of all past gradients, and the loss usually blows up after a
few steps. Two related rules: update parameters inside torch.no_grad() (an in-place change to a leaf that
requires grad raises an error otherwise), and call .detach() on any tensor you keep around for logging or as a
target, or the graph behind it stays alive and memory grows each step.
nn.Module and Parameters
An nn.Module is a container that finds its own parameters. Assign a layer or an nn.Parameter as an attribute
in __init__, and model.parameters() returns it, the optimizer updates it, .to(device) moves it and
state_dict() saves it. Write the computation in forward, and call the model as model(x), not
model.forward(x), so hooks run.
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, d_in: int, d_hidden: int, d_out: int) -> None:
super().__init__()
self.scale = nn.Parameter(torch.ones(d_out)) # a raw learnable tensor
self.fc1 = nn.Linear(d_in, d_hidden) # registered because it is an attribute
self.fc2 = nn.Linear(d_hidden, d_out)
def forward(self, x: torch.Tensor) -> torch.Tensor: # (B, d_in) -> (B, d_out)
return self.fc2(torch.relu(self.fc1(x))) * self.scale
model = MLP(4, 8, 3)
assert [n for n, _ in model.named_parameters()] == [
"scale", "fc1.weight", "fc1.bias", "fc2.weight", "fc2.bias"]
assert model.fc1.weight.shape == (8, 4) # nn.Linear stores (out, in) and computes x @ W.T
assert model(torch.randn(5, 4)).shape == (5, 3)
class Broken(nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = [nn.Linear(4, 4) for _ in range(2)] # a plain list: invisible to PyTorch
assert len(list(Broken().parameters())) == 0 # use nn.ModuleList instead
The Broken module trains without an error: its layers run in forward, but the optimizer never sees them, so
their weights stay at their random start. When a model holds a list or dict of layers, use nn.ModuleList or
nn.ModuleDict. For state that should be saved and moved with the model but not trained, such as BatchNorm's
running mean, use self.register_buffer("name", tensor).
Devices
Every tensor lives on a device, and an operation needs all its inputs on the same one. model.to(device) moves
the parameters in place; inputs and any tensors you create inside forward must be put there too. The safe
habit is to create new tensors with device=x.device, which works on any machine.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device) # moves parameters, returns the module
xb = torch.randn(5, 4, device=device)
mask = torch.ones(5, 3, dtype=torch.bool, device=xb.device) # new tensors follow the input
assert model(xb).masked_fill(~mask, 0).device.type == device.type
The error for a mismatch says "Expected all tensors to be on the same device", and it usually points at a mask or
constant built with torch.ones(...) inside forward. Interview pads usually run on CPU, but writing
device=x.device costs nothing and shows you have trained on a GPU. Move data to the device per batch, not the
whole dataset, when it won't fit in GPU memory.
no_grad and eval
torch.no_grad() and model.eval() do different jobs, and evaluation needs both. no_grad stops autograd from
recording, which saves memory and time. eval() switches layers whose behavior differs between training and
inference: dropout stops dropping, and BatchNorm uses its running statistics instead of the batch's.
drop = nn.Dropout(p=0.5)
h = torch.ones(1000)
drop.train()
assert (drop(h) == 0).any() and torch.isclose(drop(h).mean(), torch.tensor(1.0), atol=0.15)
drop.eval()
assert torch.equal(drop(h), h) # identity in eval mode
model.eval()
with torch.no_grad():
out = model(xb)
assert not out.requires_grad # no graph was built
model.train() # switch back before training again
In training mode, dropout zeroes half the entries and doubles the rest, so the mean stays near 1; in eval mode it
does nothing. Forgetting model.eval() makes validation scores noisy and lower than they should be. Forgetting
model.train() afterward is quieter: training continues without dropout. torch.inference_mode() is a stricter
no_grad for pure inference.
The Shape of a Training Step
Every PyTorch training loop has the same four lines per batch: clear the gradients, run the forward pass and loss, backpropagate, and step the optimizer. Around them sit shuffling, batching and evaluation, covered in Writing a Training Loop.
torch.manual_seed(0)
X = torch.randn(256, 4)
y = (X[:, 0] + X[:, 1] > 0).long() + (X[:, 2] > 1).long() # labels in {0, 1, 2}
model = MLP(4, 16, 3)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.CrossEntropyLoss() # raw logits (B, C) and int labels (B,)
losses = []
for epoch in range(100):
perm = torch.randperm(256) # reshuffle every epoch
for i in range(0, 256, 64):
idx = perm[i:i + 64]
opt.zero_grad() # 1. clear old gradients
loss = loss_fn(model(X[idx]), y[idx]) # 2. forward and loss
loss.backward() # 3. fill .grad
opt.step() # 4. update the parameters
losses.append(loss.item()) # .item(): a float, not a graph
print(round(losses[0], 3), round(losses[-1], 3))
assert losses[-1] < losses[0] / 3
The loss falls from about 1.12 after the first epoch to about 0.07 after the last. Two details are worth saying
while you write it. nn.CrossEntropyLoss applies log-softmax itself, so the model returns raw logits; adding a
softmax in forward trains much more slowly and is a common planted bug. And losses.append(loss) without
.item() keeps every step's graph alive. Before training on real data, train on one batch until the loss is
near zero: if the model can't memorize 64 examples, the bug is in the code, not the data.
Key Takeaways
- Tensors default to float32,
dim=replacesaxis=, andtorch.from_numpyshares memory. .backward()adds to.grad. Callzero_grad()every step, update insidetorch.no_grad(), and.detach()or.item()anything you keep.- Parameters must be attributes,
nn.Parameters or insidenn.ModuleList; a plain Python list trains silently wrong.nn.Linearstores its weight as(out, in). - Create tensors with
device=x.deviceso the code runs anywhere. - Evaluation needs both
model.eval()andtorch.no_grad(); switch back withmodel.train(). - A training step is
zero_grad, forward and loss,backward,step. Feed losses raw logits, and overfit one batch first.