PyTorch Training Breakdown


PyTorch Training Breakdown

Anna
You know those three lines of code that train every neural network? Floss.backward, optimizer.step, and optimizer.zero. They seem so simple, but there's so much happening under the hood.

Michael
Totally. I used to think PyTorch was this huge beast, but it's really just a five-step recipe. Once you understand that, everything clicks.

Anna
Exactly. And that recipe starts with the tensor, the fundamental building block. It's like a NumPy array but with superpowers like automatic differentiation.

Michael
Right. Creating tensors is straightforward. You can make them directly from data with torch.tensor, or from a desired shape using torch.randn, or even mimic another tensor's shape with torch.randn_like.

Anna
And every tensor has three critical attributes: shape, dtype, and device. Shape is your number one debugging tool. Most errors come from shape mismatches.

Michael
Device tells you if it's on CPU or GPU, and dtype defaults to float32. That's not an accident—gradients need floats because you can't nudge an integer from 3 to 3.001.

Anna
The real magic starts with requires_grad=True. That switch tells Autograd to track every operation. It builds a computation graph, like a live recording of your math.

Michael
So when you do something like y = a + b and then z = x * y, PyTorch creates nodes with grad_fn attributes. For z, it's MulBackward0; for y, it's AddBackward0. And for the original a, it's None.

Anna
That graph is what loss.backward() uses to compute gradients. It walks backward through those breadcrumbs. It's elegant.

Michael
Now operations. The star does elementwise multiplication, matching positions. But the @ symbol does matrix multiplication, which powers neural networks. That's the one you use in linear layers.

Anna
And reduction operations like mean and sum let you collapse dimensions. The dim argument is key: dim=0 collapses rows, dim=1 collapses columns. That's a huge aha moment for many people.

Michael
Indexing works like NumPy, but torch.gather is the expert tool. It lets you pick specific elements from each row using a tensor of indices. Super optimized.

Anna
So we've got the noun (tensor), the nervous system (autograd), and the verbs (operations). Now let's build a model from scratch. The forward pass is y = x @ w + b.

Michael
We create fake data following y = 2x + 1 with noise. Then we initialize random w and b with requires_grad=True. The first guess is terrible, but that's fine.

Anna
Then we compute the loss, say mean squared error: loss = ((yhat - y)**2).mean(). That gives us a single score. Then we call loss.backward() to compute gradients.

Michael
The gradients tell us which direction to nudge w and b. A negative gradient means increase the parameter to decrease loss. So we do w -= lr * w.grad and b -= lr * b.grad.

Anna
And we must zero the gradients each iteration or they accumulate. That's the manual way. But for big models, that's messy. Enter nn.Module and torch.optim.

Michael
nn.Module organizes your layers. You define them in __init__ and connect them in forward. Then torch.optim, like Adam, automates the updates. The three-line mantra: optimizer.zero_grad(), loss.backward(), optimizer.step().

Anna
And that pattern scales. Look at the feed-forward network inside a transformer: it's just two nn.Linear layers with a Gelu activation in between. Same building blocks, just bigger.

Michael
Our toy model had 2 parameters; Llama 3 8B has 8 billion. But the process is identical. The forward pass, loss, backward, and step are the same. The magic is gone—it's just engineering.

Ask anything
We've read this whole study set, so questions about it get the best answers.