PyTorch tensors, modules and autograd
What it is
A PyTorch tensor carries values together with shape, dtype, device, and optionally autograd history. nn.Module registers parameters and submodules so model.parameters(), device transfers, optimisation, and checkpointing can find them; forward describes how an input tensor becomes an output tensor. Autograd records differentiable operations executed on tensors that require gradients, while Dataset and DataLoader define how individual samples are decoded, shuffled, collated, and batched. The standard training loop is deliberately explicit, which makes state and failure boundaries inspectable.
Why it matters
Most production training mistakes are state or device mistakes: an unregistered layer is not optimised, a tensor on CPU cannot combine with GPU weights, and a saved state_dict is not the same thing as arbitrary Python state. Treat shape, dtype, and device as part of every function's contract; printing only tensor values leaves out the information that usually identifies the error.
In the real world: The tools most research and production teams use to build models.
Visual example
Deep learningA DataLoader provides batches; Module and optimizer own the learnable state.
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self, d_in, d_hidden, n_classes):
super().__init__()
self.body = nn.Sequential(nn.Linear(d_in, d_hidden), nn.ReLU())
self.head = nn.Linear(d_hidden, n_classes)
def forward(self, x):
return self.head(self.body(x))
model = Net(64, 128, 10)
sum(p.numel() for p in model.parameters()) # every registered weightCreating nn.Linear inside forward. It creates fresh, unregistered random weights every call, so the optimiser never repeatedly updates the same parameters.