Bird
Raised Fist0
PyTorchml~5 mins

Gradient clipping in PyTorch

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Gradient clipping helps keep the training stable by stopping very large updates to the model. It prevents the model from making big jumps that can cause errors.

When training deep neural networks that sometimes have very large gradients.
When the training loss suddenly becomes very large or unstable.
When using recurrent neural networks (RNNs) that can have exploding gradients.
When you want to keep training smooth and avoid the model weights from changing too much at once.
Syntax
PyTorch
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)

# or

torch.nn.utils.clip_grad_value_(model.parameters(), clip_value)

clip_grad_norm_ limits the total size (norm) of all gradients combined.

clip_grad_value_ limits each gradient value individually.

Examples
This clips the gradients so their total norm does not exceed 1.0.
PyTorch
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
This clips each gradient value to be between -0.5 and 0.5.
PyTorch
torch.nn.utils.clip_grad_value_(model.parameters(), clip_value=0.5)
Sample Model

This example shows how to clip gradients to a maximum norm of 1.0 during training. It prints the gradient norm before and after clipping to see the effect.

PyTorch
import torch
import torch.nn as nn
import torch.optim as optim

# Simple model
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(2, 1)

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

# Create model, loss, optimizer
model = SimpleNet()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)

# Dummy data
inputs = torch.tensor([[10.0, 20.0], [30.0, 40.0]])
targets = torch.tensor([[1.0], [2.0]])

# Forward pass
outputs = model(inputs)
loss = criterion(outputs, targets)

# Backward pass
loss.backward()

# Before clipping: print gradient norm
total_norm = 0
for p in model.parameters():
    if p.grad is not None:
        param_norm = p.grad.data.norm(2)
        total_norm += param_norm.item() ** 2
total_norm = total_norm ** 0.5
print(f"Gradient norm before clipping: {total_norm:.4f}")

# Clip gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

# After clipping: print gradient norm
total_norm = 0
for p in model.parameters():
    if p.grad is not None:
        param_norm = p.grad.data.norm(2)
        total_norm += param_norm.item() ** 2
total_norm = total_norm ** 0.5
print(f"Gradient norm after clipping: {total_norm:.4f}")

# Optimizer step
optimizer.step()
OutputSuccess
Important Notes

Gradient clipping should be done after calling loss.backward() and before optimizer.step().

Clipping helps prevent the problem called 'exploding gradients' which can make training unstable.

Summary

Gradient clipping keeps training stable by limiting how big gradients can get.

Use clip_grad_norm_ to limit total gradient size or clip_grad_value_ to limit individual values.

Always clip gradients after backward pass and before optimizer step.

Practice

(1/5)
1. What is the main purpose of gradient clipping in PyTorch training?
easy
A. To prevent gradients from becoming too large and destabilizing training
B. To increase the learning rate automatically during training
C. To save memory by reducing model size
D. To initialize model weights before training

Solution

  1. Step 1: Understand gradient behavior during training

    Gradients can sometimes become very large, causing unstable updates and training divergence.
  2. Step 2: Role of gradient clipping

    Gradient clipping limits the size of gradients to keep training stable and prevent exploding gradients.
  3. Final Answer:

    To prevent gradients from becoming too large and destabilizing training -> Option A
  4. Quick Check:

    Gradient clipping = prevent large gradients [OK]
Hint: Gradient clipping stops gradients from exploding during training [OK]
Common Mistakes:
  • Thinking it changes learning rate
  • Confusing with weight initialization
  • Believing it reduces model size
2. Which PyTorch function is used to clip gradients by their norm?
easy
A. torch.optim.clip_grad_norm
B. torch.nn.utils.clip_grad_value_
C. torch.nn.utils.clip_grad_norm_
D. torch.clip_gradients

Solution

  1. Step 1: Recall PyTorch gradient clipping functions

    PyTorch provides two main functions: clip_grad_norm_ and clip_grad_value_ in torch.nn.utils.
  2. Step 2: Identify function for norm clipping

    clip_grad_norm_ clips gradients based on their total norm, while clip_grad_value_ clips individual gradient values.
  3. Final Answer:

    torch.nn.utils.clip_grad_norm_ -> Option C
  4. Quick Check:

    Norm clipping function = clip_grad_norm_ [OK]
Hint: clip_grad_norm_ clips total gradient size by norm [OK]
Common Mistakes:
  • Using clip_grad_value_ for norm clipping
  • Assuming optimizer has clipping functions
  • Using non-existent torch.clip_gradients
3. What will be the output of the following code snippet?
import torch
from torch.nn.utils import clip_grad_norm_

model = torch.nn.Linear(2, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

inputs = torch.tensor([[1.0, 2.0]])
target = torch.tensor([[1.0]])

optimizer.zero_grad()
output = model(inputs)
loss = (output - target).pow(2).mean()
loss.backward()
clip_grad_norm_(model.parameters(), max_norm=0.1)
for p in model.parameters():
    print(p.grad.norm().item())
medium
A. Code will raise an error because clip_grad_norm_ is called before backward()
B. Gradient norms will be unchanged and possibly larger than 0.1
C. Gradients will be zero because of clipping
D. All printed gradient norms will be less than or equal to 0.1

Solution

  1. Step 1: Understand code flow and gradient clipping

    Gradients are computed by loss.backward(), then clipped by clip_grad_norm_ with max_norm=0.1.
  2. Step 2: Effect of clip_grad_norm_ on gradients

    clip_grad_norm_ rescales gradients so their total norm does not exceed 0.1, so printed norms will be ≤ 0.1.
  3. Final Answer:

    All printed gradient norms will be less than or equal to 0.1 -> Option D
  4. Quick Check:

    clip_grad_norm_ limits gradient norm ≤ max_norm [OK]
Hint: clip_grad_norm_ rescales gradients after backward [OK]
Common Mistakes:
  • Calling clip_grad_norm_ before backward()
  • Expecting gradients to be zero after clipping
  • Thinking clipping increases gradient norms
4. Identify the error in this PyTorch training snippet using gradient clipping:
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
clip_grad_norm_(model.parameters(), max_norm=1.0)
loss.backward()
optimizer.step()
medium
A. clip_grad_norm_ should be called after optimizer.step()
B. clip_grad_norm_ is called before loss.backward(), so gradients are not clipped
C. max_norm should be set to 0, not 1.0
D. optimizer.zero_grad() should be called after optimizer.step()

Solution

  1. Step 1: Check order of operations for gradient clipping

    Gradients are created by loss.backward(), so clipping must happen after backward() to affect gradients.
  2. Step 2: Identify mistake in code order

    clip_grad_norm_ is called before loss.backward(), so gradients do not exist yet and clipping has no effect.
  3. Final Answer:

    clip_grad_norm_ is called before loss.backward(), so gradients are not clipped -> Option B
  4. Quick Check:

    Clip gradients after backward() [OK]
Hint: Always clip gradients after backward(), before optimizer.step() [OK]
Common Mistakes:
  • Clipping before backward()
  • Calling zero_grad() after step()
  • Setting max_norm to zero
5. You want to prevent exploding gradients in a deep RNN model. Which approach correctly applies gradient clipping in PyTorch during training?
hard
A. After loss.backward(), call torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5), then optimizer.step()
B. Before loss.backward(), call torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5), then optimizer.step()
C. After optimizer.step(), call torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5)
D. Call torch.nn.utils.clip_grad_value_(model.parameters(), max_norm=5) before loss.backward()

Solution

  1. Step 1: Understand correct gradient clipping sequence

    Gradients are computed by loss.backward(), so clipping must happen after this step and before optimizer.step().
  2. Step 2: Identify correct function and order

    clip_grad_norm_ is used to clip by norm, suitable for RNNs to prevent exploding gradients. It must be called after backward() and before optimizer.step().
  3. Final Answer:

    After loss.backward(), call torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5), then optimizer.step() -> Option A
  4. Quick Check:

    Clip gradients after backward(), before step() [OK]
Hint: Clip gradients after backward(), before optimizer step [OK]
Common Mistakes:
  • Clipping before backward()
  • Clipping after optimizer.step()
  • Using clip_grad_value_ incorrectly