← back

under the hood of pytorch

pytorch, it is.

Three lines show up in almost every PyTorch training loop:

optimizer.zero_grad()
loss.backward()
optimizer.step()

But what actually happens when you call backward()? Where do gradients come from? Let's build it up from the bottom.

1. tensors and autograd

Everything starts with a tensor: a container for numbers. One number, a list, a table, or something with many dimensions.

import torch

a = torch.tensor(5.0)              # one number
b = torch.tensor([1.0, 2.0, 3.0])  # a list
c = torch.rand(2, 3)               # 2x3 table of random numbers

Learn to check three things: x.shape, x.dtype and x.device (CPU or GPU). Most PyTorch errors are shape mismatches, so check `.shape` first.

Now the important part. Tell PyTorch a tensor should learn:

x = torch.tensor(2.0)
w = torch.tensor(4.0, requires_grad=True)

y = x * w + 1
print(y)  # tensor(9., grad_fn=<AddBackward0>)

That grad_fn means PyTorch is recording how y was made. It builds a computation graph so it can later answer: if the result is wrong, how should `w` change? This system is called autograd.

2. the operations you'll use most

* multiplies matching positions. @ is matrix multiplication, combining rows with columns. Neural networks use @ constantly, because it's how inputs meet weights.

m1 = torch.rand(2, 3)
m2 = torch.rand(3, 2)
print((m1 @ m2).shape)  # torch.Size([2, 2])

The inner sizes must match (3 and 3). The result takes the outer sizes (2 and 2).

Reductions summarize: scores.mean(dim=0) averages down the columns, dim=1 across the rows. And scores.argmax(dim=1) gives the index of the biggest value in each row, a common way to pick a predicted class.

3. train a model by hand

Let's teach a model y = 2x + 1 without telling it the numbers.

torch.manual_seed(0)
x = torch.rand(100, 1)
y_true = 2 * x + 1 + 0.05 * torch.randn(100, 1)

w = torch.rand(1, 1, requires_grad=True)
b = torch.rand(1, requires_grad=True)
lr = 0.1

for epoch in range(101):
    y_hat = x @ w + b                         # 1. forward pass
    loss = ((y_hat - y_true) ** 2).mean()     # 2. loss (MSE)
    loss.backward()                           # 3. gradients

    with torch.no_grad():                     # 4. update
        w -= lr * w.grad
        b -= lr * b.grad

    w.grad.zero_()                            # 5. clear gradients
    b.grad.zero_()

Over time, w moves toward 2 and b toward 1. Two details matter:

4. the professional version, and LLMs

Tracking every weight by hand doesn't scale. nn.Module and layers like nn.Linear manage weights for you. Activations like ReLU and GELU let the network learn non-linear patterns. An optimizer handles the updates:

from torch import nn

model = nn.Linear(1, 1)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.MSELoss()

for epoch in range(100):
    loss = loss_fn(model(x), y_true)
    optimizer.zero_grad()   # clear old gradients
    loss.backward()         # calculate new ones
    optimizer.step()        # update parameters

There are the three lines.

An LLM uses the same pattern. Token IDs become vectors with nn.Embedding, pass through transformer blocks built from linear layers, GELU, attention and LayerNorm, and come out as scores for the next token. Only the scale changes, from two parameters to billions.

Make a prediction. Measure the error. Calculate gradients. Update. Repeat.