Skip to content

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.

Terminal window
# CPU only
pip 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
# Verify
python -c "import torch; print(torch.__version__); print(torch.cuda.is_available())"

import torch
import numpy as np
# From data
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
# Special tensors
torch.zeros(3, 4)
torch.ones(2, 3)
torch.randn(2, 3) # normal distribution
torch.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.dtype
x.device
x.ndim
x.requires_grad
x.grad # after backward

x.view(2, -1) # must be contiguous
x.reshape(2, -1) # more flexible
x.flatten()
x.squeeze() # remove dims of size 1
x.unsqueeze(0) # add dimension
x.permute(2, 0, 1) # reorder dimensions
x.transpose(0, 1)
# Indexing (NumPy-like)
x[0, 1]
x[:, 1:]
x[x > 0]

x + y
x * y # element-wise
x @ y # matrix multiply
torch.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-place
x.mul_(2)
x.zero_()

x = torch.tensor(2.0, requires_grad=True)
y = x ** 2 + 3 * x + 1
y.backward()
print(x.grad) # dy/dx = 2x + 3 → 7
# Multiple backwards need retain_graph or create_graph
y.backward(retain_graph=True)
# Disable gradient tracking
with torch.no_grad():
z = x * 2
# Or
z = x.detach() * 2

Key rules:

  • Only leaf tensors with requires_grad=True accumulate gradients.
  • Call optimizer.zero_grad() (or model.zero_grad()) before each backward.
  • Use torch.no_grad() for inference to save memory and computation.

import torch.nn as nn
import 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 / BatchNorm3d
nn.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) # Swish
F.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() # binary
criterion = nn.MSELoss() # regression
criterion = nn.L1Loss()
criterion = nn.SmoothL1Loss()
criterion = nn.NLLLoss() # after log_softmax
criterion = 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 schedulers
scheduler = 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 = 0
total = 0
with 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() # shorthand
x = 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")
# Load
model = 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 backend
model = torch.compile(model, mode="reduce-overhead")
model = torch.compile(model, mode="max-autotune")
model = torch.compile(model, backend="inductor")
# Compile a function
@torch.compile
def 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 clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
torch.nn.utils.clip_grad_value_(model.parameters(), clip_value=0.5)
# Freeze layers
for param in model.fc1.parameters():
param.requires_grad = False
# Check gradients
for 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
# Usage
y = MyFunction.apply(x)

# Forward hook
def forward_hook(module, input, output):
print("Forward:", output.shape)
handle = model.fc1.register_forward_hook(forward_hook)
# Backward hook
def 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()

# Reproducibility
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic = True
torch.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:,}")
# Memory
torch.cuda.empty_cache()
print(torch.cuda.memory_allocated() / 1e9, "GB")
print(torch.cuda.max_memory_allocated() / 1e9, "GB")

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Fake data
X = 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}")

  1. Always call model.train() / model.eval() appropriately.
  2. Use torch.no_grad() (or torch.inference_mode()) during evaluation.
  3. Prefer AdamW + weight decay over plain Adam for most modern models.
  4. Start with a reasonable learning rate (1e-3 or 3e-4) and use a scheduler.
  5. Use pin_memory=True and appropriate num_workers in DataLoader.
  6. Enable torch.compile for production training/inference when possible.
  7. Use mixed precision (AMP) on CUDA GPUs.
  8. Clip gradients when training RNNs or transformers.
  9. Save state_dict rather than the whole model for portability.
  10. Set seeds for reproducibility, but note that full determinism can hurt performance.

# Tensor
torch.tensor(data, dtype=torch.float32, device="cuda")
x.to(device) x.cuda() x.cpu()
x.view / reshape / permute / unsqueeze / squeeze
# Autograd
x.requires_grad = True
y.backward()
optimizer.zero_grad()
# Model
model.to(device)
model.train() / model.eval()
output = model(input)
# Training step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Save / Load
torch.save(model.state_dict(), path)
model.load_state_dict(torch.load(path, map_location=device))


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.

You're offline Check your connection.