Seyed Masoud Hosseini · Overview · Study log · Weekly summaries · Ideas · Search · Transcript · RSS feed
NLP with Deep Learning · Lecture 22 of 23 · 47:00
PyTorch Tutorial (CS224N Review Session)
Study guide
What this lecture covers
This is a teaching-assistant review session that introduces PyTorch, the deep learning framework used for the course's later assignments, to students who already know NumPy. It builds up from raw tensor operations to a full training loop, so that afterward you can define and train a small neural network in PyTorch without needing to write your own backpropagation or optimizer code.
The session covers four building blocks in order: tensors (creation, shapes, reshaping, and indexing, deliberately parallel to NumPy), autograd (PyTorch's automatic differentiation system), neural network modules (torch.nn layers such as linear layers and activations), and optimization (the torch.optim package and the standard training loop). It closes with a worked example that strings all four pieces together to fit a small model.
Key ideas
- Tensors as multi-dimensional arrays: a PyTorch tensor is the framework's equivalent of a NumPy array, created with
torch.tensor()from a list of lists, with a configurable data type (dtype) and support for element-wise operations and NumPy-style broadcasting. - Shape-first debugging: printing a tensor's
.shapeat each step is described as the most reliable debugging tool, more trustworthy than PyTorch's error messages, since operations can silently reshape data internally. - Reduction operations collapse a dimension: calling
sum(),mean(), or similar functions with adimargument removes that dimension from the result; with nodimgiven, the operation runs over the whole tensor. - Indexing mirrors NumPy: slicing with
:, indexing with a list of positions, and combining indices across multiple dimensions all work the same way as in NumPy arrays. - Autograd: setting
requires_grad=Trueon a tensor makes PyTorch track operations on it; calling.backward()computes gradients via the chain rule and stores them in.grad. - Gradient accumulation: PyTorch adds new gradients to
.gradrather than overwriting them, which is why a training loop must calloptimizer.zero_grad()before each backward pass. nn.Modulebuilding blocks: layers likenn.Linear, activation functions, andnn.Sequentiallet you compose a network from existing components instead of writing matrix operations by hand; a custom network subclassesnn.Moduleand defines__init__andforward.- The training loop pattern: zero the gradient, run a forward pass, compute the loss, call
loss.backward(), then calloptimizer.step(), repeated once per epoch.
Walkthrough
Tensors as the building block of PyTorch (0:05)
The instructor frames the session around four topics: tensors, autograd, neural network modules, and optimization. Tensors are introduced as PyTorch's version of NumPy arrays, used to represent everything from a single image (as a width-by-height tensor) to a batch of images with channels (a four-dimensional tensor).
Creating and manipulating tensors (5:10)
The lecture covers torch.tensor() for creating tensors from Python lists, torch.zeros, torch.ones, and torch.arange for quickly instantiating tensors of a given shape or range, and notes that arithmetic operations are element-wise by default. It explains that PyTorch's broadcasting rules match NumPy's: dimensions are compatible if they are equal or if one of them is 1, and notes that variable-length data, such as sentences of different lengths, is typically handled by padding to a fixed shape rather than using ragged tensors.
Shapes, reshaping, and debugging (11:15)
The instructor emphasizes printing .shape as the primary debugging habit, then demonstrates reshape() for changing a tensor's dimensions (for example, turning a flat 15-element tensor into a 5-by-3 tensor) and distinguishes view(), which returns a view of the same underlying data, from reshape(). It also shows converting between NumPy arrays and PyTorch tensors, and demonstrates reduction operations like sum() and mean(), explaining that the dim argument specifies which dimension gets collapsed in the result.
Indexing tensors (20:21)
Working through a three-dimensional example tensor, the lecture shows how indexing a single position along one dimension collapses that dimension, how a : copies an entire dimension, how to slice ranges of rows, and how list indexing (indexing with a list of positions, such as [0, 2, 4]) selects multiple elements at once. It closes with .item() for extracting a Python scalar from a one-element tensor, which is needed because a loss value must be a scalar before computing gradients.
Autograd and gradient accumulation (26:27)
Autograd is presented as PyTorch's automatic differentiation system: tensors created with requires_grad=True have their operations tracked, and calling .backward() on a downstream value computes gradients via the chain rule, storing them in the tensor's .grad attribute. A live example with y = 3x^2 shows the gradient evaluating to 6x, then a second .backward() call on a related quantity shows the gradient value doubling, because PyTorch accumulates gradients rather than overwriting them, which is why a training loop must explicitly zero the gradient before each new backward pass.
Building neural network modules (34:38)
The lecture introduces torch.nn, starting with nn.Linear(input_dim, output_dim), which applies an affine transformation to the last dimension of its input and includes a bias term by default. It covers reading and matching tensor shapes when stacking layers, other common layers (convolutions, batch normalization, pooling), composing layers with nn.Sequential, and defining a custom network by subclassing nn.Module with an __init__ method (which defines the layers) and a forward method (which defines the computation).
Training loop and optimization (43:48)
The final section introduces torch.optim and walks through the standard PyTorch training loop: for each epoch, call optimizer.zero_grad(), run a forward pass to get predictions, compute a loss (using a built-in loss function such as cross-entropy), call loss.backward() to compute gradients, and call optimizer.step() to update parameters. Running this loop on a small example shows the training loss dropping over epochs as the model fits the data.
Before you watch
- Familiarity with NumPy arrays, shapes, and broadcasting (covered in this course's Python tutorial) is assumed throughout.
- A basic understanding of what a neural network's forward pass, loss, and gradient are will make the autograd and training-loop sections easier to follow.
Check your understanding
- Why does printing a tensor's shape at each step help more with debugging than relying on PyTorch's error messages?
- What is the difference between calling
.sum(dim=0)and.sum(dim=1)on a two-dimensional tensor, and what shape does each produce? - Why does PyTorch accumulate gradients in
.gradinstead of overwriting them, and what does this require you to do in a training loop? - What are the two methods you must define when creating a custom network by subclassing
nn.Module, and what does each one do? - Walk through the five steps of a standard PyTorch training loop, in order, and explain what each step accomplishes.
Vocabulary
- tensor (noun)
- A multi-dimensional array of numbers used to store data in PyTorch.
A batch of images can be stored as a four-dimensional tensor. - autograd (noun)
- PyTorch's system that automatically computes gradients for you.
Autograd tracks operations so gradients can be computed automatically. - reshape (verb)
- To change the dimensions of a tensor without changing its data.
You can reshape a flat tensor into a grid of rows and columns. - reduction (noun)
- An operation that combines many values into fewer, such as a sum or mean.
A reduction like sum collapses one dimension of the tensor. - backpropagation (noun)
- The process of computing gradients by working backward through a network.
Calling .backward() runs backpropagation automatically. - gradient accumulation (noun)
- Adding new gradient values on top of old ones instead of replacing them.
Gradient accumulation means you must clear gradients before each new step. - zero_grad (noun)
- A function call that resets stored gradients back to zero before a new update.
Calling zero_grad prevents gradients from stacking up incorrectly. - affine transformation (noun)
- A linear operation combined with an added bias term.
A linear layer applies an affine transformation to its input. - linear layer (noun)
- A neural network layer that applies a weighted sum and bias to its input.
nn.Linear creates a linear layer with learnable weights. - activation function (noun)
- A nonlinear function applied inside a network to let it learn complex patterns.
An activation function follows most linear layers in a network. - subclass (verb)
- To create a new class that inherits behavior from an existing class.
A custom network subclasses nn.Module to define its own layers. - forward pass (noun)
- Running the network's calculations from input to output.
The forward method defines how data flows through the network. - optimizer (noun)
- An algorithm that updates a model's parameters to reduce the loss.
The optimizer adjusts weights after each backward pass. - epoch (noun)
- One complete pass through the entire training dataset.
The training loss dropped over several epochs. - cross-entropy (noun)
- A common loss function used for classification tasks.
Cross-entropy measures how far predicted probabilities are from the true label. - scalar (noun)
- A single number, not a vector or matrix.
A loss value must be a scalar before calling backward. - broadcasting (noun)
- A rule that lets operations work on tensors of different but compatible shapes.
PyTorch's broadcasting rules match NumPy's exactly. - element-wise (adjective)
- Applied separately to each matching value in two tensors.
Arithmetic operations on tensors are element-wise by default. - dtype (noun)
- The data type stored inside a tensor, such as integer or float.
You can set a tensor's dtype when creating it. - instantiate (verb)
- To create a specific object or example from a general definition.
torch.zeros quickly instantiates a tensor of a given shape. - convolution (noun)
- A layer that slides a small filter across input data to detect patterns.
Convolutions are one common layer type besides linear layers. - pooling (noun)
- An operation that shrinks data by summarizing small regions, such as taking the maximum.
Pooling layers reduce the size of feature maps. - batch normalization (noun)
- A technique that rescales layer outputs to make training more stable.
Batch normalization is mentioned alongside convolutions and pooling as a common layer. - hardcode (verb)
- To fix a value directly in code instead of letting it be set flexibly.
Using standard loss functions avoids the need to hardcode the math yourself. - trustworthy (adjective)
- Reliable and safe to depend on.
Printing shapes is more trustworthy than reading PyTorch's error messages. - roughly (adverb)
- Approximately, not exactly.
Reshaping turns a flat tensor into roughly the shape you need. - downstream (adjective)
- Happening later in a process, after earlier steps.
Calling .backward() on a downstream value computes gradients for everything before it. - string together (phrasal verb)
- To connect several parts into one continuous sequence.
The final example strings all four building blocks together.
From the YouTube description
For more information about Stanford's Artificial Intelligence professional and graduate programs, visit: https://stanford.io/ai
To learn more about this course, visit: https://online.stanford.edu/courses/c...
To follow along with the course schedule and syllabus, visit: http://web.stanford.edu/class/cs224n/
Professor Christopher Manning
Thomas M. Siebel Professor in Machine Learning, Professor of Linguistics and of Computer Science
Director, Stanford Artificial Intelligence Laboratory (SAIL)
#naturallanguageprocessing #deeplearning
← Python Tutorial (CS224N Review Session) · Hugging Face Tutorial (CS224N Review Session) →
