Skip to content
ml-recall

Topic notes

PyTorch

Practical PyTorch — tensor shapes, broadcasting and reductions, view vs reshape, autograd, nn.Module registration, losses, the training loop, DataLoader and state_dict, with the gotchas that bite.

4-min read AI-checked

Practise 90 questions Take a test

Key ideas

A training step, in order: model.train(), move x, y to the device, optimizer.zero_grad(), loss = loss_fn(model(x), y), loss.backward(), optimizer.step(). Evaluate with model.eval() inside torch.no_grad().

Formulas

Worked example

net = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Linear(32, 3)) on 1000 examples, batch size 64:

In code

import torch
from torch import nn
y_hat, y = torch.zeros(32, 1), torch.zeros(32)
print((y_hat - y).shape)                     # torch.Size([32, 32]): silent broadcast bug
t = torch.randn(2, 3, 4).transpose(1, 2)
print(t.is_contiguous(), t.reshape(2, 12).shape)   # False torch.Size([2, 12]); t.view(2, 12) raises
class ListNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = [nn.Linear(4, 4)]      # plain list: not registered
print(len(list(ListNet().parameters())), len(list(nn.ModuleList([nn.Linear(4, 4)]).parameters())))  # 0 2
shared = nn.Linear(8, 8)
print(sum(p.numel() for p in nn.Sequential(shared, nn.ReLU(), shared).parameters()))  # 72, counted once
x = torch.zeros(2); x.to(torch.float64); print(x.dtype)  # torch.float32: Tensor.to returned a copy

Common pitfalls

References

  1. PyTorch documentation: Broadcasting semantics — General semantics; In-place semantics
  2. PyTorch documentation: torch.Tensor.view — torch.Tensor.view (description and note on reshape)
  3. PyTorch documentation: Autograd mechanics — Saved tensors; Locally disabling gradient computation (Setting requires_grad; No-grad Mode; Evaluation Mode); Multithreaded Autograd (Graph retaining)
  4. PyTorch source (v2.14.1): torch/nn/modules/module.py — class Module docstring; add_module; to; state_dict; load_state_dict and _load_from_state_dict (size-mismatch check); parameters; eval
  5. PyTorch documentation: torch.nn.CrossEntropyLoss — Description; Parameters (ignore_index, reduction); Shape
  6. PyTorch documentation: torch.utils.data — torch.utils.data.DataLoader (batch_size, shuffle, drop_last)
  7. torchvision documentation: ToTensor — torchvision.transforms.ToTensor (class description)
  8. PyTorch documentation: torch.argmax — torch.argmax(input) (first signature)