Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

PyTorch: Tensors, Autograd, nn.Module, Optimizers, DataLoader

PyTorch is the most widely used framework for deep-learning research. Its core is small: tensors (n-dimensional arrays on CPU or GPU), autograd (reverse-mode automatic differentiation on a graph recorded while your code runs), nn.Module (a container that tracks parameters), optimizers (rules that update parameters from their .grad) and DataLoader (batching and shuffling). This topic explains each piece and the canonical training loop, and the classic bugs (forgetting zero_grad, forgetting model.eval(), wrong learning rate). Because PyTorch doesn't run in the browser, the exercises rebuild its core in NumPy: a Tensor with autograd, Module, Linear, Sequential, SGD with momentum and a DataLoader, then a study of training-loop pitfalls.

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.

Autograd: forward builds the graph, backward fills .grad
x = 1.500no gradw = 0.500∂L/∂· —b = 0∂L/∂· —y = 2.000no gradm = w·x = 0.750∂L/∂· —z = m + b = 0.750∂L/∂· —r = z − y = -1.250∂L/∂· —L = r² = 1.563∂L/∂· —
loss 1.563
w.grad None
b.grad None
Each operation in the forward pass records how to send gradients back (chain rule). backward() walks the graph in reverse order: ∂L/∂r = 2r, then the same value flows through the subtraction and addition, and multiplying by x gives ∂L/∂w. PyTorch adds into .grad rather than overwriting it (useful for gradient accumulation over micro-batches), which is why every training step starts with zero_grad().
Why engineers care

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. What does training repeatedly do to the parameters?
  2. 2. How does PyTorch know how each parameter affected the error?
  3. 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.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Default floating-point dtype of a new torch tensor?
  2. 2. Which call computes the gradients?
  3. 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() and torch.inference_mode() skip recording during evaluation, and t.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.

🐍 Exercise 1: a mini PyTorch in NumPy
Build a Tensor that records operations (+, −, ×, /, power, matmul, relu, tanh, sum, mean) and implements backward() in reverse topological order with gradient accumulation and unbroadcasting; then Module (parameter discovery), Linear, Tanh, ReLU, Sequential, SGD with momentum and a shuffling DataLoader. Check gradients against finite differences and train y = 3x − 2.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A tensor used twice in the forward pass receives in backward…
  2. 2. Gradient of a (1, n) bias broadcast over a batch of 32 rows?
  3. 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(): .grad becomes the running sum of all past gradients, an unbounded “momentum” that usually diverges. (Deliberate accumulation over several micro-batches before one step() 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: pred of shape (N, 1) minus y of 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.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Without zero_grad(), the gradient used at step k is…
  2. 2. pred has shape (64, 1) and y has shape (64,). (pred − y)² has shape…
  3. 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.

🐍 Exercise 2 (research): training-loop pitfalls
Write the forward and backward pass of a 1-H-1 tanh MLP with inverted dropout by hand, check it with finite differences, train it with mini-batch SGD with momentum, and measure test error for the correct loop, a loop that never zeroes gradients, a dropout model evaluated with and without eval mode, and three learning rates.

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

  1. A. Paszke et al. (2019). “PyTorch: An imperative style, high-performance deep learning library.” NeurIPS 32.
  2. A. G. Baydin, B. A. Pearlmutter, A. A. Radul, J. M. Siskind (2018). “Automatic differentiation in machine learning: a survey.” JMLR, 18(153).
  3. A. Griewank, A. Walther (2008). Evaluating Derivatives, 2nd ed. SIAM.
  4. N. Srivastava et al. (2014). “Dropout: a simple way to prevent neural networks from overfitting.” JMLR, 15.
  5. PyTorch documentation (pytorch.org/docs): Autograd mechanics, torch.nn, torch.optim, torch.utils.data.