52KL divergence, discrete and continuous

mediumpython
40:00

52 KL divergence, discrete and continuous

An OpenAI coding round asked candidates to implement KL divergence for continuous distributions (1 source). This is practice in that shape, not a leaked question. Use the standard library, and numpy in levels 2 and 3. All logs are natural.

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/52_kl_divergence -k level1. Earlier levels must keep passing.

Level 1. Discrete. kl_divergence(p, q) is Σ p log(p / q) over two lists of probabilities: a term where p is 0 counts as 0, and it's float("inf") if q is 0 where p isn't. js_divergence(p, q) is the Jensen-Shannon divergence: with m the average of p and q, it's half of KL(p ‖ m) plus half of KL(q ‖ m).

Level 2. Continuous. kl_normal(mu1, sigma1, mu2, sigma2) is KL(N(mu1, sigma1²) ‖ N(mu2, sigma2²)) in closed form: log(sigma2 / sigma1) + (sigma1² + (mu1 − mu2)²) / (2 sigma2²) − 1/2. kl_on_grid(log_p, log_q, lo, hi, n=20_001) takes two functions that return log densities for a numpy array of x values, and integrates p(x) (log p(x) − log q(x)) over n evenly spaced points from lo to hi, both ends included (np.linspace), with the trapezoid rule (np.trapezoid). Work with the log densities: far in the tails p(x) underflows to 0, and p × log(p / q) then gives 0 × log 0 = nan, while p × (log p − log q) stays 0.

Level 3. From samples. kl_from_samples(samples, log_p, log_q) takes a numpy array of samples drawn from p, and the same kind of log density functions as level 2, and returns two estimates of KL(p ‖ q) as a tuple. With r = q(x) / p(x) for each sample, the first is the mean of −log r, and the second is the mean of (r − 1) − log r.

Things to get right: zero terms, the order of p and q, the midpoint in JS, squares in the closed form, the p in front of the log in the integral, and which density goes on top of r. Follow-ups from the lesson: why the second estimate never goes negative, forward against reverse KL, and what to do when you only have samples of both.

solution.py
Run the tests to see which pass.