Compute WGAN-GP critic and generator losses with an analytic input gradient
A Wasserstein GAN critic outputs an unbounded score, and the gradient penalty keeps the critic's gradient norm near 1 at points between real and fake data. Usually autograd supplies that gradient; here you derive it by hand for a tiny critic.
Write wgan_gp_losses(real, fake, eps, W1, b1, w2, b2, lam=10.0). real and fake are (B, D), eps is (B,) in [0, 1], W1 is (D, k), b1 is (k,), w2 is (k,), b2 is a float. The critic is f(x) = tanh(x W1 + b1) . w2 + b2.
1. x_hat = eps[:, None] * real + (1 - eps[:, None]) * fake.
2. g = gradient of f at each x_hat with respect to x (shape (B, D)). Derive it with the chain rule.
3. gp = lam * mean((||g||_2 - 1)**2), the norm taken per row.
4. critic_loss = mean f(fake) - mean f(real) + gp, gen_loss = -mean f(fake).
Return {"critic_loss": float, "gen_loss": float, "gp": float}.
def wgan_gp_losses(real, fake, eps, W1, b1, w2, b2, lam=10.0)Example
check: if W1 is all zeros, g is zero for every row, so gp = lam.
Understand the idea
A WGAN critic gives real samples high scores and fakes low scores. To keep it well behaved, the gradient penalty asks that the critic's slope with respect to its input be about 1 at points mixed between real and fake samples. Here the critic is tiny, f(x) = tanh(x W1 + b1) . w2 + b2, so you derive its input gradient by hand with the chain rule. Worked example with D = k = 1: W1 = 1, b1 = 0, w2 = 2, and an interpolated point x_hat = 0. The hidden value is tanh(0) = 0, so the gradient is W1 * (w2 * (1 - 0^2)) = 2. Its norm is 2, (2 - 1)^2 = 1, and with lam = 10 the penalty is 10. Rules: x_hat = eps * real + (1 - eps) * fake per row; g = (w2 * (1 - tanh(x_hat W1 + b1)^2)) @ W1^T; gp = lam * mean((norm(g) - 1)^2) with the row norm not squared; critic_loss = mean f(fake) - mean f(real) + gp; gen_loss = -mean f(fake). If W1 is zero, g is zero and gp = lam. It stabilises GAN training.