Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.A calculator that remembers how it got the answer
A neural network is a long calculation with millions of adjustable knobs (parameters). To improve it, we need to know which way to turn each knob to make the error smaller: the gradient. PyTorch is a calculator that, while doing the calculation, writes down every step it took. Afterwards, it can walk those steps backwards and work out, for every knob at once, how much it affected the error. Then an optimizer nudges every knob a little in the helpful direction, and we repeat thousands of times.
The same tool trains image classifiers, learns robot control policies, fits neural surrogates of expensive simulations (aerodynamics, orbit propagation) and calibrates physical models by differentiating through them. Knowing what PyTorch does under the hood is what lets you debug a model that silently refuses to learn.
- 1. What does training repeatedly do to the parameters?
- 2. How does PyTorch know how each parameter affected the error?
- 3. The gradient tells you…
Level 1: Beginner
★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.Tensors
A torch.Tensor is an n-dimensional array, like a NumPy array, with three extra properties: a dtype (float32 by default, unlike NumPy’s float64), a device (cpu, cuda, mps) and an optional requires_grad flag. Broadcasting and indexing follow NumPy rules (C1.5). torch.from_numpy(a) shares memory with the array; t.numpy() goes back (CPU only); t.to("cuda") copies to a GPU.
The training loop
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
model = nn.Sequential(nn.Linear(1, 32), nn.Tanh(), nn.Linear(32, 1))
opt = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9)
loader = DataLoader(TensorDataset(X, y), batch_size=32, shuffle=True)
for epoch in range(150):
model.train() # dropout/batch-norm in training mode
for xb, yb in loader:
opt.zero_grad() # clear .grad from the previous step
loss = nn.functional.mse_loss(model(xb), yb)
loss.backward() # fill p.grad for every parameter p
opt.step() # update parameters from p.grad
model.eval() # inference mode for validation
with torch.no_grad(): # don't record a graph
val = nn.functional.mse_loss(model(Xv), yv)Five lines inside the loop do all the work: zero_grad, forward, loss, backward, step.
- 1. Default floating-point dtype of a new torch tensor?
- 2. Which call computes the gradients?
- 3. Which call changes the parameters?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.Autograd: a graph recorded at run time
Every operation on a tensor that requires gradients creates a node remembering its inputs and its backward function (the local derivative, applied to the incoming gradient: a vector-Jacobian product). The graph is built while your Python runs (“define-by-run”), so loops and if-statements just work. loss.backward() visits the nodes in reverse topological order and applies the chain rule; gradients reaching a node through several paths are summed. Only leaf tensors with requires_grad=True (the parameters) keep their .grad, and they accumulate: a second backward() adds to the first. After backward the graph is freed.
Two details matter in practice:
- Broadcasting in backward: if a bias of shape
(1, n)was broadcast over a batch, its gradient must be summed back over the batch axis (“unbroadcast”). - No graph when not needed:
torch.no_grad()andtorch.inference_mode()skip recording during evaluation, andt.detach()cuts a tensor out of the graph.
nn.Module, optimizers, DataLoader
nn.Module registers nn.Parameter attributes and sub-modules automatically, so model.parameters() finds everything. model.train() and model.eval() switch layers such as dropout and batch normalization. state_dict() gives the named tensors to save. An optimizer keeps per-parameter state (momentum buffers, Adam moments) and applies its rule in step(). A Dataset returns single samples; a DataLoader shuffles indices each epoch, collates samples into batches and can load in parallel worker processes.
- 1. A tensor used twice in the forward pass receives in backward…
- 2. Gradient of a (1, n) bias broadcast over a batch of 32 rows?
- 3. What does torch.no_grad() do?
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Classic training-loop bugs
- Forgetting
zero_grad():.gradbecomes the running sum of all past gradients, an unbounded “momentum” that usually diverges. (Deliberate accumulation over several micro-batches before onestep()is a legitimate trick for large effective batch sizes; divide the loss by the number of micro-batches.) - Forgetting
model.eval(): dropout keeps dropping units at test time and batch-norm keeps using batch statistics, so predictions are noisy and worse. - Learning rate too high: loss explodes to
nan; too low: training crawls. The stable range depends on the curvature of the loss (A6.1.3). - Silent shape broadcasting:
predof shape(N, 1)minusyof shape(N,)broadcasts to(N, N)and the loss is meaningless but finite. - Data on the wrong device or dtype, and
.item()or.cpu()inside the loop forcing GPU synchronization.
Debugging a model that won’t learn
Overfit a single small batch first (the loss should go to near zero), check gradient norms per layer, compare autograd with finite differences on a tiny input (torch.autograd.gradcheck, in float64), and log the learning rate and loss every step.
- 1. Without zero_grad(), the gradient used at step k is…
- 2. pred has shape (64, 1) and y has shape (64,). (pred − y)² has shape…
- 3. A good first sanity check for a new model is…
Level 4: Expert
★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.The mini framework, measured
Exercise 1. The NumPy Tensor’s gradients for mean(2·tanh(AB) + (AB)²) match central finite differences to about 1e-7, a broadcast bias of shape (1, 3) over 5 rows receives gradient 5, two backward() calls on x·x at x = 2 accumulate 4 + 4 = 8, and SGD with momentum recovers y = 2.993x − 2.006 from noisy samples of 3x − 2.
Exercise 2: training-loop pitfalls. A 1-32-1 tanh network fits sin(2x) from 256 noisy points with mini-batch SGD (batch 32, momentum 0.9, 150 epochs). The hand-written backward agrees with finite differences to 6e-11. Results (test MSE on a clean grid):
| Variant | Test MSE |
|---|---|
| correct loop (lr 0.05) | 0.00079 |
| lr 0.01 | 0.00114 |
| lr 0.2 | diverges |
no zero_grad() (momentum 0 or 0.9) |
diverges |
dropout 0.1, eval() at test |
0.027 |
dropout 0.1, forgot eval() |
0.070 |
Two lessons beyond the bugs: dropout does not help a small network on a smooth, low-noise problem (it costs about 35× in test error here), and the usable learning-rate window spans less than a factor of 4 above the best value.
PyTorch in AI, robotics and aerospace
- Learned dynamics and surrogates: neural networks replacing slow CFD or orbit-propagation calls inside optimization loops.
- Differentiable simulation: gradients through a physics model to fit parameters or optimize trajectories.
- Robot learning: policy networks trained with reinforcement or imitation learning, exported to embedded targets (C3.7).
- Onboard inference: small networks for terrain-relative navigation or anomaly detection, trained in PyTorch and deployed through ONNX or TorchScript.
References
- A. Paszke et al. (2019). “PyTorch: An imperative style, high-performance deep learning library.” NeurIPS 32.
- A. G. Baydin, B. A. Pearlmutter, A. A. Radul, J. M. Siskind (2018). “Automatic differentiation in machine learning: a survey.” JMLR, 18(153).
- A. Griewank, A. Walther (2008). Evaluating Derivatives, 2nd ed. SIAM.
- N. Srivastava et al. (2014). “Dropout: a simple way to prevent neural networks from overfitting.” JMLR, 15.
- PyTorch documentation (pytorch.org/docs): Autograd mechanics, torch.nn, torch.optim, torch.utils.data.