Autograd Basics: requires_grad and backward

JS
Jai Singh
20 Nov, 2026 4 min read 16 views

Autograd is PyTorch's automatic differentiation engine. If a tensor has requires_grad=True, PyTorch records every operation applied to it. Calling .backward() on a scalar result then computes the derivative of that result with respect to every tracked tensor and stores it in each tensor's .grad attribute. Training a neural network is simply this, repeated many times.

A first gradient

import torch

x = torch.tensor(3.0, requires_grad=True)
y = x ** 2 + 2 * x + 1      # y = x^2 + 2x + 1

y.backward()
print(x.grad)               # tensor(8.)

The derivative of x**2 + 2x + 1 is 2x + 2, which at x = 3 equals 8. PyTorch computed that without you writing any calculus. The gradient answers: "if I nudge x up slightly, how much does y change?"

Several inputs

w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)
x = torch.tensor(5.0)               # plain data, no gradient needed
target = torch.tensor(13.0)

pred = w * x + b                    # 11
loss = (pred - target) ** 2         # 4

loss.backward()
print(w.grad)                       # tensor(-20.)
print(b.grad)                       # tensor(-4.)

By the chain rule, d loss / d pred = 2 * (pred - target) = -4. Then d pred / d w = x = 5 gives -20 for w, and d pred / d b = 1 gives -4 for b. The negative sign says increasing w would reduce the loss, so gradient descent moves w up. This is exactly what an optimiser does with real models.

Gradient descent by hand

w = torch.tensor(0.0, requires_grad=True)
lr = 0.1

for step in range(20):
    loss = (w * 5.0 - 13.0) ** 2
    loss.backward()
    with torch.no_grad():
        w -= lr * w.grad
    w.grad.zero_()

print(w.item())       # close to 2.6, since 2.6 * 5 = 13

Each step computes the gradient, nudges w against it inside torch.no_grad() (so the update itself is not tracked), and then clears the gradient. The next posts explain why that last line matters.

Rules to remember

  • backward() needs a scalar. A loss is a single number. For a non-scalar output you must pass a gradient argument, for example y.backward(torch.ones_like(y)), or reduce it first with .sum().
  • Only floating-point tensors can require gradients. Integer tensors cannot.
  • .grad accumulates. Calling backward twice adds the new gradient to the old one.
  • Only leaf tensors keep .grad by default. A leaf is a tensor you created directly, such as a weight. Intermediate results do not store their gradient unless you call retain_grad().

Non-scalar outputs

x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2                       # a vector

y.sum().backward()               # reduce to a scalar first
print(x.grad)                    # tensor([2., 4., 6.])

Checking gradients numerically

If you write a custom operation, you can verify its gradient against finite differences:

def f(x):
    return torch.sin(x) * x

x = torch.tensor(1.3, dtype=torch.float64, requires_grad=True)
f(x).backward()

eps = 1e-6
numeric = (f(x.detach() + eps) - f(x.detach() - eps)) / (2 * eps)
print(x.grad.item(), numeric.item())   # nearly identical

Double precision keeps the numerical estimate accurate. PyTorch also ships torch.autograd.gradcheck for this purpose, which becomes useful when you write custom autograd functions later in the course.

Why gradients matter for learning

The gradient is the direction in which the loss increases fastest, so moving the opposite way reduces the loss. A neural network may have millions of weights, and autograd supplies one gradient per weight in a single backward pass. The cost of the backward pass is of the same order as the forward pass, which is what makes training large models feasible at all. The weights themselves are updated by an optimiser using these gradients and a small step size called the learning rate.

Autograd works because every differentiable operation in PyTorch knows its own local derivative. When you chain operations together, the backward pass multiplies these local derivatives together using the chain rule, starting from the loss and moving back toward the inputs. You never need to specify this order yourself; PyTorch stores the information while the forward computation runs. The next post looks at that stored structure, the computational graph, and shows how to inspect it.

Common mistakes

  • Forgetting requires_grad=True: x.grad stays None.
  • Calling backward() on a tensor that has no gradient history, which raises an error.
  • Creating a weight with an integer literal such as torch.tensor(2), which cannot require grad.
  • Updating a weight with w = w - lr * w.grad. This creates a new non-leaf tensor. Use an in-place update inside no_grad, or let an optimiser do it.

Next, we look at what autograd records behind the scenes: the computational graph.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.