Bird
Raised Fist0
PyTorchml~20 mins

Training loop structure in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Training Loop Master
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 training loop snippet?
Consider the following PyTorch training loop snippet. What will be the printed loss value after one batch?
PyTorch
import torch
import torch.nn as nn

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

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

optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()

print(round(loss.item(), 4))
A0.0
B0.5
C0.25
D0.75
Attempts:
2 left
πŸ’‘ Hint
Remember the initial weights of nn.Linear are random, so the loss won't be zero.
❓ Model Choice
intermediate
1:30remaining
Which part of the training loop updates the model's weights?
In a typical PyTorch training loop, which line is responsible for updating the model's weights?
Aoptimizer.zero_grad()
Bloss.backward()
Coptimizer.step()
Dcriterion(outputs, targets)
Attempts:
2 left
πŸ’‘ Hint
Think about which function applies the calculated gradients to the weights.
❓ Hyperparameter
advanced
1:30remaining
What effect does increasing the learning rate have in a training loop?
If you increase the learning rate in your training loop, what is the most likely effect on training?
ATraining may become unstable and loss might not decrease
BTraining will always be faster and more stable
CModel will automatically generalize better
DLoss function will change to a different type
Attempts:
2 left
πŸ’‘ Hint
Think about how too large steps affect finding the minimum loss.
πŸ”§ Debug
advanced
2:00remaining
Why does this training loop raise an error?
Examine this PyTorch training loop snippet. Why does it raise a RuntimeError?
PyTorch
import torch
import torch.nn as nn

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

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

outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
optimizer.step()  # Called twice without zero_grad
ACalling optimizer.step() twice without zero_grad causes error due to stale gradients
Bloss.backward() is missing before optimizer.step()
Coptimizer.zero_grad() is called after optimizer.step()
Dinputs and targets have mismatched shapes
Attempts:
2 left
πŸ’‘ Hint
Check how many times optimizer.step() is called without clearing gradients.
🧠 Conceptual
expert
1:30remaining
Why do we call optimizer.zero_grad() at the start of each training iteration?
In PyTorch training loops, why is optimizer.zero_grad() called before computing the loss and calling loss.backward()?
ATo zero out the loss value before backpropagation
BTo initialize model weights to zero
CTo clear the optimizer’s learning rate cache
DTo reset gradients so they don’t accumulate across batches
Attempts:
2 left
πŸ’‘ Hint
Think about what happens if gradients from previous batches are not cleared.

Practice

(1/5)
1. Which of the following best describes the main purpose of a training loop in PyTorch?
easy
A. To save the model to a file
B. To repeatedly update the model weights to improve performance
C. To visualize the model architecture
D. To load data from disk into memory

Solution

  1. Step 1: Understand the training loop role

    The training loop runs many times to adjust model weights based on data.
  2. Step 2: Identify the main goal

    Its goal is to improve model performance by updating weights repeatedly.
  3. Final Answer:

    To repeatedly update the model weights to improve performance -> Option B
  4. Quick Check:

    Training loop = update weights repeatedly [OK]
Hint: Training loop = repeat updates to improve model [OK]
Common Mistakes:
  • Confusing data loading with training loop
  • Thinking training loop saves model
  • Assuming training loop only visualizes model
2. Which of the following is the correct way to zero gradients in a PyTorch training loop?
easy
A. optimizer.zero_grad()
B. model.zero_gradients()
C. loss.zero_grad()
D. torch.zero_grad()

Solution

  1. Step 1: Recall PyTorch gradient clearing method

    Gradients are cleared by calling zero_grad() on the optimizer.
  2. Step 2: Check each option

    Only optimizer.zero_grad() is the correct PyTorch syntax.
  3. Final Answer:

    optimizer.zero_grad() -> Option A
  4. Quick Check:

    Clear gradients with optimizer.zero_grad() [OK]
Hint: Clear gradients with optimizer.zero_grad() [OK]
Common Mistakes:
  • Calling zero_grad on model or loss
  • Using non-existent torch.zero_grad()
  • Forgetting to zero gradients before backward pass
3. What will be the output of the following PyTorch training loop snippet?
for epoch in range(2):
    for batch in range(3):
        print(f"Epoch {epoch}, Batch {batch}")
medium
A. Epoch 0, Batch 0 Epoch 0, Batch 1 Epoch 1, Batch 0 Epoch 1, Batch 1
B. Epoch 0, Batch 0 Epoch 1, Batch 0 Epoch 2, Batch 0
C. Epoch 0, Batch 0 Epoch 0, Batch 1 Epoch 0, Batch 2
D. Epoch 0, Batch 0 Epoch 0, Batch 1 Epoch 0, Batch 2 Epoch 1, Batch 0 Epoch 1, Batch 1 Epoch 1, Batch 2

Solution

  1. Step 1: Understand loop ranges

    Outer loop runs for epochs 0 and 1 (2 times). Inner loop runs for batches 0,1,2 (3 times).
  2. Step 2: Trace output lines

    For each epoch, batches 0 to 2 print, so total 6 lines with epoch and batch numbers.
  3. Final Answer:

    Epoch 0, Batch 0 Epoch 0, Batch 1 Epoch 0, Batch 2 Epoch 1, Batch 0 Epoch 1, Batch 1 Epoch 1, Batch 2 -> Option D
  4. Quick Check:

    2 epochs x 3 batches = 6 lines printed [OK]
Hint: Multiply epochs by batches for total prints [OK]
Common Mistakes:
  • Confusing range end values
  • Mixing epoch and batch indices
  • Counting fewer batches than loop runs
4. Identify the error in this PyTorch training loop snippet:
for data, target in dataloader:
    optimizer.zero_grad()
    output = model(data)
    loss = criterion(output, target)
    loss.backward
    optimizer.step()
medium
A. Missing parentheses after loss.backward
B. optimizer.zero_grad() should be after optimizer.step()
C. criterion should be called before model(data)
D. optimizer.step() should be called before loss.backward

Solution

  1. Step 1: Check method calls

    loss.backward is missing parentheses, so it is not called as a function.
  2. Step 2: Verify correct order

    optimizer.zero_grad() is correctly before backward and step; criterion call order is correct; optimizer.step() after backward is correct.
  3. Final Answer:

    Missing parentheses after loss.backward -> Option A
  4. Quick Check:

    Call loss.backward() with parentheses [OK]
Hint: Always add () to call backward() [OK]
Common Mistakes:
  • Forgetting parentheses on backward()
  • Changing correct optimizer.zero_grad() position
  • Misordering loss and model calls
5. You want to train a model for 5 epochs with batches of size 10. Which of the following training loop structures correctly implements this in PyTorch?
hard
A. for epoch in range(5): optimizer.zero_grad() for batch_idx, (data, target) in enumerate(dataloader): output = model(data) loss = criterion(output, target) loss.backward() optimizer.step()
B. for batch_idx, (data, target) in enumerate(dataloader): for epoch in range(5): optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step()
C. for epoch in range(5): for batch_idx, (data, target) in enumerate(dataloader): optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step()
D. for epoch in range(5): for batch_idx, (data, target) in enumerate(dataloader): output = model(data) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step()

Solution

  1. Step 1: Check loop order

    The outer loop should be epochs, inner loop batches. for epoch in range(5): for batch_idx, (data, target) in enumerate(dataloader): optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() follows this correctly.
  2. Step 2: Verify zero_grad and step calls

    optimizer.zero_grad() must be before backward(), and optimizer.step() after. for epoch in range(5): for batch_idx, (data, target) in enumerate(dataloader): optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() has correct order.
  3. Step 3: Check other options

    for batch_idx, (data, target) in enumerate(dataloader): for epoch in range(5): optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() reverses loops (wrong). for epoch in range(5): optimizer.zero_grad() for batch_idx, (data, target) in enumerate(dataloader): output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() zeros gradients outside batch loop (wrong). for epoch in range(5): for batch_idx, (data, target) in enumerate(dataloader): output = model(data) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() zeros gradients after forward pass (wrong order).
  4. Final Answer:

    for epoch in range(5): for batch_idx, (data, target) in enumerate(dataloader): optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() -> Option C
  5. Quick Check:

    Epochs outside, zero_grad before backward, step after [OK]
Hint: Epoch loop outside, zero_grad before backward [OK]
Common Mistakes:
  • Swapping epoch and batch loops
  • Calling zero_grad outside batch loop
  • Calling zero_grad after forward pass
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