Core Concepts
- Tensors: Multi-dimensional arrays on CPU/GPU with autograd tracking
- Autograd: Automatic differentiation via
requires_gradandbackward() - nn.Module: Base class for neural network layers with
forward()method - Optimizers:
torch.optim.SGD,Adam,AdamWwithzero_grad()/step()loop - DataLoader: Batched, shuffled, parallel data loading with
Datasetsubclass - Distributed Training:
DistributedDataParallelfor multi-GPU with NCCL backend
Common Patterns
nn.Sequential(nn.Linear(d_in, d_hid), nn.ReLU(), nn.Linear(d_hid, d_out))for simple nets- Training loop:
for x, y in dataloader: pred = model(x); loss = loss_fn(pred, y); loss.backward(); optimizer.step(); optimizer.zero_grad() torch.utils.data.Datasetwith__len__and__getitem__for custom data- Transfer learning: freeze
requires_grad=Falseon backbone, train new head torch.compile(model)for graph optimization withmode="reduce-overhead"model.to("cuda")andx.to("cuda")for GPU execution
Best Practices
- Use
with torch.no_grad():for inference to disable gradient computation - Set
torch.manual_seed(42)andtorch.cuda.manual_seed_all(42)for reproducibility - Profile with
torch.profilerbefore optimizing GPU utilization - Use
pin_memory=Truein DataLoader for faster CPU-to-GPU transfer - Enable
grad_scalerfor mixed precision training withtorch.cuda.amp