Home β€Ί Curriculum β€Ί Deep Learning with PyTorch
Updated for Python 3.12+ Β· November 2026

πŸ”₯ Deep Learning with PyTorch
in Python

Learn PyTorch basics: build autograd and gradient descent from scratch, train XOR in NumPy, then use tensors, nn.Module, DataLoader, optimizers and save/load.

Expert 8 lessonsβ‰ˆ 50 min read by Glenn Pansensoy

What this lesson is about

PyTorch is one of the most widely used libraries for deep learning. Research papers, hobby projects and production systems all use it to build neural networks that recognise images, translate text, predict numbers and generate content. Underneath the big models, though, PyTorch does only a few simple jobs: it stores numbers in tensors, it records the arithmetic you do with them, and it works out derivatives automatically so that a model can improve itself.

Because of that, I do not want you to learn PyTorch as a list of magic function names. My plan for this page is to build the important ideas yourself first, in plain Python and NumPy, where every number can be printed and checked. You will write a tiny reverse-mode automatic differentiation class, use it for gradient descent, train a two-layer network on the XOR problem by writing the backward pass by hand, and then see the same training loop structure that every PyTorch program follows.

The from-scratch blocks run in your browser with the Run button. PyTorch itself is a large package that cannot run in the browser, so the real PyTorch code on this page is marked as something to run on your own computer; I show it only after the idea behind each line has been built by hand, so you will recognise what loss.backward() and optimizer.step() are really doing. This is an expert-level topic, so you should be comfortable with functions, classes, lists and basic NumPy before you start.

What you will learn

  • βœ“What a tensor is and how it differs from a NumPy array or a Python list
  • βœ“How reverse-mode automatic differentiation works, by writing a small Value class
  • βœ“How gradient descent uses gradients to reduce a loss
  • βœ“Why a hidden layer lets a network learn XOR, and how backpropagation applies the chain rule
  • βœ“The standard training loop: forward, loss, zero gradients, backward, step
  • βœ“How to build models with nn.Module, nn.Linear and nn.Sequential
  • βœ“How Dataset, DataLoader, optimizers and devices fit together
  • βœ“How to evaluate with torch.no_grad() and save or load a state_dict

Why programmers should learn this

  • β˜…Deep learning is now part of many products, and PyTorch is a common way to read research code, fine-tune pretrained models and build custom ones.
  • β˜…Understanding autograd turns error messages about gradients, requires_grad and in-place operations from mysterious into logical.
  • β˜…The training loop pattern you learn here is the same for a toy line fit and for a large image model, so it transfers directly to new projects.
  • β˜…Tensors and broadcasting extend the NumPy skills you already have, so the jump from classic machine learning to neural networks is smaller than it looks.
  • β˜…Knowing what the framework does for you lets you debug training that does not converge, instead of only copying settings from tutorials.

What a tensor is and why PyTorch needs one

A tensor is a grid of numbers of one data type, with any number of dimensions: a single number is a 0-D tensor, a list of numbers is 1-D, a table is 2-D, a colour image is usually 3-D and a batch of images is 4-D. If that sounds exactly like a NumPy ndarray, that is because it nearly is, and the shape rules and broadcasting you may have learned in NumPy carry over almost unchanged.

PyTorch tensors add two things that matter for learning. First, a tensor can live on a GPU as well as on the CPU, which makes large matrix multiplication much faster. Second, a tensor can track the operations applied to it, so the library can later compute derivatives for you. Everything else in PyTorch, from layers to optimizers, is built on those two abilities.

Before touching the real library, let me show the shape vocabulary with NumPy, which you can run right here. Shape is the single most common source of bugs in deep learning code, so I want you to be fluent with it. Notice how a batch of four samples with three features each is a (4, 3) array, and how a weight matrix of shape (3, 2) turns it into a (4, 2) result.

Shapes: the language of every tensor
import numpy as np

batch = np.arange(12, dtype=float).reshape(4, 3)   # 4 samples, 3 features
weights = np.ones((3, 2)) * 0.5                    # maps 3 features to 2 outputs
bias = np.array([1.0, -1.0])

out = batch @ weights + bias                        # matrix multiply, then broadcast
print("batch shape  :", batch.shape)
print("weights shape:", weights.shape)
print("output shape :", out.shape)
print(out)

image = np.zeros((3, 32, 32))                       # channels, height, width
print("image dims   :", image.ndim, image.shape)
Expected output
batch shape  : (4, 3)
weights shape: (3, 2)
output shape : (4, 2)
[[ 2.5  0.5]
 [ 7.   5. ]
 [11.5  9.5]
 [16.  14. ]]
image dims   : 3 (3, 32, 32)

Line by line

  1. 1NumPy gives us the same shape rules that PyTorch tensors use.
  2. 3-5A batch of 4 rows with 3 features, a weight matrix and a bias vector: the pieces of one linear layer.
  3. 7The @ operator multiplies matrices; the bias of shape (2,) is broadcast across all 4 rows.
  4. 8-11Print the shapes so you can see (4, 3) @ (3, 2) gives (4, 2).
  5. 13-14A channels-first image tensor, the layout PyTorch expects for convolution layers.
The same ideas with real PyTorchrun on your computer
import torch

a = torch.tensor([[1.0, 2.0, 3.0],
                  [4.0, 5.0, 6.0]])
print(a.shape, a.dtype, a.device)

zeros = torch.zeros(2, 3)
rand = torch.rand(2, 3)               # uniform numbers in [0, 1)
steps = torch.arange(0, 10, 2)        # tensor([0, 2, 4, 6, 8])

print(a + zeros)                      # element-wise, same shape
print(a @ torch.ones(3, 1))           # matrix multiply -> shape (2, 1)
print(a.reshape(3, 2).shape)          # same data, new shape
print(a.mean(dim=0))                  # reduce along dimension 0

import numpy as np
n = a.numpy()                         # shares memory on the CPU
t = torch.from_numpy(np.eye(2))       # also shares memory

Line by line

  1. 1Import PyTorch; the package name is torch.
  2. 3-5torch.tensor builds a tensor from nested lists. Every tensor has a shape, a dtype and a device.
  3. 7-9Factory functions create tensors filled with zeros, random numbers or a range of values.
  4. 11-14Arithmetic, @ matrix multiplication, reshape and reductions work much as they do in NumPy, except reductions take dim instead of axis (both spellings are accepted).
  5. 16-18Converting to and from NumPy on the CPU shares memory, so changing one changes the other.

A detail that catches beginners: the default float dtype in PyTorch is 32-bit (float32), while NumPy defaults to 64-bit (float64). Neural networks rarely need the extra precision, and 32-bit numbers halve memory use and run faster on GPUs. If you pass a NumPy float64 array to a layer you will get a dtype mismatch error, so convert with .float() or dtype=torch.float32.

ℹ️

PyTorch is installed on your own machine with pip, using the command generated on the official PyTorch website for your operating system and GPU. Wheels differ by platform, so I do not hard-code one here.

Reverse-mode autodiff from scratch: a tiny Value class

Training a neural network means adjusting numbers so that a loss (a measure of how wrong the network is) gets smaller. To know which direction to nudge each number, you need the gradient: the derivative of the loss with respect to that number. A real network has millions of such numbers, so nobody computes derivatives by hand. PyTorch's autograd does it by recording each operation and then replaying the record backwards.

I find this the easiest thing to understand by building it. The class below wraps one number. Whenever you add or multiply two Value objects it creates a new Value that remembers its parents and carries a small function describing how a change in the output flows back to each parent. That function is the chain rule in code: the gradient arriving at a node is multiplied by the local derivative and passed on.

Calling backward() on the final result first sorts all nodes so that every node comes after its parents (a topological order), seeds the output gradient with 1, and then walks the list in reverse. Notice that gradients are added with +=, not assigned. If a value is used in two places, as a is in a*a + a, both paths contribute to its gradient. That one detail is the most common bug when people write this from memory.

A reverse-mode autodiff engine in 60 lines
import math

class Value:
    def __init__(self, data, parents=()):
        self.data = float(data)
        self.grad = 0.0
        self._parents = parents
        self._backward = lambda: None

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other))
        def _backward():
            self.grad += out.grad
            other.grad += out.grad
        out._backward = _backward
        return out

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other))
        def _backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward
        return out

    def __pow__(self, k):
        out = Value(self.data ** k, (self,))
        def _backward():
            self.grad += k * self.data ** (k - 1) * out.grad
        out._backward = _backward
        return out

    def tanh(self):
        t = math.tanh(self.data)
        out = Value(t, (self,))
        def _backward():
            self.grad += (1 - t * t) * out.grad
        out._backward = _backward
        return out

    def __neg__(self):
        return self * -1

    def __sub__(self, other):
        return self + (-other if isinstance(other, Value) else Value(-other))

    __radd__ = __add__
    __rmul__ = __mul__

    def backward(self):
        order, seen = [], set()
        def visit(v):
            if id(v) not in seen:
                seen.add(id(v))
                for p in v._parents:
                    visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0
        for v in reversed(order):
            v._backward()

    def __repr__(self):
        return f"Value(data={self.data:.4f}, grad={self.grad:.4f})"


x, w, b = Value(2.0), Value(-0.5), Value(0.3)
y = (x * w + b).tanh()
y.backward()
print(y)
print("dy/dx =", round(x.grad, 4))
print("dy/dw =", round(w.grad, 4))
print("dy/db =", round(b.grad, 4))

a = Value(3.0)
f = a * a + a              # a is used in two places
f.backward()
print("d(a*a + a)/da =", a.grad)   # 2a + 1 = 7
Expected output
Value(data=-0.6044, grad=1.0000)
dy/dx = -0.3174
dy/dw = 1.2695
dy/db = 0.6347
d(a*a + a)/da = 7.0

Line by line

  1. 1math.tanh is the activation function we will wrap.
  2. 4-8Each Value stores its number, its gradient (starting at zero), the nodes it came from, and a function that pushes gradient to those parents.
  3. 10-17Addition: the local derivative is 1 for both inputs, so the incoming gradient is passed on unchanged and accumulated with +=.
  4. 19-26Multiplication: each parent receives the *other* parent's value times the incoming gradient. That is the product rule.
  5. 28-33Power with a constant exponent: derivative k * x**(k-1), used later for squared error.
  6. 35-41tanh has derivative 1 - tanh(x)**2, which we compute from the stored output.
  7. 43-47Subtraction and negation are built from multiplication and addition, so they need no new backward code.
  8. 49-50Let 2 * v and 2 + v work too by reusing the same methods.
  9. 52-64backward builds a topological order with a depth-first walk, sets the final gradient to 1, then runs every node's backward function in reverse order.
  10. 66-67A readable printout.
  11. 70-76Build tanh(x*w + b) and read gradients. Each should match the calculus: for example dy/dx = w * (1 - y**2).
  12. 78-81Reusing a in two places accumulates both contributions: 2a + 1 = 7 at a = 3.

This is the same design idea as PyTorch's autograd: a graph of operations built during the forward pass, then a backward walk. Real PyTorch works on whole tensors instead of single floats, has hundreds of operations with hand-written derivatives, and frees the graph after each backward call by default, but the structure is the same. If this clicks, loss.backward() will never feel like magic again.

πŸ’‘

You can check any gradient numerically: compute f(x + 0.0001) minus f(x) and divide by 0.0001. If it disagrees with your backward code, the backward code is wrong. This 'gradient check' is the standard way to test hand-written derivatives.

Gradient descent: following the slope downhill

A gradient tells you how the loss changes if you nudge a parameter upward. To make the loss smaller, you move the parameter the opposite way. Gradient descent repeats that: compute the loss, compute gradients, subtract learning_rate * gradient from each parameter, and repeat. The learning rate is the step size, and it is the most important setting you will tune.

Let us start with a one-parameter problem you can check in your head. The loss (w - 3)**2 is smallest at w = 3, and its derivative is 2 * (w - 3). With a learning rate of 0.1, each step moves w closer to 3 by a fixed fraction of the remaining distance. Run the block and watch the numbers shrink toward the answer. Then change the learning rate to 1.1 and see what happens: the steps overshoot and the loss grows instead of shrinking.

Then we will use our Value class for a real fit: find the line y = w*x + b that best matches four points. The loss is the mean of squared errors. Each iteration resets the gradients to zero (because backward accumulates), runs the forward pass, calls backward, and updates w and b. The pattern 'zero, forward, backward, update' is exactly what you will write in PyTorch.

One parameter, by hand
w = 0.0
lr = 0.1
for step in range(8):
    loss = (w - 3) ** 2
    grad = 2 * (w - 3)
    w = w - lr * grad
    print(f"step {step}: w={w:.4f} loss={loss:.4f}")
Expected output
step 0: w=0.6000 loss=9.0000
step 1: w=1.0800 loss=5.7600
step 2: w=1.4640 loss=3.6864
step 3: w=1.7712 loss=2.3593
step 4: w=2.0170 loss=1.5099
step 5: w=2.2136 loss=0.9664
step 6: w=2.3709 loss=0.6185
step 7: w=2.4967 loss=0.3958

Line by line

  1. 1-2Start far from the answer and choose a learning rate.
  2. 3-5Each step computes the loss and its derivative by hand.
  3. 6The update rule: move against the gradient, scaled by the learning rate.
  4. 7Print progress. Try lr = 1.1 to see divergence.
Fitting a line with our own autodiff
import math

class Value:
    def __init__(self, data, parents=()):
        self.data = float(data); self.grad = 0.0
        self._parents = parents; self._backward = lambda: None
    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other))
        def _backward():
            self.grad += out.grad; other.grad += out.grad
        out._backward = _backward
        return out
    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other))
        def _backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward
        return out
    def __pow__(self, k):
        out = Value(self.data ** k, (self,))
        def _backward():
            self.grad += k * self.data ** (k - 1) * out.grad
        out._backward = _backward
        return out
    def __neg__(self): return self * -1
    def __sub__(self, other): return self + (-other if isinstance(other, Value) else Value(-other))
    def backward(self):
        order, seen = [], set()
        def visit(v):
            if id(v) not in seen:
                seen.add(id(v))
                for p in v._parents: visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0
        for v in reversed(order): v._backward()

points = [(0, 1), (1, 3), (2, 5), (3, 7)]      # exactly y = 2x + 1
w, b = Value(0.0), Value(0.0)

for step in range(61):
    w.grad = 0.0
    b.grad = 0.0                                # backward() accumulates, so reset first
    loss = Value(0.0)
    for x, y in points:
        loss = loss + ((w * x + b) - y) ** 2
    loss = loss * (1 / len(points))             # mean squared error
    loss.backward()
    w.data -= 0.05 * w.grad
    b.data -= 0.05 * b.grad
    if step % 20 == 0:
        print(f"step {step:2d}  w={w.data:.3f}  b={b.data:.3f}  loss={loss.data:.5f}")
Expected output
step  0  w=0.850  b=0.400  loss=21.00000
step 20  w=2.013  b=0.972  loss=0.00029
step 40  w=2.007  b=0.985  loss=0.00009
step 60  w=2.004  b=0.992  loss=0.00003

Line by line

  1. 1-37The same Value engine, condensed so this block runs on its own.
  2. 39Four data points that lie exactly on the line y = 2x + 1, so we know the answer we hope to find.
  3. 40The two parameters start at zero.
  4. 42-44Each iteration starts by clearing old gradients.
  5. 45-48Forward pass: add up the squared error of every point, then average.
  6. 49Backward pass fills w.grad and b.grad.
  7. 50-51Update: step against each gradient. We change .data directly so the update itself is not recorded in the graph.
  8. 52-53Print every 20 steps; w approaches 2 and b approaches 1.

Notice that I changed .data in the update rather than building new Value objects. PyTorch has the same rule, which is why parameter updates happen inside torch.no_grad(): you do not want the optimiser's own arithmetic to become part of the graph that gets differentiated.

⚠️

If the loss goes up, becomes nan or inf, the first thing to try is a smaller learning rate. Divergence from too large a step is the most common reason a first training run fails.

A hidden layer: training a network on XOR with NumPy

XOR is the classic test for why neural networks need hidden layers. The output should be 1 when exactly one of the two inputs is 1: inputs (0,1) and (1,0) give 1, while (0,0) and (1,1) give 0. No single straight line can separate those two groups, so a model that is just a linear function followed by a squash can never get all four right. One hidden layer with a non-linear activation, here tanh, can.

The network below has 2 inputs, 4 hidden units with tanh, and 1 output with a sigmoid. The forward pass is two matrix multiplications with non-linearities in between. The backward pass applies the chain rule layer by layer, which is exactly what autograd automates: the gradient at the output flows through the sigmoid, then into the output weights and the hidden activations, then through tanh into the first layer's weights.

Two practical points. The random starting weights come from a seeded generator so that the run is reproducible; a different seed can land on a different result, and some seeds get stuck on a plateau, which is a real phenomenon in small networks. Also, the printed outputs are rounded: a trained network gives numbers like 0.99, not exactly 1, and we turn them into class labels with a 0.5 threshold.

Two-layer network learns XOR
import numpy as np

rng = np.random.default_rng(42)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)

W1 = rng.normal(0, 1, (2, 4)); b1 = np.zeros((1, 4))
W2 = rng.normal(0, 1, (4, 1)); b2 = np.zeros((1, 1))
sigmoid = lambda z: 1 / (1 + np.exp(-z))
lr = 1.0

for epoch in range(5001):
    # forward pass
    h = np.tanh(X @ W1 + b1)
    p = sigmoid(h @ W2 + b2)
    loss = np.mean((p - y) ** 2)
    if epoch % 1000 == 0:
        print(f"epoch {epoch:4d}  loss={loss:.4f}")

    # backward pass (chain rule, layer by layer)
    dp = 2 * (p - y) / len(X) * p * (1 - p)     # gradient at the output pre-activation
    dW2 = h.T @ dp
    db2 = dp.sum(axis=0, keepdims=True)
    dh = (dp @ W2.T) * (1 - h ** 2)             # through tanh
    dW1 = X.T @ dh
    db1 = dh.sum(axis=0, keepdims=True)

    # update
    W1 -= lr * dW1; b1 -= lr * db1
    W2 -= lr * dW2; b2 -= lr * db2

print("outputs :", np.round(p, 2).ravel())
print("classes :", (p > 0.5).astype(int).ravel())
print("targets :", y.astype(int).ravel())
Expected output
epoch    0  loss=0.2874
epoch 1000  loss=0.0010
epoch 2000  loss=0.0004
epoch 3000  loss=0.0002
epoch 4000  loss=0.0002
epoch 5000  loss=0.0001
outputs : [0.01 0.99 0.99 0.01]
classes : [0 1 1 0]
targets : [0 1 1 0]

Line by line

  1. 3-5A seeded random generator and the four XOR examples with their targets.
  2. 7-8Layer 1 maps 2 inputs to 4 hidden units; layer 2 maps 4 hidden units to 1 output. Biases start at zero.
  3. 9-10Sigmoid squashes the output into 0..1 so it reads as a probability. The learning rate is the step size.
  4. 12-17Forward pass: linear, tanh, linear, sigmoid, then the mean squared error. We print the loss every 1000 epochs.
  5. 20Start of backprop: derivative of the loss times the sigmoid's slope p * (1 - p).
  6. 21-22Gradients for the output layer's weights and bias.
  7. 23Send the gradient back through W2, then multiply by the tanh slope 1 - h**2.
  8. 24-25Gradients for the first layer.
  9. 28-29Gradient descent on all four parameter arrays.
  10. 31-33Show rounded outputs, the thresholded class labels and the targets. They should match.

Compare this code to the autograd engine from earlier: every line in the backward pass is the same local rule, applied to matrices. Frameworks exist so that you never write those backward lines yourself, and so that the same code runs on a GPU. But once you have written them once, nn.Linear and loss.backward() stop being a black box.

ℹ️

I chose the seed and learning rate by trying them, which is honest practice for a demo but not something to hide. In real projects you track results across several seeds before trusing a number.

The training loop pattern, mirrored in plain Python

Almost every PyTorch training script has the same skeleton. For each epoch (one pass over the dataset), for each batch (a small group of samples), you run the model forward, compute the loss, clear old gradients, call backward, and let the optimiser update the parameters. Batches matter because a real dataset is too large to process at once, and because the small randomness between batches actually helps training.

The block below is a complete mini training run in plain Python so that each piece has a visible counterpart. A batches function plays the role of DataLoader: it shuffles indices with a seeded generator and yields groups. A two-parameter model plays the role of nn.Linear(1, 1). The gradient lines stand in for loss.backward(), and the update lines stand in for optimizer.step(). We also compute a separate validation loss without any updates, which is what model.eval() together with torch.no_grad() does in PyTorch.

Read the loop structure rather than the arithmetic. If you can name which line corresponds to which PyTorch call, you understand training. The order of the steps matters: if you forget to zero the gradients you silently train on the sum of old and new gradients, and if you update before computing the loss you update with stale information.

Epoch, batch, forward, backward, step
import random

random.seed(0)
xs = [i / 10 for i in range(40)]
data = [(x, 2 * x + 1 + random.uniform(-0.1, 0.1)) for x in xs]    # noisy line
train, val = data[:32], data[32:]

def batches(rows, size, rng):                 # plays the part of DataLoader
    idx = list(range(len(rows)))
    rng.shuffle(idx)
    for i in range(0, len(idx), size):
        yield [rows[j] for j in idx[i:i + size]]

w, b = 0.0, 0.0                               # plays the part of nn.Linear(1, 1)
lr = 0.05
rng = random.Random(1)

for epoch in range(1, 41):
    for batch in batches(train, 8, rng):
        gw = gb = 0.0                         # zero_grad()
        for x, y in batch:
            err = (w * x + b) - y             # forward
            gw += 2 * err * x / len(batch)    # backward (hand-written)
            gb += 2 * err / len(batch)
        w -= lr * gw                          # optimizer.step()
        b -= lr * gb
    if epoch % 10 == 0:
        val_loss = sum(((w * x + b) - y) ** 2 for x, y in val) / len(val)   # no updates here
        print(f"epoch {epoch:2d}  w={w:.2f}  b={b:.2f}  val_loss={val_loss:.4f}")
Expected output
epoch 10  w=2.00  b=1.03  val_loss=0.0035
epoch 20  w=2.01  b=1.02  val_loss=0.0042
epoch 30  w=2.01  b=1.01  val_loss=0.0038
epoch 40  w=2.01  b=1.01  val_loss=0.0046

Line by line

  1. 1-5Create a noisy straight line, y = 2x + 1 plus a little seeded noise, and split it into training and validation rows.
  2. 7-11A generator that shuffles row indices and yields batches of a given size: the job DataLoader(shuffle=True) does.
  3. 13-15Two parameters and a learning rate, standing in for a model and an optimiser.
  4. 17The outer loop is the epoch loop.
  5. 18The inner loop pulls one batch at a time.
  6. 19Reset batch gradients, the equivalent of optimizer.zero_grad().
  7. 20-23Forward pass and the hand-written gradients of mean squared error with respect to w and b.
  8. 24-25Parameter update, the equivalent of optimizer.step().
  9. 26-28Every ten epochs, evaluate on held-out data. Nothing is updated in this step.

Keep two kinds of loss in mind. The training loss tells you whether the model can fit the data it is allowed to learn from. The validation loss tells you whether it works on data it has not seen. If training loss keeps falling while validation loss rises, the model is memorising (overfitting), and you should stop earlier, add regularisation or get more data.

Real PyTorch: tensors with autograd

Now we can look at the real library with understanding. In PyTorch, you mark a tensor with requires_grad=True and every operation involving it is recorded in a graph. Calling .backward() on a scalar result fills the .grad attribute of every tracked leaf tensor, just as our Value.backward() did.

There are a few rules that mirror what you built. Gradients accumulate across calls, so you must clear them, either with tensor.grad.zero_() for a manual tensor or optimizer.zero_grad() for model parameters. To perform arithmetic without recording it, such as when you update weights by hand or when you evaluate a model, wrap it in torch.no_grad(). And .backward() needs a scalar; for a non-scalar output you must pass a gradient argument, which beginners rarely need.

The second example below is the line-fitting problem from earlier done with raw tensors and no nn module at all. It is worth reading carefully because it shows that a PyTorch model is just tensors plus a loop. Since it needs the real library, it is shown as code to run on your own computer.

requires_grad and backwardrun on your computer
import torch

x = torch.tensor(2.0)
w = torch.tensor(-0.5, requires_grad=True)
b = torch.tensor(0.3, requires_grad=True)

y = torch.tanh(x * w + b)
y.backward()                 # fills w.grad and b.grad
print(w.grad, b.grad)        # same maths as our Value class

w.grad.zero_()               # gradients accumulate, so clear before reuse

Line by line

  1. 1Import torch.
  2. 3-5x is just data, while w and b are marked so PyTorch tracks operations on them.
  3. 7-8Forward pass then backward pass, exactly like our Value example.
  4. 9Gradients are stored on the tensors themselves.
  5. 11Reset a gradient manually before the next backward call.
Linear regression with raw tensorsrun on your computer
import torch

torch.manual_seed(0)
x = torch.linspace(0, 3, 40).unsqueeze(1)          # shape (40, 1)
y = 2 * x + 1 + 0.1 * torch.randn_like(x)

w = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
lr = 0.05

for step in range(200):
    pred = x * w + b
    loss = ((pred - y) ** 2).mean()
    loss.backward()
    with torch.no_grad():                           # update without recording it
        w -= lr * w.grad
        b -= lr * b.grad
    w.grad.zero_()
    b.grad.zero_()

print(w.item(), b.item())                           # close to 2 and 1

Line by line

  1. 3Seed PyTorch's random generator for repeatable noise.
  2. 4-5Forty inputs shaped as a column, and noisy targets around the line 2x + 1.
  3. 7-9Two trainable parameters and a learning rate.
  4. 11-13Forward pass and mean squared error, then backward.
  5. 14-16Update parameters inside torch.no_grad() so the update is not part of the graph.
  6. 17-18Clear gradients for the next step.
  7. 20.item() converts a one-element tensor to a Python float.

In-place updates such as w -= ... on a tensor that requires gradients raise an error unless they happen inside torch.no_grad(). If you see 'a leaf Variable that requires grad is being used in an in-place operation', that is the message you are looking at.

nn.Module, Dataset, DataLoader and optimizers

Writing parameters by hand does not scale, so PyTorch packages the common pieces. An nn.Module is a class that owns parameters and defines a forward method. Layers such as nn.Linear are modules, and a module can contain other modules, so a model is a tree. Parameters assigned as layers in __init__ are discovered automatically, which is how an optimiser finds them with model.parameters().

A Dataset knows how to return one sample, and a DataLoader wraps it to give shuffled mini-batches. For tensors already in memory, TensorDataset is enough. An optimizer such as torch.optim.SGD or Adam holds references to the parameters and implements step(). A loss function such as nn.MSELoss or nn.CrossEntropyLoss is also a module. With these four parts, the loop you wrote by hand shrinks to five lines.

Here is the full structure for the XOR problem, using a two-layer model. Two details deserve attention. First, you call model(inputs), not model.forward(inputs), because calling the module runs hooks and bookkeeping around forward. Second, nn.CrossEntropyLoss expects raw scores (logits) and integer class labels, so you do not put a softmax at the end of the model.

A complete nn.Module training looprun on your computer
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader

torch.manual_seed(0)
X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y = torch.tensor([0, 1, 1, 0])                      # class labels as integers

loader = DataLoader(TensorDataset(X, y), batch_size=2, shuffle=True)

class XorNet(nn.Module):
    def __init__(self, hidden=8):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(2, hidden),
            nn.Tanh(),
            nn.Linear(hidden, 2),                   # two logits, one per class
        )

    def forward(self, x):
        return self.layers(x)

model = XorNet()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)

for epoch in range(300):
    model.train()
    for xb, yb in loader:
        logits = model(xb)                          # forward
        loss = loss_fn(logits, yb)                  # loss
        optimizer.zero_grad()                       # clear old gradients
        loss.backward()                             # backward
        optimizer.step()                            # update

model.eval()
with torch.no_grad():
    print(model(X).argmax(dim=1))                   # expected: tensor([0, 1, 1, 0])

Line by line

  1. 1-3Import the core package, the nn namespace and data utilities.
  2. 5-7Seed, inputs and integer labels.
  3. 9A TensorDataset pairs inputs with labels; DataLoader yields shuffled batches of 2.
  4. 11-21A model is a class that inherits from nn.Module. super().__init__() is required. nn.Sequential chains layers in order.
  5. 23-25Instantiate the model, choose a loss and give Adam the model's parameters.
  6. 27-28Loop over epochs; model.train() switches layers like dropout to training behaviour.
  7. 29-35The standard five steps: forward, loss, zero gradients, backward, step.
  8. 37-39Switch to evaluation mode, disable gradient tracking, and take the highest-scoring class for each input.

The order zero_grad, backward, step is the one to memorise. Some people call zero_grad() at the start of the iteration rather than after the forward pass; both work as long as it runs before backward() and after the previous step().

πŸ’‘

model.train() and model.eval() do not turn gradients on or off. They change the behaviour of layers such as Dropout and BatchNorm. Gradient tracking is controlled by torch.no_grad(). Use both when you evaluate.

Devices, saving, loading and next steps

Tensors and models live on a device. By default that is the CPU. If you have an NVIDIA GPU with a matching PyTorch build, or on some systems Apple's GPU backend, you can move both the model and each batch to the accelerator with .to(device). The rule that trips beginners is that the model and its inputs must be on the same device; mixing them raises a runtime error. A small helper that chooses the device once and a habit of moving each batch inside the loop keeps code portable between a laptop and a GPU machine.

To keep a trained model, save its state_dict, a dictionary mapping parameter names to tensors, rather than pickling the whole object. To restore it, build the same model class, then call load_state_dict. Saving the dictionary is more robust because it does not depend on where your class is defined. When loading weights you did not create yourself, pass weights_only=True to torch.load, since the default pickle-based loading of arbitrary files can execute code. Recent PyTorch versions are moving toward making this the default, but passing it explicitly is clear and safe.

Where to go from here depends on your goal. For images you will meet nn.Conv2d and the torchvision package for datasets and pretrained models. For text you will meet embeddings and transformer layers. For tabular data, classic methods in scikit-learn are often a stronger and simpler baseline, so try them first. Whatever the domain, the loop you built on this page stays the same.

Device handling and checkpointsrun on your computer
import torch
from torch import nn

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model = nn.Linear(4, 1).to(device)            # move parameters to the device
batch = torch.randn(8, 4).to(device)          # inputs must be on the same device
print(model(batch).shape)                     # torch.Size([8, 1])

# save only the learned numbers
torch.save(model.state_dict(), "linear.pt")

# later, or in another script: rebuild the same architecture, then load
restored = nn.Linear(4, 1)
restored.load_state_dict(torch.load("linear.pt", weights_only=True))
restored.eval()

Line by line

  1. 4Choose a CUDA GPU when available, otherwise the CPU. Other accelerators have their own device names.
  2. 6-8Move the model's parameters and the data to the same device, then run a forward pass.
  3. 11Save the state_dict, a plain mapping from names to tensors.
  4. 14-16Create a new model with the same architecture, load the weights, and put it in evaluation mode.
What a checkpoint really is
import numpy as np

# The same idea as state_dict, with plain NumPy: parameters in a dict, saved and restored
params = {"w": np.array([[2.0]]), "b": np.array([1.0])}
np.savez("params.npz", **params)

loaded = dict(np.load("params.npz"))
print(sorted(loaded))                # names of the saved parameters
print(loaded["w"].item(), loaded["b"].item())
Expected output
['b', 'w']
2.0 1.0

Line by line

  1. 3-5Parameters as a dictionary of arrays; savez stores every array under its name.
  2. 7-9Loading returns the same names and values, which is all a state_dict really is.

Checkpoints are also how you resume after a crash. Many projects save the optimizer's state_dict and the epoch number alongside the model, so training can continue instead of restarting.

Common mistakes

❌ Forgetting to zero the gradients

Gradients accumulate in .grad across backward() calls. If you never call optimizer.zero_grad(), each step uses the sum of all previous gradients, and the loss behaves strangely or explodes. Clear gradients once per optimisation step, before backward().

❌ Mixing devices

A model on the GPU with a batch on the CPU raises an error that mentions two different devices. Choose one device variable, move the model once and move every batch inside the loop.

❌ Evaluating with tracking on and in training mode

If you validate without model.eval() and torch.no_grad(), dropout and batch-norm layers behave as they do in training and PyTorch wastes memory building graphs you never use. Wrap evaluation code in both.

❌ Passing probabilities to CrossEntropyLoss

nn.CrossEntropyLoss applies log-softmax internally and wants raw logits plus integer class indices. Adding your own softmax before it makes the loss wrong in a way that still runs without an error.

❌ Using a learning rate by habit

A learning rate that works for one model can diverge on another. When the loss becomes nan or rises, try a smaller value first, and when it falls very slowly, try a larger one. Tune it before changing the architecture.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What is the main job of loss.backward()?

Q2. In our Value class, why are gradients added with += instead of assigned?

Q3. Why can a model with no hidden layer not learn XOR?

Q4. Which order is the usual training step?

Q5. What should you save to store a trained PyTorch model most robustly?

Q6. What does torch.no_grad() do?

Frequently asked questions

No. All the concepts on this page work on a CPU, and small models train fine on a laptop. A GPU helps when models or datasets get large. Free hosted notebooks that offer a GPU are one way to try one; check their current terms yourself.

Both are capable. PyTorch is very common in research and in open-source model code, which is why many people learn it first. The concepts of tensors, autograd and training loops transfer between frameworks, so learning one makes the other much easier.

They look and behave alike, but tensors can run on GPUs and can record operations for automatic differentiation. You can convert between them, and on the CPU the conversion shares memory.

Calling the module object runs forward plus extra machinery such as hooks. Calling forward directly skips that machinery, so the convention is to always call the module itself.

Track loss on a validation set that is never used for updates. If training loss keeps decreasing while validation loss stops improving or rises, the model is memorising the training data.

Key takeaways

  • βœ“A tensor is a typed grid of numbers that can live on a GPU and can track operations for differentiation.
  • βœ“Autograd records a graph in the forward pass and applies the chain rule backwards; gradients accumulate, so clear them each step.
  • βœ“Gradient descent moves each parameter against its gradient, scaled by a learning rate that you must choose carefully.
  • βœ“A hidden layer with a non-linear activation lets a network learn patterns such as XOR that a linear model cannot.
  • βœ“Every training loop has the same shape: batches, forward, loss, zero gradients, backward, step, then validation without gradients.
  • βœ“Build models with nn.Module, feed them with DataLoader, optimise with torch.optim, and save the state_dict.