Lesson 2.4foundation3 h 30 min

PyTorch I: tensors, autograd and the training loop

The five lines every deep-learning program is built from

PyTorch is the framework in which most research and most open-weights models are written. Its two ideas — tensors that live on a GPU, and autograd that computes gradients of any program you write — are what make the derivations of 1.4 Derivatives, gradients and the chain rule and 4.4 Backpropagation, fully derived executable. The training loop you learn here is the same loop, almost line for line, that trains a GPT in 7.8 Build GPT from scratch (nanoGPT walkthrough).

You'll be able to

  • Convert between NumPy arrays and tensors, move tensors between CPU and GPU, and choose dtypes
  • Explain what requires_grad, backward() and .grad do and why gradients must be zeroed
  • Write the canonical five-step training loop and implement linear and logistic regression with it
  • Use nn.Module, nn.Linear, loss functions and optimizers, and switch between train and eval modes
  • Save and load model weights with state_dict and diagnose the common shape errors

Key ideas

  1. Tensors are NumPy-like arrays that can live on a GPU and record operations for autograd; default float dtype is float32.
  2. requires_grad=True records a dynamic graph; loss.backward() applies the chain rule in reverse and accumulates into .grad — zero gradients before each step.
  3. The five-step loop: batch → forward → loss → zero_grad + backward → optimizer.step(); it is identical from linear regression to GPT.
Show 5 more key ideas
  1. nn.Module holds parameters (in init) and computation (forward); model.parameters() feeds the optimizer; train()/eval() toggle dropout and batch norm.
  2. Use BCEWithLogitsLoss / CrossEntropyLoss on raw logits with integer targets; they handle the sigmoid/softmax stably.
  3. A Linear(d_in, d_out) layer has d_in·d_out + d_out parameters; counting them is a habit you will keep through transformers.
  4. Wrap evaluation in torch.no_grad(), log with loss.item(), save/load state_dict() rather than whole models.
  5. Most errors are shape or device mismatches; fix shapes at the loss boundary and create tensors on the right device.

Suggested path through this lesson