PyTorch Cheatsheet
A complete PyTorch cheatsheet from beginner to advanced — tensors, autograd, nn.Module, training loops, data loading, optimizers, GPU, torch.compile, mixed precision, saving models, and production patterns.
PyTorch is a flexible, Pythonic deep learning framework with first-class GPU support and dynamic computation graphs. It is the foundation of most modern research and production deep learning work.
This cheatsheet covers beginner fundamentals through advanced training and optimization techniques.
# CPU onlypip install torch torchvision torchaudio
# CUDA (check https://pytorch.org for the exact command)pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
# Verifypython -c "import torch; print(torch.__version__); print(torch.cuda.is_available())"import torchimport numpy as np
# From datax = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
# Special tensorstorch.zeros(3, 4)torch.ones(2, 3)torch.randn(2, 3) # normal distributiontorch.rand(2, 3) # uniform [0, 1)torch.arange(0, 10, 2)torch.linspace(0, 1, 5)torch.eye(3)
# From NumPy (shares memory when possible)a = np.array([1, 2, 3])t = torch.from_numpy(a)a2 = t.numpy()x.shape # or x.size()x.dtypex.devicex.ndimx.requires_gradx.grad # after backwardx.view(2, -1) # must be contiguousx.reshape(2, -1) # more flexiblex.flatten()x.squeeze() # remove dims of size 1x.unsqueeze(0) # add dimensionx.permute(2, 0, 1) # reorder dimensionsx.transpose(0, 1)
# Indexing (NumPy-like)x[0, 1]x[:, 1:]x[x > 0]x + yx * y # element-wisex @ y # matrix multiplytorch.matmul(x, y)x.sum(dim=0)x.mean(dim=1, keepdim=True)x.max(dim=1)torch.cat([x, y], dim=0)torch.stack([x, y], dim=0)x.add_(1) # trailing underscore = in-placex.mul_(2)x.zero_()x = torch.tensor(2.0, requires_grad=True)y = x ** 2 + 3 * x + 1y.backward()print(x.grad) # dy/dx = 2x + 3 → 7
# Multiple backwards need retain_graph or create_graphy.backward(retain_graph=True)
# Disable gradient trackingwith torch.no_grad(): z = x * 2
# Orz = x.detach() * 2Key rules:
- Only leaf tensors with
requires_grad=Trueaccumulate gradients. - Call
optimizer.zero_grad()(ormodel.zero_grad()) before each backward. - Use
torch.no_grad()for inference to save memory and computation.
import torch.nn as nnimport torch.nn.functional as F
class Net(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 10) self.dropout = nn.Dropout(0.2)
def forward(self, x): x = x.view(-1, 784) x = F.relu(self.fc1(x)) x = self.dropout(x) x = self.fc2(x) return x
model = Net()print(model)nn.Linear(in_features, out_features)nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0)nn.ConvTranspose2d(...)nn.MaxPool2d(kernel_size)nn.BatchNorm1d / BatchNorm2d / BatchNorm3dnn.LayerNorm(normalized_shape)nn.Dropout(p=0.5)nn.Embedding(num_embeddings, embedding_dim)nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)nn.TransformerEncoderLayer(...)nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 1))nn.ModuleList([nn.Linear(10, 10) for _ in range(3)])nn.ModuleDict({"fc": nn.Linear(10, 10)})F.relu(x)F.gelu(x)F.silu(x) # SwishF.softmax(x, dim=-1)F.log_softmax(x, dim=-1)torch.sigmoid(x)torch.tanh(x)criterion = nn.CrossEntropyLoss() # classification (logits + class indices)criterion = nn.BCEWithLogitsLoss() # binarycriterion = nn.MSELoss() # regressioncriterion = nn.L1Loss()criterion = nn.SmoothL1Loss()criterion = nn.NLLLoss() # after log_softmaxcriterion = nn.KLDivLoss(reduction="batchmean")criterion = nn.CosineEmbeddingLoss()criterion = nn.TripletMarginLoss()import torch.optim as optim
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)optimizer = optim.RMSprop(model.parameters(), lr=1e-3)optimizer = optim.Adagrad(model.parameters(), lr=1e-2)
# Learning rate schedulersscheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", patience=5)scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-2, total_steps=1000)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = Net().to(device)criterion = nn.CrossEntropyLoss()optimizer = optim.AdamW(model.parameters(), lr=1e-3)
for epoch in range(num_epochs): model.train() running_loss = 0.0
for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()
running_loss += loss.item()
scheduler.step() print(f"Epoch {epoch}: loss = {running_loss / len(train_loader):.4f}")model.eval()correct = 0total = 0with torch.no_grad(): for inputs, labels in test_loader: inputs, labels = inputs.to(device), labels.to(device) outputs = model(inputs) _, predicted = outputs.max(1) total += labels.size(0) correct += predicted.eq(labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")from torch.utils.data import Dataset, DataLoader, random_split
class MyDataset(Dataset): def __init__(self, data, labels, transform=None): self.data = data self.labels = labels self.transform = transform
def __len__(self): return len(self.data)
def __getitem__(self, idx): x = self.data[idx] y = self.labels[idx] if self.transform: x = self.transform(x) return x, y
dataset = MyDataset(X, y)train_set, val_set = random_split(dataset, [0.8, 0.2])
train_loader = DataLoader( train_set, batch_size=64, shuffle=True, num_workers=4, pin_memory=True, # faster host-to-device transfer persistent_workers=True,)from torchvision import transforms
transform = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# Apple Silicon# device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
model = model.to(device)x = x.to(device)x = x.cuda() # shorthandx = x.cpu()
# Multi-GPU (simple)if torch.cuda.device_count() > 1: model = nn.DataParallel(model)# Save weights only (recommended)torch.save(model.state_dict(), "model.pt")
# Loadmodel = Net()model.load_state_dict(torch.load("model.pt", map_location=device))model.eval()
# Save full checkpoint (training resume)torch.save({ "epoch": epoch, "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict(), "loss": loss,}, "checkpoint.pt")
checkpoint = torch.load("checkpoint.pt")model.load_state_dict(checkpoint["model_state_dict"])optimizer.load_state_dict(checkpoint["optimizer_state_dict"])model = torch.compile(model) # default backendmodel = torch.compile(model, mode="reduce-overhead")model = torch.compile(model, mode="max-autotune")model = torch.compile(model, backend="inductor")
# Compile a function@torch.compiledef fused_op(x, y): return (x + y).relu()Often gives 20–40%+ speedups with almost no code changes.
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad()
with autocast(): outputs = model(inputs) loss = criterion(outputs, labels)
scaler.scale(loss).backward() scaler.step(optimizer) scaler.update()Saves memory and often speeds up training on modern GPUs.
# Gradient clippingtorch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)torch.nn.utils.clip_grad_value_(model.parameters(), clip_value=0.5)
# Freeze layersfor param in model.fc1.parameters(): param.requires_grad = False
# Check gradientsfor name, param in model.named_parameters(): if param.grad is not None: print(name, param.grad.norm())class MyFunction(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return input.clamp(min=0)
@staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input
# Usagey = MyFunction.apply(x)# Forward hookdef forward_hook(module, input, output): print("Forward:", output.shape)
handle = model.fc1.register_forward_hook(forward_hook)
# Backward hookdef backward_hook(module, grad_input, grad_output): print("Backward grad:", grad_output[0].norm())
handle = model.fc1.register_full_backward_hook(backward_hook)
handle.remove()# Reproducibilitytorch.manual_seed(42)torch.cuda.manual_seed_all(42)torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = False
# Model summary (rough)total_params = sum(p.numel() for p in model.parameters())trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)print(f"Total: {total_params:,} | Trainable: {trainable:,}")
# Memorytorch.cuda.empty_cache()print(torch.cuda.memory_allocated() / 1e9, "GB")print(torch.cuda.max_memory_allocated() / 1e9, "GB")import torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import DataLoader, TensorDataset
# Fake dataX = torch.randn(1000, 20)y = torch.randint(0, 2, (1000,))loader = DataLoader(TensorDataset(X, y), batch_size=32, shuffle=True)
model = nn.Sequential( nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 2),)criterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(10): for xb, yb in loader: optimizer.zero_grad() loss = criterion(model(xb), yb) loss.backward() optimizer.step() print(f"Epoch {epoch}: {loss.item():.4f}")- Always call
model.train()/model.eval()appropriately. - Use
torch.no_grad()(ortorch.inference_mode()) during evaluation. - Prefer
AdamW+ weight decay over plain Adam for most modern models. - Start with a reasonable learning rate (1e-3 or 3e-4) and use a scheduler.
- Use
pin_memory=Trueand appropriatenum_workersin DataLoader. - Enable
torch.compilefor production training/inference when possible. - Use mixed precision (AMP) on CUDA GPUs.
- Clip gradients when training RNNs or transformers.
- Save
state_dictrather than the whole model for portability. - Set seeds for reproducibility, but note that full determinism can hurt performance.
# Tensortorch.tensor(data, dtype=torch.float32, device="cuda")x.to(device) x.cuda() x.cpu()x.view / reshape / permute / unsqueeze / squeeze
# Autogradx.requires_grad = Truey.backward()optimizer.zero_grad()
# Modelmodel.to(device)model.train() / model.eval()output = model(input)
# Training stepoptimizer.zero_grad()loss.backward()optimizer.step()
# Save / Loadtorch.save(model.state_dict(), path)model.load_state_dict(torch.load(path, map_location=device))- Official docs: https://pytorch.org/docs/stable/index.html
- Tutorials: https://pytorch.org/tutorials/
- torch.nn: https://pytorch.org/docs/stable/nn.html
- torch.optim: https://pytorch.org/docs/stable/optim.html
- PyTorch Forums: https://discuss.pytorch.org
- Awesome PyTorch: https://github.com/bharathgs/Awesome-pytorch-list
This cheatsheet targets modern PyTorch 2.x. Always verify against the version you have installed (torch.__version__).
Frequently asked questions
What is a tensor in PyTorch?
A tensor is a multi-dimensional array (like a NumPy ndarray) that can live on CPU or GPU and supports automatic differentiation when requires_grad=True.
How does autograd work?
PyTorch records operations on tensors that require gradients. Calling .backward() on a scalar loss computes gradients for all leaf tensors, stored in .grad.
What is the difference between model.train() and model.eval()?
model.train() enables dropout and batch norm updates. model.eval() disables them for inference. Always wrap inference with torch.no_grad() as well.
How do I move a model to GPU?
Use device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') then model.to(device) and tensors .to(device).
What does torch.compile do?
torch.compile wraps a model or function and optimizes it via graph capture and compilation, often giving significant speedups with minimal code changes.