Entropy and KL divergence, for continuous distributions too

55 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Compute the KL divergence between two discrete distributions, and say why it isn't a distance
  • Write the KL divergence between two normals, and check it with an integral on a grid
  • Explain why a continuous entropy can go negative while the KL divergence can't
  • Estimate KL from samples, and pick the estimator that never goes negative
  • Tell forward from reverse KL, and say which one RLHF, variational inference and distillation use

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.

Part 1 of 7about 8 min
KL divergence

KL divergence is the extra cost of the wrong model

The OpenAI question is about continuous distributions, but start with the discrete version: the continuous one is the same idea with an integral.

The likelihood lesson split cross entropy into the entropy plus a gap. That gap is the KL divergence:

DKL(p ∥ q)=∑ipilog⁡piqiD_{\mathrm{KL}}(p \,\|\, q) = \sum_i p_i \log \frac{p_i}{q_i}

The Deep Learning book reads it as the extra information needed to send messages drawn from P with a code designed for Q. Here p is how often each of the shop's four sizes sells, and q is a model that gives every size the same chance.

import numpy as np

# how often each of 4 sizes sells
p = np.array([0.50, 0.30, 0.15, 0.05])
# a model that knows nothing
q = np.array([0.25, 0.25, 0.25, 0.25])


def kl(p, q):
    """D(p || q) in nats."""
    keep = p > 0
    return np.sum(p[keep] * np.log(p[keep] / q[keep]))


cross = -np.sum(p * np.log(q))
entropy = -np.sum(p * np.log(p))
print(f"KL(p || q) {kl(p, q):.4f} = cross entropy {cross:.4f} - entropy {entropy:.4f}")
print(f"KL(q || p) {kl(q, p):.4f}")
Predict

KL(p ‖ q) comes out at 0.244 nats. What does that say about the uniform model?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

A new model gives XL a 0% chance, but 5% of sales are XL. What's KL(p ‖ q)?

Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 9 min
Continuous distributions

For densities, the sum becomes an integral

TTIC's information theory notes define the continuous version the same way, when both distributions have density functions: the integral of p(x) log(p(x) / q(x)). For two normals it has a closed form, which the same notes work out:

DKL(N(μ1,σ12) ∥ N(μ2,σ22))=log⁡σ2σ1+σ12+(μ1−μ2)22σ22−12D_{\mathrm{KL}}\big(\mathcal{N}(\mu_1, \sigma_1^2) \,\|\, \mathcal{N}(\mu_2, \sigma_2^2)\big) = \log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac{1}{2}

Predict

Two normals share a mean, with spreads 1 and 2. Which costs more: KL(wide ‖ narrow) or KL(narrow ‖ wide)?

Pick an answer above to see the rest

Days or weeks: what changes with the units

The same deliveries can be measured in days or in weeks. Before you run the code, decide what that does to each number.

Predict

Measure the same deliveries in weeks instead of days. What happens to the entropy and the KL?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 8 min
From samples

Without a formula, estimate KL from samples of p

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?

Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 10 min
Forward and reverse

Fit one normal to two peaks, in both directions

Fit one normal q to a distribution p by minimizing KL, and the direction decides the answer. The shop's deliveries come from two carriers: 60% by a fast courier around 2 days, 40% by the slow post around 6.

Predict

Fit a normal q by minimizing KL(p ‖ q). Where does it go?

Pick an answer above to see the rest
Predict

Now minimize KL(q ‖ p) instead. Where does q go?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 3 min
KL in training

RLHF, variational inference and distillation each minimize a KL

InstructGPT's RL step adds a per-token KL penalty from the SFT model at each token, to mitigate over-optimization of the reward model. The penalty is KL(policy ‖ reference) on the policy's own samples: the reverse direction.

Predict

Drop the KL penalty and run RL against a learned reward model for a long time. What tends to happen?

Pick an answer above to see the rest
Predict

Reward grows with the square root of the KL. What does twice the reward gain cost in KL?

Pick an answer above to see the rest
Predict

Distillation trains a student on a teacher's soft targets with cross entropy. Which KL does that minimize?

Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 9 min
The worked example

A worked example: KL for continuous distributions, out loud

Here's the OpenAI question, worked out loud.

Implement KL divergence for continuous distributions. The report is one line (1 source), and it leaves the inputs open, so ask.

1. Ask what you're given. Two named families, like normals? Two density functions you can evaluate? Samples from p only? Samples from both?

Predict

The interviewer says: two density functions of one variable, no formula. What's your first move?

Pick an answer above to see the rest
Predict

You only have samples of p and q. You bin both into histograms and compute the discrete KL. What can go wrong?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 8 min
Follow-ups

A symmetric version

Three follow-ups come up after KL questions.

Predict

You need a symmetric score that stays finite when the two supports differ. What's the standard choice?

Pick an answer above to see the rest

PyTorch's KLDivLoss reduction

The second follow-up is a PyTorch detail. PyTorch's documentation warns that the reduction named mean doesn't return the true KL divergence value, and to use batchmean, which aligns with the mathematical definition. mean divides by every element, the batch times the classes, instead of by the batch size.

Mutual information is a KL

The third follow-up links KL to dependence. The mutual information of two variables is the KL divergence from their joint distribution to the product of their marginals. It's 0 exactly when the two are independent.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.KL(p ‖ q) is 0.244 and KL(q ‖ p) is 0.311. What does that show?

  2. 2.A model gives a size a 0% chance, but 5% of sales are that size. What's KL(p ‖ q)?

  3. 3.The same delivery times are measured in weeks instead of days. What changes?

  4. 4.Which unbiased estimate of KL(p ‖ q) from samples of p never goes negative on a single sample?

  5. 5.Fit one normal to a two-peaked distribution by minimizing KL(q ‖ p). What do you get?

Practice

Sources (21)
  1. Deep Learning, Chapter 3: Probability and Information Theory · Ian Goodfellow, Yoshua Bengio and Aaron Courville · Nov 19, 2026
    “it is the extra amount of information ... needed to send a message containing symbols drawn from probability distribution P, when we use a code that was designed to minimize the length of messages drawn from probability distribution Q.”
  2. Deep Learning, Chapter 3: Probability and Information Theory · Ian Goodfellow, Yoshua Bengio and Aaron Courville · Nov 19, 2026
    “The KL divergence has many useful properties, most notably being non-negative.”
  3. Deep Learning, Chapter 3: Probability and Information Theory · Ian Goodfellow, Yoshua Bengio and Aaron Courville · Nov 19, 2026
    “It is not a true distance measure because it is not symmetric”
  4. scipy.stats.entropy · SciPy documentation · Nov 19, 2026
    “If qk is not None, then compute the relative entropy D = sum(pk * log(pk / qk)). This quantity is also known as the Kullback-Leibler divergence.”
  5. Information and Coding Theory, Lecture 6 · Madhur Tulsiani, TTIC (Winter 2025) · Jan 23, 2025
    “We define KL-divergence for two distributions analogously, when both distributions have associated density functions.”
  6. Information and Coding Theory, Lecture 6 · Madhur Tulsiani, TTIC (Winter 2025) · Jan 23, 2025
    “We can compute the KL-divergence of two Gaussian distributions”
  7. Approximating KL Divergence · John Schulman · Mar 7, 2020
    “we can compute the probabilities (or probability densities) p(x) and q(x) for any x, but we can’t calculate the sum over x analytically.”
  8. Approximating KL Divergence · John Schulman · Mar 7, 2020
    “However, it has high-variance, as it’s negative for half of the samples, whereas KL is always positive.”
  9. Approximating KL Divergence · John Schulman · Mar 7, 2020
    “k3 has even lower standard deviation than k2 while being unbiased, so it appears to be a strictly better estimator.”
  10. KLDivLoss · PyTorch 2.15 documentation · Nov 19, 2026
    “To avoid underflow issues when computing this quantity, this loss expects the argument input in the log-space.”
  11. Deep Learning, Chapter 3: Probability and Information Theory · Ian Goodfellow, Yoshua Bengio and Aaron Courville · Nov 19, 2026
    “Some applications require an approximation that usually places high probability anywhere that the true distribution places high probability, while other applications require an approximation that rarely places high probability anywhere that the true distribution places low probability.”
  12. Deep Learning, Chapter 3: Probability and Information Theory · Ian Goodfellow, Yoshua Bengio and Aaron Courville · Nov 19, 2026
    “When p has multiple modes, q chooses to blur the modes together, in order to put high probability mass on all of them.”
  13. Deep Learning, Chapter 3: Probability and Information Theory · Ian Goodfellow, Yoshua Bengio and Aaron Courville · Nov 19, 2026
    “the KL divergence is minimized by choosing a single mode, to avoid putting probability mass in the low-probability areas between modes of p.”
  14. Pattern Recognition and Machine Learning, 10.1.2 Properties of factorized approximations · Christopher M. Bishop (Springer; free PDF from Microsoft Research) · Nov 19, 2026
    “a variational treatment based on the minimization of KL(q‖p) will tend to find one of these modes. By contrast, if we were to minimize KL(p‖q), the resulting approximations would average across all of the modes”
  15. Training language models to follow instructions with human feedback · Ouyang et al., OpenAI (arXiv 2203.02155) · Mar 4, 2022
    “In addition, we add a per-token KL penalty from the SFT model at each token to mitigate over-optimization of the reward model.”
  16. Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback · Bai et al., Anthropic (arXiv 2204.05862) · Apr 12, 2022
    “identify a roughly linear relation between the RL reward and the square root of the KL divergence between the policy and its initialization.”
  17. Variational Inference: A Review for Statisticians · Blei, Kucukelbir and McAuliffe (arXiv 1601.00670) · Jan 4, 2016
    “The idea behind VI is to first posit a family of densities and then to find the member of that family which is close to the target. Closeness is measured by Kullback-Leibler divergence.”
  18. Variational Inference: A Review for Statisticians · Blei, Kucukelbir and McAuliffe (arXiv 1601.00670) · Jan 4, 2016
    “It penalizes placing mass in q(·) on areas where p(·) has little mass, but penalizes less the reverse.”
  19. Variational Inference: A Review for Statisticians · Blei, Kucukelbir and McAuliffe (arXiv 1601.00670) · Jan 4, 2016
    “We do know that variational inference generally underestimates the variance of the posterior density; this is a consequence of its objective function.”
  20. Distilling the Knowledge in a Neural Network · Hinton, Vinyals and Dean (arXiv 1503.02531) · Mar 9, 2015
    “The first objective function is the cross entropy with the soft targets and this cross entropy is computed using the same high temperature in the softmax of the distilled model as was used for generating the soft targets from the cumbersome model.”
  21. KLDivLoss · PyTorch 2.15 documentation · Nov 19, 2026
    “reduction = “mean” doesn’t return the true KL divergence value, please use reduction = “batchmean” which aligns with the mathematical definition.”