Learn PyTorch · 2/12

Autograd: Automatic Differentiation

6 min read

Autograd: Automatic Differentiation ⚙️

Welcome to the world of automatic differentiation with PyTorch's autograd! This powerful engine is the heart of how neural networks learn. But before we dive in, let's understand the problem it so cleverly solves.

The Problem: Training a neural network involves adjusting its parameters (weights and biases) to minimize a loss function. To do this, we need to know how a small change in each parameter affects the overall loss. This is where calculus comes in, specifically, the concept of gradients. Calculating these gradients for complex models with millions of parameters by hand would be an absolute nightmare. Imagine trying to solve a massive, interconnected puzzle where moving one piece slightly changes the entire picture. That's the challenge of gradient calculation in deep learning.

The Solution: torch.autograd automates this entire process. It keeps track of all the operations performed on tensors and then, with a single command, calculates the gradients of a specified tensor (usually the loss) with respect to other tensors (usually the model's parameters).


1. The Concept of Gradients and Computational Graphs 🧠

What are Gradients?
In the context of machine learning, a gradient is a vector that points in the direction of the steepest ascent of a function. For a neural network's loss function, the negative of the gradient points in the direction of the steepest descent. By following this direction, we can iteratively update our model's parameters to minimize the loss.

What are Computational Graphs?
PyTorch uses a concept called a computational graph to track all the operations. A computational graph is a directed acyclic graph (DAG) where nodes represent mathematical operations and edges represent the flow of data (tensors).

When you perform operations on tensors in PyTorch, it dynamically builds this graph. This graph is then used during the backward pass (backpropagation) to calculate the gradients. The forward pass defines the graph, and the backward pass, initiated by calling .backward(), uses this graph to compute gradients.

Imagine this: You're building a complex LEGO structure. Each LEGO block you add is an operation, and the connections between them represent the flow of your construction. The final structure is your output. Now, if you want to know how adjusting a single block at the very beginning affects the final structure, you would trace back your steps. That's essentially what a computational graph allows PyTorch to do for calculating gradients.

Here's a simple visual representation:
x -> [add] -> y -> [multiply] -> z

In this graph, x and other tensors are the inputs, add and multiply are operations, and y and z are the intermediate and final outputs.

A fun fact: The concept of computational graphs isn't new and has been a cornerstone of various fields in computer science, but its application in deep learning frameworks like PyTorch has made it incredibly powerful and accessible for training complex models.


2. Using requires_grad and the Backward Pass 🚀

To tell PyTorch to track the operations for a tensor and thus enable automatic gradient calculation, you need to set its requires_grad attribute to True. Any tensor that is a result of an operation involving a tensor with requires_grad=True will also have this attribute set to True.

The backward() method:
Once you have your final output (usually the loss, which should be a scalar), you can call the .backward() method on it. This initiates the backpropagation process, and PyTorch will automatically compute the gradients of this output with respect to all the tensors in the computational graph that have requires_grad=True. These gradients are then stored in the .grad attribute of those tensors.

Let's see it in action:

python
import torch

# Create tensors with requires_grad=True
x = torch.tensor(2.0, requires_grad=True)
w = torch.tensor(3.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)

# Define a simple computation
y = w * x + b
loss = (y - 8.0)**2 # A simple squared error loss

# Initiate the backward pass
loss.backward()

# Print the gradients
print(f"Gradient of loss with respect to x: {x.grad}")
print(f"Gradient of loss with respect to w: {w.grad}")
print(f"Gradient of loss with respect to b: {b.grad}")

What's happening here?

  1. We define three tensors x, w, and b and set requires_grad=True.
  2. We perform a series of operations to get y and then calculate a loss.
  3. When we call loss.backward(), PyTorch traverses the computational graph backwards from loss.
  4. It calculates the gradients and stores them in x.grad, w.grad, and b.grad.

3. Disabling Gradient Tracking with torch.no_grad() 🛑

There are situations where you don't need PyTorch to track gradients. The most common scenario is during inference (when you're using a trained model to make predictions). Disabling gradient tracking can significantly speed up your computations and reduce memory usage.

For this, PyTorch provides a context manager called torch.no_grad(). Any code inside this block will not be tracked by autograd.

Example of using torch.no_grad():

python
import torch

# A tensor that requires gradients
x = torch.randn(3, requires_grad=True)
print(f"x.requires_grad: {x.requires_grad}")

# Operations inside the with block will not have gradients tracked
with torch.no_grad():
    y = x * 2
    print(f"y.requires_grad inside no_grad: {y.requires_grad}")

# Operations outside the block will still be tracked
z = x + 1
print(f"z.requires_grad outside no_grad: {z.requires_grad}")

Why is this important in the industry?
When deploying models for real-world applications, performance is key. Using torch.no_grad() during inference is a standard practice to ensure your model runs as efficiently as possible. It prevents the overhead of building the computational graph, leading to faster predictions and lower memory consumption.


4. Accumulating and Zeroing Gradients 쌓다/비우다

Gradient Accumulation:
By default, every time you call .backward(), the newly computed gradients are added to the .grad attribute of the tensors. This is known as gradient accumulation.

Why is this useful? It's a technique used to simulate a larger batch size than your GPU memory can handle. Instead of processing a large batch at once, you can process several smaller mini-batches and accumulate their gradients. Only after accumulating the gradients for a certain number of mini-batches do you update the model's weights.

Zeroing Gradients:
Because gradients accumulate, you need to explicitly zero them out before starting a new training iteration. If you don't, the gradients from the previous batch will be added to the gradients of the current batch, leading to incorrect updates of your model's parameters.

This is typically done using optimizer.zero_grad().

Here's a standard training loop structure:

python
import torch
import torch.optim as optim

# Sample model, loss function, and optimizer
model = torch.nn.Linear(10, 1)
loss_fn = torch.nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

# A mini-batch of data
inputs = torch.randn(32, 10)
targets = torch.randn(32, 1)

# Training loop iteration
# 1. Zero the gradients
optimizer.zero_grad()

# 2. Forward pass
outputs = model(inputs)
loss = loss_fn(outputs, targets)

# 3. Backward pass to compute gradients
loss.backward()

# 4. Update the weights
optimizer.step()

In this loop:

  1. optimizer.zero_grad() clears the .grad attribute of all model parameters.
  2. The forward pass computes the model's output and the loss.
  3. loss.backward() calculates the gradients for the current batch.
  4. optimizer.step() updates the model's parameters using the computed gradients.

This cycle of zeroing gradients, forward pass, backward pass, and parameter update is the fundamental process of training a neural network in PyTorch.


Extra Reading 📚

Challenge

Challenge: Manual Gradient Management in a Training Loop

You are tasked with simulating the core steps of a neural network training loop using PyTorch's autograd engine. Your goal is to correctly compute and manage gradients for a simple linear model over several iterations.

Requirements:

  1. You are given four tensors: x (input), y (true output), w (weight), and b (bias). The weight and bias tensors are already configured to track gradients.
  2. Write a for loop that simulates three training iterations.
  3. Inside the loop, for each iteration, you must perform the following steps in order:
    a. Calculate the model's prediction, y_pred, using the formula y_pred = x * w + b.
    b. Compute the Mean Squared Error (MSE) loss. The formula is loss = (y_pred - y).pow(2).sum().
    c. Perform backpropagation on the loss to compute the gradients for w and b.
    d. Crucially, you must implement the step that prevents gradients from one iteration from affecting the next. Gradients should be calculated fresh for each pass.
  4. After the loop finishes, access and store the final computed gradient for the weight tensor w in a variable named final_w_grad.

Expected result

Your solution should be a Python script that correctly implements a training loop for three iterations.

The script must:

  1. Contain a for loop that runs exactly three times.
  2. Inside the loop, correctly calculate the y_pred and loss tensors as specified.
  3. Call the .backward() method on the loss tensor in each iteration.
  4. Include the correct method call to zero out the gradients for both w and b at the appropriate point within the loop to prevent accumulation. This is the key part of the challenge.
  5. The final line of your implementation should assign the .grad attribute of the w tensor to the final_w_grad variable after the loop has completed.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.