P5 — Reading PyTorch Code + Your First Colab Notebook
About 80 min
Read this before L3.11 — Pretrained Models and Transfer Learning. L3.11–L3.14 notebooks have no TODO functions; you run cells and change only the requested values. Writing a new PyTorch class is not required yet. If you get every question below right, you can move to the next lesson. This is a non-numbered optional guide: its checks and Labs do not record course progress.
Quick Check
Goal
Read a Tensor, nn.Module skeleton, dtype and shape, five-line training step, and state_dict without having to implement them. Open Colab and run an existing notebook safely on CPU.
Tensor = values plus shape and dtype
import torch
x = torch.tensor([[1.0, 2.0, 3.0]], dtype=torch.float32)
print(x.shape) # torch.Size([1, 3])
print(x.dtype) # torch.float32
A Tensor resembles a NumPy array but participates in PyTorch model computation. Shape (1,3) means one example, three features. float32 is a common feature/weight dtype; torch.long is common for class-index targets. A device such as cpu or cuda says where storage/computation happens. CPU is sufficient for all P5 and L3.11–L3.14 notebook steps.
Read the nn.Module template, not advanced OOP
class Encoder(torch.nn.Module):
def __init__(self, hidden=32):
super().__init__()
self.net = torch.nn.Linear(64, hidden)
def forward(self, x):
return self.net(x)
class Encoder(nn.Module) says this is a reusable model definition. __init__ sets up its layers; super().__init__() initializes the PyTorch module's bookkeeping so layers and parameters can be registered. self.net names a layer owned by the model; forward(x) describes how an input flows through that layer. model(x) calls forward through the module's normal call path. This is a model-definition template, not an invitation to learn inheritance first. A Linear(64,32) maps shape (batch,64) to (batch,32).
Read five training-loop operations
optimizer.zero_grad()
predictions = model(features)
loss = loss_fn(predictions, targets)
loss.backward()
optimizer.step()
Trace in order: clear accumulated gradients → forward prediction → compare against targets → compute gradients by autograd → update trainable parameters. loss.backward() does not update weights on its own. In inference/inspection, model.eval() changes behavior of certain layers, and with torch.no_grad(): avoids building a gradient graph. model.state_dict() gives parameter and persistent-buffer tensors keyed by name; loading it requires compatible parameter shapes and preprocessing, not just matching filenames.