A tensor is an n-dimensional array with optional GPU acceleration and autograd tracking.
import torch
x = torch.tensor([[1., 2.], [3., 4.]])
z = torch.zeros(2, 3) # also ones, rand, randn, arange, linspace
x.shape, x.dtype, x.device # inspect
y = x @ x.T # matmul (also torch.matmul)
x.view(4) # reshape without copy (needs contiguous)
x.reshape(4) # reshape, copies if needed
x.unsqueeze(0) # add dim -> (1, 2, 2)
x[:, 0] # slicing, same as NumPy
x.mean(dim=0, keepdim=True) # reductions take dim/keepdim
import numpy as np
t = torch.from_numpy(np.ones(3)) # shares memory with the array
a = t.numpy() # CPU tensors only
Trailing underscore means in-place: x.add_(1)
Autograd records operations on tensors with requires_grad=True and computes gradients with backward().
w = torch.randn(3, requires_grad=True)
loss = (w * 2).sum()
loss.backward() # populates w.grad
print(w.grad) # tensor([2., 2., 2.])
w.grad.zero_() # gradients ACCUMULATE, reset them
with torch.no_grad(): # no graph: use for eval / manual updates
w -= 0.1 * w.grad
x = w.detach() # cut from the graph (shares storage)
with torch.inference_mode(): # faster than no_grad for pure inference
pass
backward() frees the graph by default; retain_graph=True keeps it
device = ("cuda" if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available()
else "cpu")
model = model.to(device) # modules move in place
x = x.to(device) # tensors return a NEW tensor
x = x.to(torch.float16) # dtype conversion
x = x.to(device, dtype=torch.bfloat16)
torch.cuda.device_count()
torch.cuda.memory_allocated() / 1e9 # GB in use
torch.cuda.empty_cache() # release cached blocks
float32: default; safest
bfloat16: same range as fp32, lower precision; preferred for training on Ampere+
float16: needs loss scaling (GradScaler)
import torch.nn as nn
import torch.nn.functional as F
class MLP(nn.Module):
def __init__(self, d_in, d_hidden, n_classes):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_in, d_hidden),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(d_hidden, n_classes),
)
def forward(self, x):
return self.net(x) # return logits
model = MLP(784, 256, 10)
sum(p.numel() for p in model.parameters() if p.requires_grad)
Call model(x), not model.forward(x), so hooks run
nn.Linear: fully connected
nn.Conv2d: images; (N, C, H, W) layout
nn.LSTM / nn.GRU: recurrent sequence models
nn.TransformerEncoderLayer: self-attention block
nn.Embedding: token id to vector lookup
nn.LayerNorm / nn.BatchNorm1d: normalization
Loss functions:
nn.CrossEntropyLoss: multi-class; takes raw LOGITS and integer targets (no softmax first)
nn.BCEWithLogitsLoss: binary / multi-label; takes logits
nn.MSELoss / nn.L1Loss: regression
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
# SGD: torch.optim.SGD(params, lr=0.1, momentum=0.9, nesterov=True)
# Different LR per group
opt = torch.optim.AdamW([
{"params": model.backbone.parameters(), "lr": 1e-5},
{"params": model.head.parameters(), "lr": 1e-3},
])
# Freeze layers
for p in model.backbone.parameters():
p.requires_grad = False
AdamW (decoupled weight decay) is the usual default
from torch.utils.data import Dataset, DataLoader
class MyDS(Dataset):
def __init__(self, X, y):
self.X, self.y = X, y
def __len__(self):
return len(self.X)
def __getitem__(self, i):
return self.X[i], self.y[i]
loader = DataLoader(
MyDS(X, y),
batch_size=64,
shuffle=True,
num_workers=4, # parallel loading processes
pin_memory=True, # faster host-to-GPU copies
persistent_workers=True, # keep workers alive between epochs
drop_last=True,
)
Start with num_workers = number of CPU cores per GPU, then tune
Use a custom collate_fn for variable-length data such as text sequences.
from torch.nn.utils.rnn import pad_sequence
def collate(batch):
xs, ys = zip(*batch)
lens = torch.tensor([len(x) for x in xs])
xs = pad_sequence(xs, batch_first=True, padding_value=0)
return xs, torch.tensor(ys), lens
loader = DataLoader(ds, batch_size=32, collate_fn=collate)
# Imbalanced classes
from torch.utils.data import WeightedRandomSampler
sampler = WeightedRandomSampler(weights, num_samples=len(weights))
loader = DataLoader(ds, batch_size=32, sampler=sampler) # no shuffle=True
# Recommended: save the state_dict, not the whole model
torch.save(model.state_dict(), "model.pt")
model = MLP(784, 256, 10)
state = torch.load("model.pt", map_location="cpu", weights_only=True)
model.load_state_dict(state)
model.eval()
# Full training checkpoint (to resume)
torch.save({"epoch": epoch, "model": model.state_dict(),
"opt": opt.state_dict(), "sched": sched.state_dict()}, "ckpt.pt")
Use weights_only=True: unpickling untrusted files can run code
model.train()
for epoch in range(num_epochs):
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
opt.zero_grad(set_to_none=True) # 1. reset grads
logits = model(xb) # 2. forward
loss = loss_fn(logits, yb) # 3. loss
loss.backward() # 4. backward
opt.step() # 5. update
@torch.no_grad()
def evaluate(model, loader):
model.eval() # disables dropout, BN uses running stats
correct = total = 0
for xb, yb in loader:
pred = model(xb.to(device)).argmax(dim=1)
correct += (pred.cpu() == yb).sum().item()
total += len(yb)
return correct / total
Forgetting model.eval() is the most common silent bug
# bfloat16: no scaler needed (Ampere+ GPUs)
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
loss = loss_fn(model(xb), yb)
loss.backward()
opt.step()
# float16: use a GradScaler
scaler = torch.amp.GradScaler("cuda")
with torch.autocast(device_type="cuda", dtype=torch.float16):
loss = loss_fn(model(xb), yb)
scaler.scale(loss).backward()
scaler.unscale_(opt) # needed before clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt)
scaler.update()
Typically 1.5-3x faster with about half the activation memory
sched = torch.optim.lr_scheduler.OneCycleLR(
opt, max_lr=1e-3, total_steps=epochs * len(loader))
# Others: CosineAnnealingLR, StepLR, LinearLR, ReduceLROnPlateau
# Per-batch schedulers: call sched.step() after opt.step()
# Gradient clipping (stabilizes transformers / RNNs)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
# Gradient accumulation = larger effective batch
accum = 4
for i, (xb, yb) in enumerate(loader):
loss = loss_fn(model(xb.to(device)), yb.to(device)) / accum
loss.backward()
if (i + 1) % accum == 0:
opt.step(); opt.zero_grad(set_to_none=True)
# train.py -- launch: torchrun --nproc_per_node=4 train.py
import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
dist.init_process_group("nccl")
rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(rank)
model = DDP(MyModel().to(rank), device_ids=[rank])
sampler = DistributedSampler(ds)
loader = DataLoader(ds, batch_size=64, sampler=sampler)
for epoch in range(epochs):
sampler.set_epoch(epoch) # reshuffle differently each epoch
...
if rank == 0: # save once
torch.save(model.module.state_dict(), "model.pt")
dist.destroy_process_group()
DDP = one process per GPU, gradients all-reduced every step
FSDP shards parameters, gradients and optimizer state across GPUs, so models larger than one GPU can train. Use DDP when the model fits on one GPU.
from torch.distributed.fsdp import fully_shard # FSDP2 (PyTorch 2.6+)
for layer in model.layers:
fully_shard(layer)
fully_shard(model)
torch.compile:
model = torch.compile(model) # default
model = torch.compile(model, mode="max-autotune") # slower compile, faster run
# First iterations are slow (compilation); dynamic shapes can trigger recompiles
from torch.profiler import profile, ProfilerActivity
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
train_step()
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10))
Gotchas:
- Forgetting
model.eval()/torch.no_grad()at inference - Not calling
zero_grad(): gradients accumulate - Applying softmax before
CrossEntropyLoss(it expects logits) - Accumulating
lossinstead ofloss.item(): keeps the whole graph in memory - GPU ops are async: call
torch.cuda.synchronize()before timing - Set seeds:
torch.manual_seed(0); full determinism needstorch.use_deterministic_algorithms(True)