// REF. 16 / DEEP LEARNING

PyTorch cheat sheet

The working surface of PyTorch, current to 2.15 (stable, October 2026): tensors and shapes, autograd, the nn building blocks, the training loop, optimizers and schedulers, DataLoader, mixed precision, torch.compile, and checkpoints. Every signature checked against the stable docs.

Two habits: reach for reshape when you are not sure a view is legal, and save state_dict() rather than the module. torch.load defaults to weights_only=True now, so the old pickled-module checkpoints will complain.

↓ Download the printable PDF free · letter size · no email needed

Tensors

torch.tensor([1., 2.])
from data; infers dtype (float32)
torch.zeros(2, 3)
also ones, randn, arange, linspace
x.view(-1, 8)
no copy; -1 is inferred; needs contiguous
x.reshape(...)
view if it can, copy if it must
x.permute(2, 0, 1)
reorder dims; returns a view
x.unsqueeze(0)
add a dim; squeeze drops size-1 dims
x.to(device)
also .to(dtype); non_blocking=True
torch.accelerator
is_available(), current_accelerator()

Autograd

requires_grad=True
track ops on this leaf tensor
loss.backward()
accumulates into .grad; zero first
torch.no_grad()
context: no graph; eval and updates
torch.inference_mode()
stricter no_grad, less overhead
x.detach()
same data, cut from the graph
x.item()
one-element tensor to python number

NN

class Net(nn.Module)
define forward(); call net(x), not it
nn.Linear(in, out)
input (*, in) to (*, out)
nn.Conv2d(cin, cout, k)
input (N, C, H, W); stride=1, padding=0
nn.Sequential(...)
chain layers; ModuleList for loops
nn.CrossEntropyLoss()
raw logits (N, C); int64 targets
nn.BCEWithLogitsLoss()
binary; logits in, no sigmoid needed
nn.MultiheadAttention
batch_first=True for (N, L, E)

Train loop

model.train()
dropout, batchnorm on; eval() off
optimizer.zero_grad()
set_to_none=True by default
loss = loss_fn(out, y)
then loss.backward()
optimizer.step()
apply the update
scheduler.step()
after optimizer.step(); epoch or batch
nn.utils.clip_grad_norm_
(params, max_norm) before step()

Optim

optim.SGD(params, lr=)
momentum=0.9 for the classic
optim.AdamW(params)
lr=1e-3, weight_decay=0.01 defaults
StepLR
(opt, step_size, gamma); decay per epoch
CosineAnnealingLR
(opt, T_max, eta_min=0); cosine decay
OneCycleLR
(opt, max_lr, total_steps); step per batch
ReduceLROnPlateau
step(val_loss); cut lr when it stalls

Data

class DS(Dataset)
define __len__ and __getitem__
DataLoader(ds, ...)
batch_size, shuffle, num_workers
pin_memory=True
faster host-to-gpu copies
drop_last=True
skip the ragged final batch
random_split(ds, lens)
fractions ok; pass generator for seed
TensorDataset(x, y)
wrap tensors sharing dim 0

AMP & compile

torch.autocast("cuda")
fp16 on cuda, bf16 on cpu by default
torch.amp.GradScaler()
the torch.cuda.amp one is deprecated
scaler.scale(loss)
.backward() on the scaled loss
scaler.unscale_(opt)
before clipping; once per step
scaler.step(opt)
skips on inf/nan; then scaler.update()
torch.compile(model)
mode=reduce-overhead or max-autotune

Save & load

torch.save(sd, path)
save model.state_dict(), not the module
torch.load(path)
weights_only=True is the default
map_location="cpu"
load gpu weights on a cpu box
m.load_state_dict(sd)
strict=True; same architecture

Here be dragons

x.view() on a slice
RuntimeError; .contiguous() first
forgot zero_grad()
grads accumulate; loss goes weird
model.eval() missing
dropout on in prod; nondeterminism
x.T on a 3-d tensor
deprecated; use permute
PyTorch Field Manual Desk Mat

// KEEP IT UNDER YOUR KEYBOARD

PyTorch Field Manual Desk Mat

from $34 · printed to order in the USA

See the desk mat