42. Deep learning with PyTorch — Cheat sheet
The essentials of module 42 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| make runs reproducible | seed and one thread | torch.manual_seed(42); torch.set_num_threads(1) |
| make a tensor from a list | torch.tensor |
torch.tensor([21.5, 22.1]) |
| make a float32 tensor from NumPy | torch.as_tensor(..., dtype=) |
torch.as_tensor(arr, dtype=torch.float32) |
| share memory with a NumPy array | torch.from_numpy |
torch.from_numpy(arr) |
| get a NumPy array back | .numpy() (after .detach() if it has a graph) |
t.detach().numpy() |
| get one Python number | .item() |
loss.item() |
| change the dtype | .float(), .long(), .to(dtype) |
labels.long() |
| add or remove a size-1 dimension | unsqueeze, squeeze |
x.unsqueeze(1), out.squeeze(1) |
| reduce over rows | dim=0 |
X.mean(dim=0) |
| standardize like scikit-learn | population std | (X - X.mean(0)) / X.std(0, correction=0) |
| track gradients | requires_grad=True |
w = torch.tensor(1.0, requires_grad=True) |
| compute gradients | backward() then .grad |
loss.backward(); w.grad |
| turn off the graph | torch.no_grad() |
with torch.no_grad(): pred = model(X) |
| write a model | subclass nn.Module |
class Net(nn.Module): ... |
| chain layers | nn.Sequential |
nn.Sequential(nn.Linear(22, 32), nn.ReLU()) |
| list learned tensors | parameters(), named_parameters() |
sum(p.numel() for p in m.parameters()) |
| binary classification loss | BCEWithLogitsLoss on logits |
nn.BCEWithLogitsLoss(pos_weight=w) |
| multiclass loss | CrossEntropyLoss on logits, int64 class-index targets |
nn.CrossEntropyLoss() |
| a good default optimizer | AdamW |
torch.optim.AdamW(m.parameters(), lr=1e-3) |
| batch and shuffle data | TensorDataset + DataLoader |
DataLoader(ds, batch_size=64, shuffle=True) |
| switch dropout off to predict | eval mode | model.eval() |
| turn logits into probabilities | sigmoid or softmax | torch.sigmoid(logits), logits.softmax(dim=1) |
| pick the predicted class | argmax |
logits.argmax(dim=1) |
| save a model | state_dict + torch.save |
torch.save(m.state_dict(), "output/m.pt") |
| load a model without running pickled code | weights_only=True |
m.load_state_dict(torch.load(p, weights_only=True)) |
| copy the best weights | copy.deepcopy |
best = copy.deepcopy(m.state_dict()) |
| count batches per epoch | len(loader) |
len(DataLoader(ds, batch_size=64)) |
Setup and reproducibility
Section titled “Setup and reproducibility”import copy
import numpy as npimport torchfrom torch import nnfrom torch.utils.data import DataLoader, TensorDataset
torch.set_num_threads(1) # results depend on thread count; also no oversubscriptiontorch.manual_seed(42) # weights, shuffles, dropoutprint(torch.get_num_threads(), torch.rand(2))1 tensor([0.8823, 0.9150])| Source of randomness | Control |
|---|---|
initial weights, dropout, torch.rand* |
torch.manual_seed(42) |
DataLoader shuffling |
generator=torch.Generator().manual_seed(42) |
| NumPy and scikit-learn | np.random.default_rng(42), random_state=42 |
| sums whose last digits depend on the thread count | torch.set_num_threads(1) (the default count differs between machines) |
| a library function that should not touch global state | with torch.random.fork_rng(devices=[]): ... |
| save and restore generator state | torch.get_rng_state(), g.get_state(), set_state(...) |
Tensors
Section titled “Tensors”| Create | Result |
|---|---|
torch.tensor([1.0, 2.0]) |
float32 copy |
torch.tensor([1, 2]) |
int64 copy |
torch.zeros(2, 3), ones, full((2, 3), 7.0) |
filled |
torch.arange(0, 10, 2), linspace(0, 1, 5) |
ranges |
torch.rand(2, 3), randn, randint(0, 10, (2, 3)) |
random |
torch.zeros_like(t), ones_like(t) |
same shape and dtype |
torch.eye(3) |
identity matrix |
| dtype | Use | Convert |
|---|---|---|
float32 |
features, weights, BCE/MSE targets | .float() |
float64 |
gradient checks, NumPy default | .double() |
int64 |
class labels for CrossEntropyLoss, indices |
.long() |
bool |
masks | t > 0 |
X = torch.arange(12.0).reshape(3, 4) # 3 samples, 4 featuresprint(X.shape, X.dtype, X.ndim, X.numel())print(X[:, 0].shape, X[:, :1].shape, X.unsqueeze(0).shape, X.T.shape)print(X.sum(dim=0), X.mean(dim=1, keepdim=True).shape)print(X @ torch.ones(4), X.max(dim=1).values, X.argmax(dim=1))torch.Size([3, 4]) torch.float32 2 12torch.Size([3]) torch.Size([3, 1]) torch.Size([1, 3, 4]) torch.Size([4, 3])tensor([12., 15., 18., 21.]) torch.Size([3, 1])tensor([ 6., 22., 38.]) tensor([ 3., 7., 11.]) tensor([3, 3, 3])| Shape tool | Effect |
|---|---|
reshape(a, b), reshape(-1) |
new shape, same values (-1 = infer) |
view(a, b) |
like reshape, needs contiguous memory |
unsqueeze(d) / squeeze(d) |
add / remove a size-1 dimension at d |
flatten(start_dim=1) |
keep the batch dimension, join the rest |
t.T, t.permute(0, 2, 3, 1) |
swap / reorder dimensions |
torch.cat([a, b], dim=0) |
join along an existing dimension |
torch.stack([a, b]) |
join along a new dimension |
Broadcasting follows NumPy: align shapes from the right; size 1 or missing dimensions stretch.
mean = X.mean(dim=0) # (4,)std = X.std(dim=0, correction=0) # population std, like StandardScalerZ = (X - mean) / std # (3, 4) - (4,) broadcasts over the rowsprint(Z.round(decimals=3))tensor([[-1.2250, -1.2250, -1.2250, -1.2250], [ 0.0000, 0.0000, 0.0000, 0.0000], [ 1.2250, 1.2250, 1.2250, 1.2250]])NumPy interop
Section titled “NumPy interop”| Call | Copies | dtype |
|---|---|---|
torch.from_numpy(arr) |
no (shared memory) | kept (float64 stays float64) |
torch.as_tensor(arr, dtype=torch.float32) |
only if the dtype changes | as asked |
torch.tensor(arr, dtype=torch.float32) |
always | as asked |
t.numpy() |
no (shared memory) | kept; fails if t.requires_grad |
t.detach().numpy() |
no | safe for tensors with a graph |
t.item(), t.tolist() |
yes | Python numbers |
Autograd
Section titled “Autograd”w = torch.tensor(2.0, requires_grad=True)loss = (w * 3.0 - 5.0) ** 2 # dL/dw = 2(3w - 5) * 3 = 6loss.backward()print(w.grad, loss.grad_fn.name())with torch.no_grad(): w -= 0.1 * w.grad # update outside the graphw.grad.zero_() # backward() adds; reset before the next oneprint(round(w.item(), 2), w.grad)tensor(6.) PowBackward01.4 tensor(0.)| Rule | Code |
|---|---|
| gradients accumulate | optimizer.zero_grad() each step |
| updates outside the graph | with torch.no_grad(): w -= lr * w.grad |
| evaluation without a graph | with torch.no_grad(): or torch.inference_mode() |
| leave the graph to plot or store | t.detach() |
only leaf tensors get .grad |
create weights with requires_grad=True |
| check a gradient | central difference in float64; torch.autograd.gradcheck |
nn.Module
Section titled “nn.Module”class ChurnMLP(nn.Module): """22 features -> hidden layers -> 1 logit."""
def __init__(self, n_features: int, hidden=(32, 16), dropout=0.0) -> None: super().__init__() # always first self.hidden = hidden # hyperparameter: plain attribute layers: list[nn.Module] = [] for size_in, size_out in zip((n_features, *hidden), hidden, strict=False): layers += [nn.Linear(size_in, size_out), nn.ReLU(), nn.Dropout(dropout)] layers.append(nn.Linear(hidden[-1], 1)) self.net = nn.Sequential(*layers) # registered: its weights are parameters
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.net(x).squeeze(1) # (batch,) logits
model = ChurnMLP(22)print(sum(p.numel() for p in model.parameters()))print([name for name, _ in model.named_parameters()][:2])print(model(torch.zeros(5, 22)).shape)1281['net.0.weight', 'net.0.bias']torch.Size([5])| minilearn / scikit-learn | PyTorch |
|---|---|
BaseEstimator |
nn.Module |
hyperparameters in __init__ |
hyperparameters and layers in __init__ |
learned coef_, created in fit |
nn.Parameters, created in __init__ (random) |
fit(X, y) |
your training loop (or a wrapper estimator) |
predict(X) |
forward(x), called as model(x) |
get_params() |
plain attributes |
| learned attributes / joblib | state_dict() / torch.save |
Pipeline |
nn.Sequential |
| Layer | Shape in → out | Parameters |
|---|---|---|
nn.Linear(i, o) |
(n, i) → (n, o) |
i·o + o |
nn.Conv2d(c, k, 3, padding=1) |
(n, c, H, W) → (n, k, H, W) |
k·c·9 + k |
nn.MaxPool2d(2) |
(n, c, H, W) → (n, c, H//2, W//2) |
0 |
nn.Flatten() |
(n, c, H, W) → (n, c·H·W) |
0 |
nn.ReLU(), nn.Tanh(), nn.Sigmoid() |
same shape | 0 |
nn.Dropout(p) |
same shape | 0 |
nn.BatchNorm1d(f) |
(n, f) → (n, f) |
2f (+ running stats) |
nn.Embedding(v, d) |
(n,) int64 → (n, d) |
v·d |
Losses and output layers
Section titled “Losses and output layers”| Task | Last layer | Loss | Target | To predict |
|---|---|---|---|---|
| regression | Linear(h, 1) |
MSELoss() / L1Loss() |
float, same shape | the output |
| binary | Linear(h, 1) |
BCEWithLogitsLoss(pos_weight=…) |
float 0./1., same shape | torch.sigmoid(z) |
| multiclass | Linear(h, K) |
CrossEntropyLoss() |
int64 (n,), or float probabilities (n, K) |
z.softmax(1), z.argmax(1) |
logits = torch.tensor([2.0, -1.0, 0.5])targets = torch.tensor([1.0, 0.0, 1.0])plain = nn.BCEWithLogitsLoss()(logits, targets)weighted = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(4.0))(logits, targets)scores = torch.tensor([[2.0, 0.1, -1.0], [0.0, 1.5, 0.2]])ce = nn.CrossEntropyLoss()(scores, torch.tensor([0, 1]))print(round(plain.item(), 4), round(weighted.item(), 4), round(ce.item(), 4))print(torch.sigmoid(logits).round(decimals=3), scores.argmax(dim=1))0.3048 0.9058 0.2922tensor([0.8810, 0.2690, 0.6220]) tensor([0, 1])pos_weight = n_negative / n_positive balances the classes (like class_weight="balanced"). It raises the probabilities; it keeps most of the ranking.
Optimizers
Section titled “Optimizers”| Optimizer | When | Typical lr |
|---|---|---|
SGD(params, lr, momentum=0.9) |
simple models, well-tuned schedules | 0.01–0.1 |
Adam(params, lr) |
a fast default | 1e-3 |
AdamW(params, lr, weight_decay=0.01) |
the default with decoupled weight decay | 1e-3 |
lr_scheduler.ReduceLROnPlateau(opt) |
lower the rate when the validation loss stalls | — |
lr_scheduler.OneCycleLR(opt, max_lr, total_steps) |
warm up, then anneal | — |
The training loop
Section titled “The training loop”torch.manual_seed(42)X_toy = torch.randn(200, 22)y_toy = (X_toy[:, 0] + X_toy[:, 1] > 0).float() # a learnable ruleloader = DataLoader(TensorDataset(X_toy, y_toy), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42))model = ChurnMLP(22)loss_fn = nn.BCEWithLogitsLoss()optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2)for epoch in range(1, 6): model.train() # dropout on for xb, yb in loader: optimizer.zero_grad() # 1. clear old gradients loss = loss_fn(model(xb), yb) # forward loss.backward() # 2. gradients optimizer.step() # 3. update model.eval() # dropout off with torch.no_grad(): acc = ((model(X_toy) > 0).float() == y_toy).float().mean().item() print(epoch, round(loss.item(), 4), round(acc, 3)) # last-batch loss, accuracy1 0.6661 0.8052 0.5523 0.8753 0.2428 0.9354 0.3412 0.985 0.096 0.975| Term | Meaning |
|---|---|
| batch | the rows of one optimizer step |
| epoch | one pass over all training rows; len(loader) steps |
drop_last=True |
skip the last, smaller batch |
Dataset |
any object with __len__ and __getitem__ |
num_workers > 0 |
load batches in subprocesses; needs a main guard (if __name__ == "__main__":) |
Train and eval mode
Section titled “Train and eval mode”model.train() |
model.eval() |
torch.no_grad() |
|
|---|---|---|---|
| dropout | active | off | unchanged |
| batch norm | batch statistics, updates running stats | running stats | unchanged |
| graph recorded | yes | yes | no |
| use for | training steps | validation, prediction | validation, prediction, weight updates |
Regularization and early stopping
Section titled “Regularization and early stopping”| Tool | Code | Effect |
|---|---|---|
| dropout | nn.Dropout(0.3) after activations |
zeroes 30% of values in training, scales the rest by 1/0.7 |
| weight decay | AdamW(..., weight_decay=0.05) |
shrinks each weight by (1 - lr·λ) per step |
| early stopping | patience on the validation loss | stops when overfitting starts; restore the best weights |
| smaller network | fewer or narrower layers | fewer parameters to memorize with |
class EarlyStopping: def __init__(self, patience: int = 5) -> None: self.patience, self.best, self.bad, self.state = patience, float("inf"), 0, None
def step(self, val_loss: float, model: nn.Module) -> bool: if val_loss < self.best: self.best, self.bad = val_loss, 0 self.state = copy.deepcopy(model.state_dict()) # copy, not a reference else: self.bad += 1 return self.bad >= self.patience
stopper = EarlyStopping(patience=2)for epoch, val in enumerate([0.9, 0.8, 0.82, 0.81, 0.7], start=1): if stopper.step(val, model): print(f"stop after epoch {epoch}; best loss {stopper.best}") breakstop after epoch 4; best loss 0.8CNN shapes
Section titled “CNN shapes”| Input | Layer | Output |
|---|---|---|
(n, 1, 8, 8) |
Conv2d(1, 16, 3, padding=1) |
(n, 16, 8, 8) |
(n, 16, 8, 8) |
MaxPool2d(2) |
(n, 16, 4, 4) |
(n, 16, 4, 4) |
flatten(start_dim=1) |
(n, 256) |
(n, 256) |
Linear(256, 10) |
(n, 10) logits |
(n, 1, 28, 28) |
Conv2d(1, 8, 3) (no padding) |
(n, 8, 26, 26) |
(n, 3, 32, 32) |
Conv2d(3, 16, 3, stride=2, padding=1) |
(n, 16, 16, 16) |
x = torch.zeros(4, 1, 8, 8) # NCHW: batch, channels, height, widthconv = nn.Conv2d(1, 16, kernel_size=3, padding=1)h = nn.MaxPool2d(2)(torch.relu(conv(x)))print(tuple(h.shape), tuple(h.flatten(start_dim=1).shape), conv.weight.numel())(4, 16, 4, 4) (4, 256) 144Saving and loading
Section titled “Saving and loading”from pathlib import Path
Path("output").mkdir(exist_ok=True)torch.save({"config": {"n_features": 22, "hidden": [32, 16]}, "state_dict": model.state_dict()}, "output/cheatsheet_mlp.pt")ckpt = torch.load("output/cheatsheet_mlp.pt", weights_only=True)restored = ChurnMLP(ckpt["config"]["n_features"], tuple(ckpt["config"]["hidden"]))print(restored.load_state_dict(ckpt["state_dict"]))restored.eval()with torch.no_grad(): print(torch.equal(restored(X_toy), model(X_toy)))<All keys matched successfully>True| Do | Avoid |
|---|---|
torch.save(model.state_dict(), path) |
torch.save(model, path) (pickles the class path) |
torch.load(path, weights_only=True) |
weights_only=False on files you did not create |
| save the hyperparameters in the checkpoint | guessing the architecture when you load |
| save optimizer state, epoch and RNG states to resume | resuming with a fresh optimizer and expecting the same run |
model.eval() after loading for prediction |
predicting in train mode |
write to output/ |
writing into data/ |
Gotchas
Section titled “Gotchas”- dtype mismatch: NumPy arrays are float64;
nn.Linearweights are float32. Error:mat1 and mat2 must have the same dtype. Convert once with.float(). torch.stddivides by n − 1. Usecorrection=0to match NumPy’s default andStandardScaler.from_numpyand.numpy()share memory. Changing one changes the other. Usetorch.tensor(arr)or.clone()for a copy.- Gradients accumulate. Forgetting
zero_grad()makes each step larger than the last. - No sigmoid before
BCEWithLogitsLoss, no softmax beforeCrossEntropyLoss. The losses apply them inside. - Shapes
(n, 1)against(n,). BCE raises aValueError; MSE broadcasts to(n, n)with a warning. Squeeze the output. CrossEntropyLosstargets: int64 class indices of shape(n,), or float class probabilities (such as one-hot rows) of shape(n, K). Float labels of shape(n,)raiseexpected target dtype to be Long or Byte.- Eval mode is not
no_grad. Use both for evaluation, and callmodel.train()again before training. state_dict()returns references. Store the best weights withcopy.deepcopy.- Build the optimizer after the model. An optimizer built for an old model updates the old parameters.
total += losskeeps every graph alive. Accumulateloss.item().- Image tensors need a channel dimension:
(n, 1, 8, 8), not(n, 8, 8).Conv2dreads a 3-D input as one unbatched(C, H, W)image, sonbecomes the channel count and the call fails. - Threads: several processes that each use all cores slow each other down. Call
torch.set_num_threads(1)in worker processes. torch.loaduses pickle. Always passweights_only=True, which blocks arbitrary code; still prefer trusted files and an up-to-date PyTorch.