Back to section lessons
18 min · medium · Lesson 6 of 8

PyTorch: tensors, autograd and optimizers

Train a linear model y = wx + b on the CPU and trace how a loss changes its parameters.

Lesson contents
  1. 1 Tensors and parameters
  2. 2 The computation graph
  3. 3 An optimizer step
  4. 4 Checking numerical stability
  5. 5 Task
  6. 6 Common mistake

Tensors and parameters

A tensor stores numbers and resembles an ndarray, but PyTorch can record operations on it to calculate gradients. This course uses the CPU and torch.float32:

import torch

x = torch.tensor([0.0, 1.0, 2.0], dtype=torch.float32, device="cpu")
y = torch.tensor([1.0, 3.0, 5.0], dtype=torch.float32, device="cpu")

These points lie on the line y = 2x + 1. We'll try to recover the weight w and bias b from the data. The weight controls the line's slope; the bias moves the whole line up or down. For example, with w=2, b=1 and x=3, the answer is 7.

The computation graph

A parameter with requires_grad=True participates in automatic differentiation, or autograd: PyTorch automatically calculates derivatives from the recorded operations. prediction stores the predictions, while loss contains the mean squared error from the previous lesson:

w = torch.tensor(0.0, dtype=torch.float32, requires_grad=True)
b = torch.tensor(0.0, dtype=torch.float32, requires_grad=True)

prediction = w * x + b
loss = ((prediction - y) ** 2).mean()
loss.backward()

print(w.grad, b.grad)

backward() traverses the graph backward and writes derivatives to .grad. A gradient shows how a small parameter change will affect the loss.

An optimizer step

An optimizer applies gradients to parameters. In SGD, each parameter decreases by its gradient multiplied by the step size lr. A negative gradient makes the parameter increase. For this simple line, start with lr=0.1:

optimizer = torch.optim.SGD([w, b], lr=0.1)

optimizer.zero_grad()
prediction = w * x + b
loss = ((prediction - y) ** 2).mean()
loss.backward()
optimizer.step()

print(w.item(), b.item())  # примерно 0.8667 и 0.6

Gradients accumulate between backward() calls, so you need zero_grad() before each iteration. After backward(), the old graph is freed. Recompute the predictions and loss for the next step, as shown above.

The full loop repeats four actions: prediction, loss, backward, and an optimizer step. loss.item() turns a one-number tensor into a Python float for the training log.

Checking numerical stability

Loss and gradients must remain finite. NaN or Infinity indicate a data error, an excessive learning rate, or an invalid operation:

if not torch.isfinite(loss):
    raise ValueError("training loss is not finite")

In the short example, the loss should decrease and the parameters should change. The exact value after 200 steps depends on the settings, so the test uses a tolerance.

Task

Implement the following in exercises/lesson06.py:

def fit_line(x, y, steps=200):
    ...

The function returns (weight, bias, losses). The first two values must be Python float values. losses contains the loss value after each step.

Requirements:

Hints

Create two scalar tensors with requires_grad=True. Clear gradients before each iteration, then call backward() and step().

Don't convert the loss to float before backward(): an ordinary number is no longer connected to the graph. After backward(), save the current iteration's numeric value to a list with loss.item() or float(loss.detach()).

Check

python -m pytest -q tests/test_exercises.py --student exercises -k lesson06

The test checks the expected gradient on a small example, parameter changes and loss reduction.

Where to find the solution

The reference function is in solutions/lesson06.py. When comparing, trace the order zero_grad → forward → loss → backward → step.

python -m pytest -q tests/test_exercises.py --student solutions -k lesson06

Common mistake

If you forget zero_grad(), the new gradient is added to the previous one. Training may work at first and then become unstable, even when the loss formula is correct.

Done reading?

Mark the lesson as read to move your track progress forward.

Practice

Fix a local lab. The agent checks your work and gives hints if you get stuck.

Full access to all labs

$134 $67.00 for one year −50%

One payment, no auto-renewal · Terms

Buy for $67.00