Concept Explanation
The previous lesson used model.fit(), which trains a network in one line. This lesson opens that line up, because everything interesting in deep learning happens inside it.
A deep learning framework gives you exactly two things NumPy does not:
- Tensors that run on a GPU — the same n-dimensional arrays, but able to move to hardware that does thousands of multiplications in parallel.
- Automatic differentiation — the framework records every operation you perform and can compute the derivative of the result with respect to any input, automatically.
The second is the real magic. Training a network means nudging millions of parameters in whichever direction reduces the error, which requires the gradient of the loss with respect to every one of them. Deriving that by hand for a 50-layer network is not feasible. Autograd does it exactly, for free, every step.
We will use PyTorch here because it makes both mechanisms explicit and inspectable. Keras hides the same machinery behind fit().
pip install torch
Tensors Are NumPy Arrays That Remember
import torch
t = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
t.shape # torch.Size([2, 2])
t.dtype # torch.float32
t.device # cpu
| Operation | NumPy | PyTorch |
|---|---|---|
| Create | np.array([1, 2]) | torch.tensor([1, 2]) |
| Zeros | np.zeros((2, 3)) | torch.zeros(2, 3) |
| Random normal | np.random.randn(2, 3) | torch.randn(2, 3) |
| Matrix multiply | a @ b | a @ b |
| Reshape | a.reshape(3, 2) | a.view(3, 2) or a.reshape(3, 2) |
| Sum along axis | a.sum(axis=0) | a.sum(dim=0) |
Two differences bite newcomers: PyTorch says dim where NumPy says axis, and PyTorch defaults to float32 where NumPy defaults to float64. Mixing dtypes raises errors rather than silently promoting.
requires_grad: Opting Into the Tape
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2 + 2 * x
y.backward()
print(x.grad) # tensor(8.) because dy/dx = 2x + 2 = 8
Three things happened:
- Marking
xwithrequires_grad=Truetold PyTorch to record operations involving it. - Each operation built a node in a computation graph — a record of what was computed from what.
backward()walked that graph in reverse, applying the chain rule, and deposited the result inx.grad.
This is reverse-mode automatic differentiation. It is not numerical approximation and not symbolic algebra; it is the chain rule applied mechanically to a recorded trace, and it is exact.
The Rules That Trip People Up
| Rule | Consequence |
|---|---|
| Gradients accumulate | x.grad adds on each backward(). Zero it between steps |
backward() needs a scalar | Call it on a loss, not on a batch of predictions |
The graph is freed after backward() | Calling it twice raises, unless retain_graph=True |
no_grad() disables recording | Wrap inference and parameter updates in it |
| In-place ops on leaves are blocked | Use with torch.no_grad(): p -= lr * p.grad |
The accumulation rule is the source of the most common deep learning bug in existence. Forget optimizer.zero_grad() and your gradients are the sum of every batch so far, which makes training diverge in a way that looks like a bad learning rate.
Moving to the GPU
device = "cuda" if torch.cuda.is_available() else "cpu"
x = x.to(device)
model = model.to(device)
Both the data and the model must be on the same device, or you get Expected all tensors to be on the same device. Writing device once at the top and .to(device) everywhere is the habit that avoids it.
Code Example #1 (Basic)
Autograd on a function you can differentiate by hand, so you can check it.
import torch
# --- A single variable ---
x = torch.tensor(3.0, requires_grad=True)
y = x ** 3 + 2 * x ** 2 - 5 * x
y.backward()
# dy/dx = 3x^2 + 4x - 5 -> 27 + 12 - 5 = 34
print(f"y = {y.item():.1f}, dy/dx at x=3 = {x.grad.item():.1f} (expected 34)")
# --- Two variables, one output ---
a = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(4.0, requires_grad=True)
loss = a ** 2 * b + b ** 3
loss.backward()
# dL/da = 2ab = 16 ; dL/db = a^2 + 3b^2 = 4 + 48 = 52
print(f"dL/da = {a.grad.item():.1f} (expected 16), dL/db = {b.grad.item():.1f} (expected 52)")
# --- Gradients ACCUMULATE: the classic bug, demonstrated ---
w = torch.tensor(1.0, requires_grad=True)
for step in range(3):
out = (w * 5) ** 2 # d/dw = 50w = 50 at w=1
out.backward()
print(f" step {step}: w.grad = {w.grad.item():.0f}")
print(" ^ 50, 100, 150 -- it summed. This is why you must zero gradients.\n")
w.grad = None # or optimizer.zero_grad()
# --- Gradient descent by hand: fit y = 2x + 1 ---
X = torch.tensor([[1.0], [2.0], [3.0], [4.0], [5.0]])
Y = torch.tensor([[3.0], [5.0], [7.0], [9.0], [11.0]])
weight = torch.randn(1, 1, requires_grad=True)
bias = torch.zeros(1, requires_grad=True)
lr = 0.02
for epoch in range(400):
pred = X @ weight + bias
loss = ((pred - Y) ** 2).mean() # mean squared error
loss.backward() # fills weight.grad and bias.grad
with torch.no_grad(): # updates must not be recorded
weight -= lr * weight.grad
bias -= lr * bias.grad
weight.grad.zero_() # reset for the next step
bias.grad.zero_()
if epoch % 100 == 0:
print(f"epoch {epoch:>3} loss {loss.item():.5f} "
f"w {weight.item():.3f} b {bias.item():.3f}")
print(f"\nLearned: y = {weight.item():.3f}x + {bias.item():.3f} (true: y = 2x + 1)")
That final loop is a complete neural network training run with no framework abstractions at all: forward pass, loss, backward pass, parameter update, zero gradients. Every deep learning library is a more convenient wrapper around those five lines.
Code Example #2 (Intermediate)
The same problem three ways, and a look inside the graph.
import torch
import torch.nn as nn
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"device: {device}\n")
# A non-linear target, so a single linear layer cannot solve it
X = torch.linspace(-3, 3, 300).unsqueeze(1) # shape (300, 1)
Y = torch.sin(X) + 0.1 * torch.randn_like(X)
X, Y = X.to(device), Y.to(device)
# ---------- 1. Manual parameters, manual updates ----------
W1 = torch.randn(1, 32, device=device, requires_grad=True) * 0.5
b1 = torch.zeros(32, device=device, requires_grad=True)
W2 = torch.randn(32, 1, device=device, requires_grad=True) * 0.5
b2 = torch.zeros(1, device=device, requires_grad=True)
params = [W1, b1, W2, b2]
for epoch in range(1500):
hidden = torch.tanh(X @ W1 + b1)
pred = hidden @ W2 + b2
loss = ((pred - Y) ** 2).mean()
for p in params:
if p.grad is not None:
p.grad.zero_()
loss.backward()
with torch.no_grad():
for p in params:
p -= 0.05 * p.grad
print(f"manual final loss {loss.item():.5f}")
# ---------- 2. nn.Module + an optimiser (the idiomatic way) ----------
model = nn.Sequential(
nn.Linear(1, 32),
nn.Tanh(),
nn.Linear(32, 1),
).to(device)
optimiser = torch.optim.Adam(model.parameters(), lr=0.02)
criterion = nn.MSELoss()
for epoch in range(1500):
optimiser.zero_grad() # <- replaces the manual loop above
loss = criterion(model(X), Y)
loss.backward()
optimiser.step() # <- replaces the manual update
print(f"nn.Module final loss {loss.item():.5f}")
print(f"parameters: {sum(p.numel() for p in model.parameters())}")
# ---------- 3. Inspect the computation graph ----------
x = torch.tensor(2.0, requires_grad=True)
y = torch.tensor(3.0, requires_grad=True)
z = (x * y + x ** 2).sqrt()
print(f"\nz = sqrt(x*y + x^2) = {z.item():.4f}")
print(f"z.requires_grad: {z.requires_grad}")
print(f"z.grad_fn: {z.grad_fn}") # the last op that produced z
print(f"one step back: {z.grad_fn.next_functions[0][0]}")
z.backward()
print(f"dz/dx = {x.grad.item():.4f}, dz/dy = {y.grad.item():.4f}")
# ---------- 4. no_grad(): 2-3x faster, no memory for the graph ----------
big = torch.randn(2000, 2000, device=device, requires_grad=True)
tracked = (big @ big).sum()
print(f"\ntracked result has grad_fn: {tracked.grad_fn is not None}")
with torch.no_grad():
untracked = (big @ big).sum()
print(f"no_grad result has grad_fn: {untracked.grad_fn is not None}")
print("Always wrap evaluation and inference in no_grad().")
Sections 1 and 2 produce the same result, which is the point: optimizer.zero_grad() / loss.backward() / optimizer.step() is not new machinery, it is the manual loop packaged. grad_fn shows the graph is a real linked structure you can walk, not a black box.
Common Mistakes
- Forgetting to zero gradients: they accumulate across steps, so training diverges for reasons that look unrelated. Call
optimizer.zero_grad()first thing every iteration. - Calling
backward()on a non-scalar:RuntimeError: grad can be implicitly created only for scalar outputs. Reduce to a loss with.mean()or.sum()first. - Updating parameters without
no_grad(): the update itself gets recorded, which corrupts the next backward pass. Wrap it, or use an optimiser. - Device mismatch: model on GPU, data on CPU. Define
deviceonce and.to(device)consistently. .numpy()on a tensor that requires grad: raises. Usetensor.detach().cpu().numpy()..item()inside a hot loop on GPU: it forces a synchronisation and stalls the pipeline. Accumulate tensors, convert at the end.- Calling
backward()twice: the graph is freed after the first call. If you genuinely need two passes, useretain_graph=True— but usually it means a bug. - Evaluating without
no_grad(): builds a graph you never use, wasting memory and time — and can trigger out-of-memory on large batches. - dtype mismatch:
float64NumPy data into afloat32model raises. Convert withtorch.tensor(arr, dtype=torch.float32). - Accumulating the loss tensor instead of the number:
total += losskeeps the whole graph alive for every batch. Usetotal += loss.item().
Best Practices
- Zero, backward, step — in that order, every iteration. Make it muscle memory.
- Define
deviceonce at the top and move both model and data with.to(device). - Wrap all inference and validation in
torch.no_grad(). - Call
.item()when logging so you keep a float, not a live graph node. - Set
torch.manual_seed(0)for reproducible runs while you are debugging. - Verify autograd against hand-computed derivatives on a toy function once — it turns the magic into arithmetic you trust.
- Prefer
nn.Moduleand an optimiser over manual parameters in real code; write the manual version once to understand it. - Check
tensor.shapeconstantly: most deep learning bugs are shape bugs, and broadcasting hides them until the loss makes no sense. - Use
detach()to cut the graph when you want a value carried forward but not differentiated through. - Read
grad_fnwhen confused: it tells you exactly which operation produced a tensor.
Practice Exercises
- The Derivative Check: Pick a function like
f(x) = x**4 - 3*x**2 + 2, computef'(x)by hand, then verify it at three values ofxwith autograd. Print both numbers side by side. - The Accumulation Bug: Write a loop that calls
backward()five times without zeroing gradients and printgradeach time. Then fix it and confirm the value stays constant. Write a comment on what this would look like during real training. - The Manual Network: Build a two-layer network for
y = x**2using only raw tensors,backward(), and manual updates insideno_grad()— nonn.Module, no optimiser. Then rewrite it withnn.Sequentialandtorch.optim.Adamand confirm both reach a similar loss.