Autograd and Gradient Descent by Hand
Every neural network learns the same way. It makes a guess, measures how wrong the guess is, and nudges its numbers to be a little less wrong. That nudge is called gradient descent. In this lesson you will do it by hand first, with plain numpy, and then let PyTorch do the hard part for you with autograd.
If you have not seen the idea of loss and gradient descent before, the short course How Neural Networks Actually Work explains it without code. This lesson assumes you know the idea and want to see it run.
What You'll Learn
- What a loss function measures
- What a gradient tells you, in plain words
- How to run gradient descent by hand on a tiny problem
- How PyTorch's autograd computes gradients for you with
requires_gradand.backward() - Why you must reset gradients with
zero_grad()before each step
The Problem: Find the Hidden Rule
Say you have five data points. Each x is a number, and each y is the answer.
| x | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| y | 5 | 7 | 9 | 11 | 13 |
The hidden rule is y = 2x + 3. The model does not know that. It starts with a guess, y = w * x + b, where w (the weight) and b (the bias) are random. Training means finding the w and b that make the guesses match the data.
Step 1: Measure How Wrong You Are
A loss function turns "how wrong" into one number. For predicting numbers, a common choice is mean squared error (MSE):
- For each point, take prediction minus true answer.
- Square it, so negative and positive errors both count.
- Take the average.
A loss of 0 means perfect guesses. Bigger means worse.
Step 2: Find Which Way to Move
The gradient answers one question for each number in the model: "If I make this number a little bigger, does the loss go up or down, and by how much?"
- A positive gradient means "bigger makes the loss worse", so you move the number down.
- A negative gradient means "bigger makes the loss better", so you move the number up.
That is why the update rule subtracts the gradient:
w = w - learning_rate * gradient_of_w
b = b - learning_rate * gradient_of_b
The learning rate is the step size. Too small and training is slow. Too big and the numbers jump past the answer and the loss blows up.
Try It: Gradient Descent with numpy
This part runs right here in your browser. For MSE with y = w * x + b, the gradients have a short formula, which is written out in the code. Press Run and watch the loss shrink while w moves toward 2 and b moves toward 3.
Try changing learning_rate to 0.1 and then to 0.001. With a big step the loss jumps around or grows. With a tiny step, 200 steps are not enough to reach the answer.
The Catch: Real Networks Have Millions of Numbers
Here you wrote the gradient formulas by hand. That works for two numbers. A real network has thousands or millions of weights, stacked in many layers. Nobody writes those formulas by hand.
This is what autograd solves. PyTorch remembers every math step you do with a tensor. When you call .backward() on the loss, it walks those steps in reverse and fills in the gradient for every number that needs one. This reverse walk is called backpropagation.
The Same Problem with PyTorch Autograd
PyTorch does not run in our browser playground, so open a Google Colab notebook (see lesson 1) and paste this into a cell. PyTorch is already installed in Colab, and this small example runs fine on CPU.
import torch
x = torch.tensor([1., 2., 3., 4., 5.])
y = torch.tensor([5., 7., 9., 11., 13.])
# requires_grad=True tells PyTorch to track gradients for these
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
learning_rate = 0.05
for step in range(201):
pred = w * x + b
loss = ((pred - y) ** 2).mean()
loss.backward() # autograd fills w.grad and b.grad
with torch.no_grad(): # update without tracking this step
w -= learning_rate * w.grad
b -= learning_rate * b.grad
w.grad.zero_() # reset, or gradients add up
b.grad.zero_()
if step % 25 == 0:
print(f"step {step:3d} loss {loss.item():.4f} w {w.item():.3f} b {b.item():.3f}")
You should see the same numbers as the numpy version. The difference: you never wrote grad_w or grad_b. PyTorch worked them out.
Three lines need a closer look:
loss.backward()computes the gradients and stores them inw.gradandb.grad.with torch.no_grad():tells PyTorch not to track the update itself. The update is not part of the model's math.w.grad.zero_()resets the gradient. PyTorch adds new gradients to old ones by default. If you forget to reset, each step uses the sum of all past gradients and training goes wrong.
Let PyTorch Do the Update Too
Writing the update by hand gets long. PyTorch gives you optimizers that do it for you. Here is the same training with torch.optim.SGD (stochastic gradient descent) and a ready-made loss function:
import torch
from torch import nn
x = torch.tensor([1., 2., 3., 4., 5.])
y = torch.tensor([5., 7., 9., 11., 13.])
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD([w, b], lr=0.05)
for step in range(201):
pred = w * x + b
loss = loss_fn(pred, y)
optimizer.zero_grad() # 1. reset old gradients
loss.backward() # 2. compute new gradients
optimizer.step() # 3. update the numbers
print(f"w = {w.item():.2f}, b = {b.item():.2f}")
Learn these three lines by heart: zero_grad(), backward(), step(). Every PyTorch training loop you will ever see has them, including the one you write in the next lesson.
Common Mistakes
- Forgetting
zero_grad(). The loss stops going down or jumps around. - Forgetting
requires_grad=Trueon your own tensors..backward()then has nothing to fill, andw.gradstaysNone. Layers fromtorch.nnturn this on for you. - Calling
.item()too early..item()gives you a plain Python number. That is fine for printing, but you cannot call.backward()on it.
Key Takeaways
- A loss function turns "how wrong" into one number. Training tries to make it small.
- A gradient says which way to move each number to lower the loss.
- Gradient descent repeats: predict, measure loss, compute gradients, step against the gradient.
- Autograd computes gradients for you when you call
loss.backward(). - Every PyTorch training step is
optimizer.zero_grad(),loss.backward(),optimizer.step().
Quiz
Up next · Lesson 3 of 6
Build and Train a Network on Fashion-MNIST
6 min read
2 of 6 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

