Schulman's post on approximating KL starts where real models are: you can compute p(x) and q(x) for any x, but you can't do the sum or the integral. Draw x from p, and average log(p(x) / q(x)). That's the estimator he calls k1, and it's unbiased.
Predict
q is very close to p, so the true KL is tiny. What share of single-sample k1 values come out negative?
In Schulman's words, k1 has high variance, as it's negative for half of the samples, whereas KL is always positive. His k3 adds a term whose average is zero: with r = q(x) / p(x), it's (r − 1) − log r, which is never negative.
rng = np.random.default_rng(3)# 2,000 deliveries from carrier Axs = rng.normal(mu_p, s_p, 2_000)# a model much closer to pmu_c, s_c = 4.1, 1.2# log q(x) / p(x)log_r = normal_logpdf(xs, mu_c, s_c) - normal_logpdf(xs, mu_p, s_p)k1 = -log_rk3 = np.exp(log_r) - 1 - log_rprint(f"true KL {kl_normal(mu_p, s_p, mu_c, s_c):.5f}")for name, k in (("k1", k1), ("k3", k3)): print(f"{name}: mean {k.mean():.5f}, one-sample spread {k.std():.4f}, negative {np.mean(k < 0):.0%}")
true KL 0.00347k1: mean 0.00117, one-sample spread 0.0827, negative 49%k3: mean 0.00342, one-sample spread 0.0048, negative 0%
Here k3's spread is 17 times smaller than k1's. Schulman's summary: k3 has even lower standard deviation than k2 while being unbiased, so it appears to be a strictly better estimator. PyTorch's KLDivLoss takes the same care with logs: to avoid underflow issues, it expects its input in log space.
In the editor, write kl_estimates(log_p, log_q). It prints both estimates for five samples.
Pick an answer above to see the rest
Instructions
1
Write kl_estimates(log_p, log_q): with log r = log q(x) − log p(x) at each sample, return the mean of −log r and the mean of (r − 1) − log r.