Take one discriminator and one generator step of a 1D GAN by hand

Why it matters This alternating update is the core loop of every GAN, from DCGAN to StyleGAN.

A GAN alternates two updates. Doing one round by hand, with gradients you derive yourself, makes the game concrete.

Write gan_step(params, x_real, z, lr). params is a dict with generator G(z) = a * z + c and discriminator D(x) = sigmoid(w * x + v). x_real and z are 1D arrays of the same length. Step 1: with x_fake = G(z), compute d_loss = -mean(log D(x_real)) - mean(log(1 - D(x_fake))), take its gradients with respect to w and v and update them by SGD (the generator is held fixed). Step 2: using the UPDATED w and v and the same z, compute the non-saturating g_loss = -mean(log D(G(z))), take its gradients with respect to a and c and update them. Return a dict with the new "a", "c", "w", "v" and the losses "d_loss" and "g_loss" (each computed before its own update) as floats.

Signaturedef gan_step(params, x_real, z, lr)

Example

params {"a": 1, "c": 0, "w": 0, "v": 0}, x_real = [2], z = [0], lr = 1 gives d_loss 1.3863 (2 log 2), w 1.0, v 0.0, g_loss 0.6931, a 1.0 and c 0.5 (rounded).

Understand the idea

A GAN is a game between a forger (the generator) and a detective (the discriminator). The detective learns to say real for real data and fake for generated data. Then the forger changes its output to fool the improved detective. Each round is two separate gradient steps, and each player only moves its own parameters.

Tiny example: D starts at w = v = 0, so it says 0.5 for everything: d_loss = log 2 + log 2 = 1.386. Real x = 2 gives gradient (0.5 - 1) * 2 = -1 for w, fake x = 0 gives 0; so w becomes 1. v gets -0.5 + 0.5 = 0. Now D(0) = 0.5 still, g_loss = log 2, and the generator's c gradient is (0.5 - 1) * w = -0.5, so c moves to 0.5, toward the real data.

Rules: dL_D/dlogit = D - 1 (real), D (fake); dL_G/dlogit = D(G(z)) - 1, then times w and the generator's inputs.

The non-saturating generator loss here is the standard choice because it gives strong gradients early in training.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplegan_step({'a': 1.0, 'c': 0.0, 'w': 0.0, 'v': 0.0}, [2.0], [0.0], 1.0)
  • Sample 2: batchgan_step({'a': 0.5, 'c': -1.0, 'w': 0.3, 'v': 0.1}, [1.5, 2.0, 2.5, 3.0], [-1.0, 0.0, 0.5, 1.0], 0.1)