Bird
Raised Fist0
PyTorchml~20 mins

Zeroing gradients in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Gradient Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PyTorch code snippet?

Consider the following PyTorch code that performs a backward pass and then prints the gradient of a tensor. What will be printed?

PyTorch
import torch
x = torch.tensor([2.0], requires_grad=True)
y = x * 3
z = y ** 2
z.backward()
print(x.grad)
x.grad.zero_()
print(x.grad)
Atensor([36.])\ntensor([36.])
Btensor([36.])\ntensor([0.])
Ctensor([6.])\ntensor([0.])
Dtensor([6.])\ntensor([6.])
Attempts:
2 left
💡 Hint

Remember that backward() computes gradients and zero_() sets them to zero in-place.

❓ Model Choice
intermediate
1:30remaining
Which PyTorch method correctly resets gradients before a new training step?

In a typical training loop, which method should be called to clear gradients before computing new ones?

Atorch.no_grad()
Bmodel.zero_grad()
Coptimizer.zero_grad()
Dloss.backward()
Attempts:
2 left
💡 Hint

Think about which object manages the parameters and their gradients during optimization.

❓ Hyperparameter
advanced
1:30remaining
What happens if you forget to zero gradients in a PyTorch training loop?

Consider a training loop where optimizer.zero_grad() is never called. What is the effect on the gradients during training?

AGradients accumulate, causing updates to be larger than intended.
BGradients are reset automatically each step, so no effect.
CTraining will raise a runtime error due to missing zeroing.
DGradients become zero, so model weights do not update.
Attempts:
2 left
💡 Hint

Think about how PyTorch accumulates gradients by default.

🔧 Debug
advanced
2:00remaining
Why does this PyTorch code raise an error when zeroing gradients?

Examine the code below. Why does it raise an error at x.grad.zero_()?

PyTorch
import torch
x = torch.tensor([1.0, 2.0], requires_grad=True)
y = x.sum()
y.backward()
x.grad = None
x.grad.zero_()
Ax.grad is None, so calling zero_() raises AttributeError.
Bx.grad is not a tensor, so zero_() is undefined.
Cx.grad has already been zeroed, so zero_() fails.
Dx.grad is a scalar, zero_() requires a tensor.
Attempts:
2 left
💡 Hint

What happens if you assign None to a variable and then call a method on it?

🧠 Conceptual
expert
2:30remaining
Why is zeroing gradients important in mini-batch training?

In mini-batch gradient descent, why must gradients be zeroed before processing each batch?

ATo save memory by deleting old gradients permanently.
BTo initialize model weights to zero before each batch.
CBecause gradients are automatically reset after optimizer.step().
DTo prevent gradient accumulation from previous batches, ensuring correct updates.
Attempts:
2 left
💡 Hint

Consider how PyTorch handles gradients across multiple backward passes.

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

  1. Step 1: Understand gradient accumulation in PyTorch

    PyTorch accumulates gradients by default, so old gradients stay unless cleared.
  2. Step 2: Purpose of zeroing gradients before backward pass

    Zeroing gradients ensures only the current batch's gradients are used for updating weights.
  3. Final Answer:

    To clear old gradients so new gradients are calculated correctly -> Option D
  4. 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

  1. Step 1: Recall PyTorch optimizer API

    The correct method to zero gradients is zero_grad() on the optimizer object.
  2. Step 2: Check method names for zeroing gradients

    Only zero_grad() is valid; others are incorrect or do not exist.
  3. Final Answer:

    optimizer.zero_grad() -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    36.0 -> Option A
  4. 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

  1. Step 1: Understand correct order of zeroing gradients

    Gradients must be zeroed before calling loss.backward() to avoid accumulation.
  2. Step 2: Identify error in given code

    Here, zero_grad() is called after optimizer.step(), so old gradients accumulate during backward pass.
  3. Final Answer:

    Gradients are zeroed after optimizer.step(), causing stale gradients in next iteration -> Option B
  4. 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

  1. Step 1: Understand gradient accumulation

    To accumulate gradients over multiple batches, zero_grad() is called once before loop, then backward() accumulates gradients.
  2. Step 2: Check correct update and zeroing frequency

    After 4 batches, optimizer.step() updates weights, then zero_grad() clears gradients for next accumulation cycle.
  3. Final Answer:

    Code snippet C correctly accumulates gradients and updates every 4 batches -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard