1/13
Learn

KL divergence, the way the coding round asks

An OpenAI coding round asked candidates to implement KL divergence for continuous distributions (1 source). This lesson's practice problem builds up to it, in three levels:

  1. kl_divergence(p, q) for two lists of probabilities, and js_divergence(p, q), the symmetric Jensen-Shannon version.
  2. kl_normal(mu1, sigma1, mu2, sigma2) in closed form, and kl_on_grid(log_p, log_q, lo, hi): the integral for any two densities, by the trapezoid rule.
  3. kl_from_samples(samples, log_p, log_q): two estimates from samples of p, one that can go negative on a single sample and one that never does.
CallReturns
kl_divergence([0.5, 0.3, 0.15, 0.05], [0.25] * 4)0.2442 nats
the same with p and q swapped0.3112 nats: KL isn't symmetric
kl_normal(4.0, 1.2, 4.5, 1.5)0.098699
kl_on_grid for the same two normals0.098699

The lesson follows the shop's sizes and delivery times: the discrete KL, the continuous one and its closed form, estimates from samples, forward against reverse KL, and where KL shows up in training. Six steps end with a small task in the editor.