Bird
Raised Fist0
PyTorchml~20 mins

GAN training loop in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
GAN Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of discriminator loss calculation in GAN training loop
Consider the following snippet from a GAN training loop where the discriminator loss is calculated. What is the output of print(d_loss.item()) after one backward pass?
PyTorch
import torch
import torch.nn as nn

criterion = nn.BCELoss()
d_real = torch.tensor([0.9], requires_grad=True)
d_fake = torch.tensor([0.1], requires_grad=True)
real_labels = torch.ones_like(d_real)
fake_labels = torch.zeros_like(d_fake)

loss_real = criterion(d_real, real_labels)
loss_fake = criterion(d_fake, fake_labels)
d_loss = loss_real + loss_fake
d_loss.backward()
print(round(d_loss.item(), 3))
A0.211
B0.000
C0.693
D0.105
Attempts:
2 left
💡 Hint
Recall that BCELoss for a prediction close to the true label is low, and for wrong predictions is high.
❓ Model Choice
intermediate
1:30remaining
Choosing the correct optimizer update step in GAN training
In a GAN training loop, after computing the discriminator loss and calling d_loss.backward(), which of the following is the correct next step to update the discriminator's weights?
Aloss.backward()
Boptimizer_d.zero_grad()
Coptimizer_d.step()
Doptimizer_g.step()
Attempts:
2 left
💡 Hint
Think about which optimizer corresponds to the discriminator.
❓ Hyperparameter
advanced
2:00remaining
Effect of learning rate on GAN training stability
Which of the following learning rate choices is most likely to cause unstable GAN training with mode collapse?
ALearning rate = 0.0005
BLearning rate = 0.0002
CLearning rate = 0.00005
DLearning rate = 0.1
Attempts:
2 left
💡 Hint
High learning rates can cause large weight updates and instability.
🔧 Debug
advanced
2:00remaining
Identifying the bug in GAN generator training step
In the generator training step below, which line causes the generator to not learn properly?
PyTorch
optimizer_g.zero_grad()
fake_data = generator(noise)
d_fake = discriminator(fake_data)
g_loss = criterion(d_fake, real_labels)
g_loss.backward()
optimizer_d.step()  # <-- suspicious line
Ag_loss.backward()
Boptimizer_d.step()
Coptimizer_g.zero_grad()
Dcriterion(d_fake, real_labels)
Attempts:
2 left
💡 Hint
Check which optimizer should update the generator weights.
🧠 Conceptual
expert
2:30remaining
Why alternate training of discriminator and generator is important in GANs
Why do GAN training loops alternate between updating the discriminator and the generator instead of updating both simultaneously?
ATo prevent one network from overpowering the other, maintaining a balance for stable training
BBecause simultaneous updates cause syntax errors in PyTorch
CTo reduce the total training time by skipping some updates
DBecause the generator requires more frequent updates than the discriminator
Attempts:
2 left
💡 Hint
Think about the adversarial nature of GANs and training stability.

Practice

(1/5)
1. In a GAN training loop, what is the main role of the discriminator?
easy
A. To calculate the learning rate
B. To generate new fake data samples
C. To distinguish between real and fake data
D. To optimize the generator's weights directly

Solution

  1. Step 1: Understand the discriminator's purpose

    The discriminator's job is to tell apart real data from fake data created by the generator.
  2. Step 2: Differentiate roles in GAN

    The generator creates fake data, while the discriminator judges it. It does not generate data or adjust learning rates.
  3. Final Answer:

    To distinguish between real and fake data -> Option C
  4. Quick Check:

    Discriminator = spot fake data [OK]
Hint: Discriminator judges data authenticity, generator creates data [OK]
Common Mistakes:
  • Confusing discriminator with generator
  • Thinking discriminator generates data
  • Assuming discriminator sets learning rate
2. Which of the following is the correct way to zero the gradients of both generator and discriminator optimizers in PyTorch during a GAN training loop?
easy
A. optimizer_G.clear(); optimizer_D.clear()
B. optimizer_G.zero_grad(); optimizer_D.zero_grad()
C. optimizer_G.reset_grad(); optimizer_D.reset_grad()
D. optimizer_G.zero(); optimizer_D.zero()

Solution

  1. Step 1: Recall PyTorch optimizer method

    In PyTorch, the method to clear gradients before backpropagation is zero_grad().
  2. Step 2: Check each option's validity

    Only optimizer_G.zero_grad(); optimizer_D.zero_grad() uses zero_grad(), which is the correct method. Other options use non-existent methods.
  3. Final Answer:

    optimizer_G.zero_grad(); optimizer_D.zero_grad() -> Option B
  4. Quick Check:

    Clear gradients = zero_grad() [OK]
Hint: Use zero_grad() to clear gradients before backward pass [OK]
Common Mistakes:
  • Using non-existent optimizer methods
  • Forgetting to zero gradients before backward
  • Confusing zero_grad() with optimizer step()
3. Given the following PyTorch GAN training snippet, what will be the printed output for print(loss_D.item(), loss_G.item()) after one iteration?
real_data = torch.ones(4)
fake_data = torch.zeros(4)
criterion = torch.nn.BCELoss()

# Discriminator output
output_real = torch.tensor([0.9, 0.8, 0.95, 0.85])
output_fake = torch.tensor([0.1, 0.2, 0.05, 0.15])

loss_real = criterion(output_real, real_data)
loss_fake = criterion(output_fake, fake_data)
loss_D = (loss_real + loss_fake) / 2

# Generator tries to fool discriminator
output_fake_for_G = torch.tensor([0.4, 0.3, 0.5, 0.6])
loss_G = criterion(output_fake_for_G, real_data)

print(loss_D.item(), loss_G.item())
medium
A. Approximately 0.693 and 0.105
B. Approximately 0.0 and 1.0
C. Approximately 0.5 and 0.5
D. Approximately 0.136 and 0.831

Solution

  1. Step 1: Calculate discriminator loss

    Loss_real = BCELoss([0.9,0.8,0.95,0.85], [1,1,1,1]) ≈ 0.136; Loss_fake = BCELoss([0.1,0.2,0.05,0.15], [0,0,0,0]) ≈ 0.136; Average loss_D ≈ 0.136.
  2. Step 2: Calculate generator loss

    Generator tries to fool discriminator, so loss_G = BCELoss([0.4,0.3,0.5,0.6], [1,1,1,1]) ≈ 0.831.
  3. Final Answer:

    Approximately 0.136 and 0.831 -> Option D
  4. Quick Check:

    Discriminator loss < Generator loss [OK]
Hint: Discriminator loss low near 0, generator loss higher when fooled less [OK]
Common Mistakes:
  • Mixing up real and fake labels in loss
  • Confusing which loss belongs to generator
  • Ignoring averaging of discriminator losses
4. Identify the error in this GAN training loop snippet and select the fix:
for real_data in dataloader:
    optimizer_D.zero_grad()
    output_real = discriminator(real_data)
    loss_real = criterion(output_real, torch.ones_like(output_real))

    fake_data = generator(torch.randn(batch_size, noise_dim))
    output_fake = discriminator(fake_data.detach())
    loss_fake = criterion(output_fake, torch.zeros_like(output_fake))

    loss_D = loss_real + loss_fake
    loss_D.backward()
    optimizer_D.step()

    optimizer_G.zero_grad()
    output_fake_for_G = discriminator(fake_data)
    loss_G = criterion(output_fake_for_G, torch.ones_like(output_fake_for_G))
    loss_G.backward()
    optimizer_D.step()
medium
A. Replace last optimizer_D.step() with optimizer_G.step()
B. Add optimizer_G.zero_grad() before loss_G.backward()
C. Detach fake_data before passing to generator
D. Use torch.zeros_like for output_fake_for_G labels

Solution

  1. Step 1: Analyze optimizer steps

    After computing generator loss and backward, the generator's optimizer should update weights, not discriminator's.
  2. Step 2: Identify incorrect optimizer call

    The code calls optimizer_D.step() twice; the second should be optimizer_G.step() to update generator.
  3. Final Answer:

    Replace last optimizer_D.step() with optimizer_G.step() -> Option A
  4. Quick Check:

    Generator update uses optimizer_G.step() [OK]
Hint: Generator updates need optimizer_G.step(), not optimizer_D.step() [OK]
Common Mistakes:
  • Calling discriminator optimizer twice
  • Forgetting to update generator weights
  • Misplacing zero_grad calls
5. You want to improve GAN training stability by modifying the training loop. Which change below best helps prevent the discriminator from overpowering the generator?
hard
A. Train the discriminator less frequently than the generator
B. Increase the learning rate of the discriminator only
C. Remove the generator's loss calculation
D. Use the same optimizer instance for both models

Solution

  1. Step 1: Understand discriminator overpowering

    If the discriminator learns too fast, the generator receives poor feedback and training stalls.
  2. Step 2: Evaluate options to balance training

    Training discriminator less often than generator slows its learning, giving generator a chance to improve.
  3. Final Answer:

    Train the discriminator less frequently than the generator -> Option A
  4. Quick Check:

    Balance training frequency to stabilize GAN [OK]
Hint: Train discriminator less often to balance GAN training [OK]
Common Mistakes:
  • Increasing discriminator learning rate worsens imbalance
  • Removing generator loss stops generator learning
  • Sharing optimizer causes parameter update conflicts
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