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.
Your first Colab notebook — step by step
- Use the Open notebook in Google Colab Lab launcher below to open the notebook directly. If the public materials are not yet synchronized, download the P5 notebook file and select File → Upload notebook in Google Colab. The L3.11 notebook also opens directly.
- Choose Connect to attach a runtime; keep the default CPU. There is no need to pay for a GPU.
- Use Runtime → Run all initially, or run cells sequentially using each cell's play control. Imports and model definitions must run before later cells referencing them.
- Inspect
features.shape,predictions.shape,loss, andstate_dictkeys. Change onlyhidden_width=4to6in the companion notebook. Then restore4. - Use Runtime → Restart session if state becomes confusing; run from the top again. A restart clears Python variables; it does not rewrite the notebook on disk.
Common errors: NameError means a definition cell was not run; ModuleNotFoundError means a dependency or runtime is absent; RuntimeError: size mismatch means tensor/weight shapes disagree; CUDA unavailable means keep tensors and model on CPU; stale training results often mean earlier cells were edited without rerunning all downstream cells. The L3.11 deliberately mismatched state_dict load is caught by a try/except and is not a failed notebook.
Loading lab…
The companion notebook download contains no unfinished code. Spend ~15 minutes running it and ~15 minutes tracing the first L3.11 model definitions and outputs.
Predict
Browser practice: read before editing
Use Python to identify the output shape of a given linear layer, pick weight keys from a sample state_dict, and put the five named training steps in order. These TODOs assess your ability to read a model; they do not ask you to write a new PyTorch model or to install torch in the browser. Three progressive hints and the full solution are provided.
Loading lab…
Just before Project p03 — optional writing appendix
The regular L3.11–L3.14 notebook activities are run-and-modify, not class-writing tasks. Just before p03 — Transfer Learning, spend 10–15 minutes writing a single small nn.Module in a copy of your Colab notebook: define __init__, call super().__init__(), store nn.Linear(3,2) as self.linear, and return self.linear(x) from forward. Check model(torch.zeros(4,3)).shape == (4,2).
Hint 1: create the layer in __init__. Hint 2: forward(self,x) returns the layer call. Complete solution:
class TinyHead(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(3, 2)
def forward(self, x):
return self.linear(x)
assert TinyHead()(torch.zeros(4, 3)).shape == (4, 2)
Quick Check
Key Takeaways
- A PyTorch class can be read as a definition template: layers in init, flow in forward.
- Shape/dtype and training-step order are more important than writing new torch code before p03.
- Colab CPU, top-to-bottom execution and restart-and-rerun are sufficient for L3 notebooks.