Compute GAN discriminator and non-saturating generator losses from logits

A GAN's discriminator outputs a logit per sample. It is trained to call real samples 1 and fakes 0, while the generator uses the non-saturating loss, which pushes D(fake) toward 1 and keeps gradients alive early in training. Early on, logits get large, so a naive sigmoid then log produces inf.

Write gan_losses(real_logits, fake_logits), both 1D arrays of logits. With sigma the sigmoid:
- d_loss = mean(-log sigma(real)) + mean(-log(1 - sigma(fake)))
- g_loss = mean(-log sigma(fake))
Return {"d_loss": float, "g_loss": float}. It must stay finite and accurate for logits as large as plus or minus 1000.

Use softplus(t) = log(1 + e^t): -log sigma(t) = softplus(-t) and -log(1 - sigma(t)) = softplus(t). Compute softplus stably, e.g. with np.logaddexp(0, t).

Signaturedef gan_losses(real_logits, fake_logits)

Example

real = [0], fake = [0] gives d_loss = 2 log 2 = 1.38629 and g_loss = log 2 = 0.69315.

Understand the idea

The discriminator gives each sample a logit: positive means it thinks the sample is real. It is trained to call real samples 1 and fakes 0. The generator uses the non-saturating loss, which tries to make the discriminator call fakes real. All of these are binary cross-entropies, and each one is a softplus of the logit, which you can compute without forming huge exponentials. Worked example: real logit 2, fake logit -1. -log sigmoid(2) = softplus(-2) = 0.1269. -log(1 - sigmoid(-1)) = softplus(-1) = 0.3133. So d_loss = 0.1269 + 0.3133 = 0.4402. g_loss = -log sigmoid(-1) = softplus(1) = 1.3133. Rules: softplus(t) = log(1 + e^t); -log sigmoid(t) = softplus(-t); -log(1 - sigmoid(t)) = softplus(t); d_loss = mean softplus(-real) + mean softplus(fake); g_loss = mean softplus(-fake). Compute softplus as max(t, 0) + log1p(exp(-|t|)) so logits of plus or minus 1000 stay finite. Taking sigmoid first and then log returns inf when the discriminator becomes confident.

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_losses([0.0], [0.0])
  • Sample 2: random logitsgan_losses(_real, _fake)