Skip to content

MLDay 31 of 50Deep Learning

PyTorch Basics

Tensors and Autograd

6 min read

On Day 30 you worked out two gradients by hand, one local slope at a time. A real network has millions of weights, and nobody writes their backward pass by hand. PyTorch watches your forward computation and works out every gradient for you.

The idea

A tensor is PyTorch's array: a grid of numbers, like a NumPy array. Each tensor has a dtype, the type of number it holds (float32 unless you ask for another), and a device, where it lives: cpu here, or a GPU (graphics card) when one is fitted.

Autograd is PyTorch's gradient engine. It works in three moves:

  1. Mark the tensors you want gradients for with requires_grad=True. PyTorch then records every operation that uses them.
  2. Compute the loss with ordinary maths: +, *, ** and @ (matrix multiply). This is the forward pass.
  3. Call loss.backward(). PyTorch runs backpropagation through the recorded steps, as in D30. Each marked tensor's gradient lands in its .grad.

One surprise: .backward() adds to .grad instead of replacing it. So a training loop clears every .grad after each step, or the old gradients pile up.

A tiny example

Take y=x2y = x^2 at x=3x = 3. The slope of x2x^2 is 2x2x, so the gradient is 2×3=62 \times 3 = 6. Here's what x.grad holds after each call:

Call x.grad Why
y.backward() 6 the slope at x=3x = 3
y.backward() again, on a fresh yy 12 6 + 6: the new gradient is added to the old one
x.grad.zero_() 0 cleared
y.backward() once more 6 right again

The formula

Autograd knows the slope of every basic operation, such as this one for squaring:

y=x2⇒dydx=2xy = x^2 \Rightarrow \frac{dy}{dx} = 2x
Symbol Meaning
xx a tensor marked with requires_grad=True
yy a value computed from xx
dydx\frac{dy}{dx} how fast yy grows when xx grows a little; after y.backward(), it sits in x.grad

Worked: at x=3x = 3, dydx=2×3=6\frac{dy}{dx} = 2 \times 3 = 6, so x.grad is 6. For a longer chain, autograd multiplies these slopes, just as you did on Day 30.

Try it

The gradients autograd will compute

One example: x = 2, y = 6. Change a weight and watch every number update, or take steps downhill.

forward z = w1·x1
h = ReLU(z)1
ŷ = w2·h1
loss (ŷ − y)²25
∂L/∂ŷ = 2(ŷ − y)-10
∂ŷ/∂h = w21
∂h/∂z (ReLU slope)1
∂z/∂w1 = x2

∂L/∂w1 = (-10)·(1)·(1)·(2) = -20

∂L/∂w2 = (-10)·(h = 1) = -10

Each step: w ← w − η·gradient

The network predicts 1 for a target of 6, so the loss is 25. Read the two gradient lines: −20 for w1w_1 and −10 for w2w_2. Then click Take a step three times and watch the loss fall to about 0.59. Every slope on screen is a step .backward() does for you; the code below gets the same −20 and −10 from one call.

In code

The first script checks the table above, then runs the playground's network through autograd:

# script_id: day_031_pytorch_tensors_autograd/autograd
import torch

x = torch.tensor(3.0, requires_grad=True)     # mark x: record what is done with it
(x ** 2).backward()
print("x.grad:", x.grad.item())               # .item() turns a one-number tensor into a float
(x ** 2).backward()
print("again, without clearing:", x.grad.item())
x.grad.zero_()
print("after zero_():", x.grad.item())

w1 = torch.tensor(0.5, requires_grad=True)    # the playground: x = 2, y = 6
w2 = torch.tensor(1.0, requires_grad=True)
loss = (w2 * torch.relu(w1 * 2.0) - 6.0) ** 2
loss.backward()
print(f"loss {loss.item():.0f}, dL/dw1 {w1.grad.item():.0f}, dL/dw2 {w2.grad.item():.0f}")
x.grad: 6.0
again, without clearing: 12.0
after zero_(): 0.0
loss 25, dL/dw1 -20, dL/dw2 -10

Now Day 9's gradient descent on the bike-share data: rentals from temperature, humidity, wind and hour, standardized, at η=0.1\eta = 0.1 for 17 steps (D09). First the NumPy walk, with the gradient written by hand:

# script_id: day_031_pytorch_tensors_autograd/bike
import os
from pathlib import Path

import numpy as np
import pandas as pd
import torch

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
X = np.column_stack([df["temp"] * 41, df["hum"] * 100, df["windspeed"] * 67, df["hr"]])  # °C, %, km/h, hour
y = df["cnt"].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)              # standardize each column

w, b = np.zeros(4), 0.0
for step in range(17):
    err = Z @ w + b - y
    w, b = w - 0.1 * 2 * Z.T @ err / len(y), b - 0.1 * 2 * err.mean()  # slope of the MSE, by hand
print("NumPy   w:", w.round(2), f" b: {b:.2f}  RMSE: {np.sqrt(np.mean((Z @ w + b - y) ** 2)):.2f}")
NumPy   w: [ 62.63 -39.44   0.57  51.54]  b: 185.20  RMSE: 149.08

The PyTorch loop writes only the loss. .backward() finds the slope:

# script_id: day_031_pytorch_tensors_autograd/bike
Zt, yt = torch.from_numpy(Z), torch.from_numpy(y)     # tensors; they keep NumPy's float64
print(Zt.dtype, Zt.device)
wt = torch.zeros(4, dtype=torch.float64, requires_grad=True)
bt = torch.zeros((), dtype=torch.float64, requires_grad=True)
for step in range(17):
    loss = ((Zt @ wt + bt - yt) ** 2).mean()          # the MSE, as plain maths
    loss.backward()                                   # fills wt.grad and bt.grad
    with torch.no_grad():                             # don't record the update itself
        wt -= 0.1 * wt.grad
        bt -= 0.1 * bt.grad
    wt.grad.zero_()                                   # .grad adds up, so clear it every step
    bt.grad.zero_()
rmse = ((Zt @ wt + bt - yt) ** 2).mean().sqrt().item()
print("PyTorch w:", np.round(wt.tolist(), 2), f" b: {bt.item():.2f}  RMSE: {rmse:.2f}")
print(f"largest weight difference: {np.abs(w - wt.tolist()).max():.1e}")
torch.float64 cpu
PyTorch w: [ 62.63 -39.44   0.57  51.54]  b: 185.20  RMSE: 149.08
largest weight difference: 7.1e-15

The weights differ by less than 10−1410^{-14}, and both walks reach Day 9's RMSE of 149.08. torch.no_grad() matters: without it, PyTorch refuses to change a tracked weight in place and raises a RuntimeError.

Quick check

Quick check

1. x = torch.tensor(5.0, requires_grad=True), then (x ** 2).backward(). What is x.grad?

2. A loop calls loss.backward() every step but never clears .grad. What happens?

3. Why is the weight update inside `with torch.no_grad():`?

Next

D32: The Training Loop hands the weights, the update and the clearing to PyTorch's own building blocks, so the same loop trains a real network.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 32 · 9 minThe Training Loop← Previous: Day 30 · Backpropagation by Hand
Not tapped yet