Zeroing gradients means setting all the gradients of model parameters to zero before starting a new backward pass. This prevents accumulation of gradients from multiple passes.
Click to reveal answer
beginner
Why do we need to zero gradients before calling backward() in PyTorch?
Because PyTorch accumulates gradients by default, zeroing them ensures that gradients from previous batches do not mix with the current batch's gradients.
Click to reveal answer
beginner
Which PyTorch method is commonly used to zero gradients?
The method optimizer.zero_grad() is commonly used to reset all gradients to zero before the backward pass.
Click to reveal answer
intermediate
What happens if you forget to zero gradients in a training loop?
Gradients will accumulate across batches, causing incorrect updates and making training unstable or ineffective.
Click to reveal answer
beginner
Show a simple PyTorch training loop snippet that includes zeroing gradients.
for data, target in dataloader:
optimizer.zero_grad() # Reset gradients
output = model(data)
loss = loss_fn(output, target)
loss.backward() # Compute gradients
optimizer.step() # Update parameters
Click to reveal answer
What is the purpose of calling optimizer.zero_grad() in PyTorch?
ATo reset gradients to zero before computing new gradients
BTo update model parameters
CTo compute the loss value
DTo save the model state
✗ Incorrect
optimizer.zero_grad() clears old gradients so new gradients from the current batch do not accumulate with previous ones.
If you skip zeroing gradients, what will happen during training?
AGradients will accumulate, causing incorrect updates
BModel parameters will not update
CLoss will always be zero
DTraining will be faster
✗ Incorrect
Without zeroing, gradients add up across batches, leading to wrong parameter updates.
Which PyTorch function computes gradients for model parameters?
Amodel.eval()
Boptimizer.step()
Closs.backward()
Doptimizer.zero_grad()
✗ Incorrect
loss.backward() calculates gradients of the loss with respect to model parameters.
When should zeroing gradients be done in the training loop?
AAfter optimizer.step()
BBefore loss.backward()
CAfter loss.backward()
DAt the end of training
✗ Incorrect
Zeroing gradients must happen before computing new gradients with loss.backward().
What does optimizer.step() do in PyTorch?
AComputes the loss
BResets gradients to zero
CLoads data into the model
DUpdates model parameters using current gradients
✗ Incorrect
optimizer.step() applies the computed gradients to update model parameters.
Explain why zeroing gradients is important in a PyTorch training loop.
Think about what happens if gradients keep adding up over batches.
You got /3 concepts.
Describe the sequence of steps in a PyTorch training loop involving gradients.
Focus on the order of zeroing, backward, and stepping.
You got /5 concepts.
Practice
(1/5)
1. Why do we need to zero gradients in PyTorch before calling loss.backward() during training?
easy
A. To initialize the model parameters randomly
B. To save memory by deleting the model weights
C. To speed up the training by skipping backward pass
D. To clear old gradients so new gradients are calculated correctly
Solution
Step 1: Understand gradient accumulation in PyTorch
PyTorch accumulates gradients by default, so old gradients stay unless cleared.
Step 2: Purpose of zeroing gradients before backward pass
Zeroing gradients ensures only the current batch's gradients are used for updating weights.
Final Answer:
To clear old gradients so new gradients are calculated correctly -> Option D
Quick Check:
Zero gradients = fresh gradient calculation [OK]
Hint: Always zero gradients before backward pass to avoid accumulation [OK]
Common Mistakes:
Skipping zero_grad() causes wrong gradient sums
Confusing zeroing gradients with resetting weights
Thinking zero_grad() speeds training by skipping steps
2. Which of the following is the correct way to zero gradients for an optimizer named optimizer in PyTorch?
easy
A. optimizer.clear_grad()
B. optimizer.zero_gradients()
C. optimizer.zero_grad()
D. optimizer.reset_grad()
Solution
Step 1: Recall PyTorch optimizer API
The correct method to zero gradients is zero_grad() on the optimizer object.
Step 2: Check method names for zeroing gradients
Only zero_grad() is valid; others are incorrect or do not exist.
Final Answer:
optimizer.zero_grad() -> Option C
Quick Check:
Use zero_grad() method to clear gradients [OK]
Hint: Remember method name ends with '_grad', not '_gradients' [OK]
Common Mistakes:
Using zero_gradients() which does not exist
Confusing with clear_grad() or reset_grad() methods
Calling zero_grad on model instead of optimizer
3. What will be the output of the following PyTorch code snippet?
import torch
x = torch.tensor([2.0], requires_grad=True)
optimizer = torch.optim.SGD([x], lr=0.1)
optimizer.zero_grad()
y = x * 3
loss = y ** 2
loss.backward()
print(x.grad.item())
medium
A. 36.0
B. 12.0
C. 18.0
D. 6.0
Solution
Step 1: Calculate loss and gradients
y = 3 * x = 6.0; loss = y^2 = 36.0; gradient of loss wrt x is d(loss)/dx = 2*y * dy/dx = 2*6*3 = 36.
Step 2: Check printed gradient value
x.grad will hold 36.0 after backward, but since x.grad is printed directly, it shows 36.0.
Final Answer:
36.0 -> Option A
Quick Check:
Gradient = 2*y*3 = 36.0 [OK]
Hint: Use chain rule: d(loss)/dx = 2*y * dy/dx [OK]
Common Mistakes:
Calculating gradient as 12.0 by missing chain rule
Confusing loss value with gradient value
Forgetting to call zero_grad() before backward
4. Consider this training loop snippet:
for data, target in dataloader:
output = model(data)
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
optimizer.zero_grad()
What is the problem here?
medium
A. No problem, this is the correct order
B. Gradients are zeroed after optimizer.step(), causing stale gradients in next iteration
C. loss.backward() should be called after optimizer.step()
D. optimizer.zero_grad() should be called before loss.backward() to clear old gradients
Solution
Step 1: Understand correct order of zeroing gradients
Gradients must be zeroed before calling loss.backward() to avoid accumulation.
Step 2: Identify error in given code
Here, zero_grad() is called after optimizer.step(), so old gradients accumulate during backward pass.
Final Answer:
Gradients are zeroed after optimizer.step(), causing stale gradients in next iteration -> Option B
Quick Check:
Zero gradients before backward pass [OK]
Hint: Call zero_grad() before backward() to reset gradients [OK]
Common Mistakes:
Calling zero_grad() after optimizer.step() instead of before backward()
Swapping order of backward() and step()
Assuming zero_grad() is optional
5. You want to accumulate gradients over 4 mini-batches before updating model weights to simulate a larger batch size. Which code snippet correctly implements this using zeroing gradients in PyTorch?
hard
A.
optimizer.zero_grad()
for i, (data, target) in enumerate(dataloader):
output = model(data)
loss = loss_fn(output, target) / 4
loss.backward()
if (i + 1) % 4 == 0:
optimizer.step()
optimizer.zero_grad()
B.
for i, (data, target) in enumerate(dataloader):
optimizer.zero_grad()
output = model(data)
loss = loss_fn(output, target)
loss.backward()
if (i + 1) % 4 == 0:
optimizer.step()
C.
for i, (data, target) in enumerate(dataloader):
output = model(data)
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
optimizer.zero_grad()
D.
optimizer.zero_grad()
for data, target in dataloader:
output = model(data)
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
optimizer.zero_grad()
Solution
Step 1: Understand gradient accumulation
To accumulate gradients over multiple batches, zero_grad() is called once before loop, then backward() accumulates gradients.
Step 2: Check correct update and zeroing frequency
After 4 batches, optimizer.step() updates weights, then zero_grad() clears gradients for next accumulation cycle.
Final Answer:
Code snippet C correctly accumulates gradients and updates every 4 batches -> Option A
Quick Check:
Zero once, accumulate 4 backward calls, then step and zero [OK]
Hint: Zero gradients once, step and zero every N batches to accumulate [OK]
Common Mistakes:
Zeroing gradients inside loop every batch prevents accumulation
Not dividing loss by accumulation steps causing large gradients
Calling optimizer.step() every batch defeats accumulation purpose
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.