JA EN
LearnInformation Theory
·★ MEMBER·PAPER·9 min read

KL Divergence From Scratch — Measuring the Gap Between Two Distributions

KL divergence measures the gap between two probability distributions. We build it up from a compression metaphor to the definition, its famous asymmetry, and a numpy implementation — then watch it at work as the regularizer in VAEs and the leash in RLHF.

ModalitytextTaskmath

Training language models to follow instructions with human feedback

Primary source — what this article is built on

undefined2022-03-04undefined2026-08-134y 5mo later

Auto-Encoding Variational BayesarXiv:1312.6114Paper page·PDF
Training language models to follow instructions with human feedbackLong Ouyang, Jeff Wu, Xu Jiang et al. · 2022-03-04 · v1arXiv:2203.02155Paper page·PDF
undefined

Making language models bigger does not inherently make them better at following a user's intent. For example, large language models can generate outputs that are untruthful, toxic, or simply not helpful to the user. In other words, these models are not aligned with their users. In this paper, we show an avenue for aligning language models with user intent on a wide range of tasks by fine-tuning with human feedback. Starting with a set of labeler-written prompts and prompts submitted through the OpenAI API, we collect a dataset of labeler demonstrations of the desired model behavior, which we use to fine-tune GPT-3 using supervised learning. We then collect a dataset of rankings of model outputs, which we use to further fine-tune this supervised model using reinforcement learning from human feedback. We call the resulting models InstructGPT. In human evaluations on our prompt distribution, outputs from the 1.3B parameter InstructGPT model are preferred to outputs from the 175B GPT-3, despite having 100x fewer parameters. Moreover, InstructGPT models show improvements in truthfulness and reductions in toxic output generation while having minimal performance regressions on public NLP datasets. Even though InstructGPT still makes simple mistakes, our results show that fine-tuning with human feedback is a promising direction for aligning language models with human intent.


We need a number for "how far apart are these two distributions?"

Strip away the details and most of machine learning is one job: take the true distribution PP and push a model distribution QQ toward it. For a language model, PP is the distribution of words humans actually write next and QQ is the model's prediction. For a weather app, PP is what the sky actually does and QQ is the forecast.

You cannot push QQ toward PP until you can measure how far apart they are — one number, computable, differentiable. The standard ruler is KL divergence (Kullback–Leibler divergence). The name is intimidating; the substance is not. It is simply the average cost of acting on a wrong belief. This article builds it up in the usual order — metaphor, intuition, definition, code — and then follows it into two places where it quietly runs the modern AI stack: the loss function of VAEs and the reward objective of RLHF.

The metaphor: overpaying with the wrong codebook

As we saw in the information theory article, the trick to compressing data is to give short codes to frequent symbols and long codes to rare ones. The ideal code length is set by probability: a symbol with probability pp deserves about log1p\log \frac{1}{p} bits.

Now imagine a planning mistake. You believe tomorrow's data will follow distribution QQ, so you build the codebook that is optimal for QQ. But the data actually arrives from a different distribution PP. Symbols you bet on rarely show up; symbols you assigned long codes to keep appearing. Your compressed files are consistently fatter than they had to be.

The average number of extra bits you pay because of that wrong belief is exactly the KL divergence DKL(PQ)D_{\mathrm{KL}}(P \| Q). If PP and QQ agree, the surcharge is zero. The more they disagree, the more you overpay. That is the KL way of thinking: measure the gap between distributions as real, incurred cost.

The intuition: averaging the excess surprise

Here is the same idea from a second angle. Information theory measures the "surprise" of an event with probability pp as log1p\log \frac{1}{p} — the rarer the event, the bigger the surprise.

Suppose symbol xx actually arrives. Believing QQ, your surprise is log1q(x)\log \frac{1}{q(x)}. Someone who knows the true distribution feels only log1p(x)\log \frac{1}{p(x)}. The difference, logp(x)q(x)\log \frac{p(x)}{q(x)}, is how much extra surprise your wrong belief cost you on this one event. Average that over how events actually occur — weight by p(x)p(x) — and you have KL. KL divergence is the expected excess surprise.

The definition: one line

DKL(PQ)=xp(x)logp(x)q(x)D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{x} p(x) \log \frac{p(x)}{q(x)}
(1)

Read aloud: for each symbol xx, take the log of the ratio between the true probability p(x)p(x) and the believed probability q(x)q(x), then average it weighted by how often xx really occurs. PP is the true distribution, QQ is the approximation (the model), and for continuous variables the sum simply becomes an integral. Use log base 2 and the answer is in bits; use the natural log and it is in nats.

Tie that back to the metaphor and the sum is the surcharge, which says: a wrong belief about a symbol you meet constantly lands hard on the bill, while the same wrong belief about a symbol you almost never see barely moves it. Weighting by p(x)p(x) is what puts that on the meter.

Two properties are worth memorizing. First, KL is never negative, and it equals zero only when PP and QQ match exactly (Gibbs' inequality) — the minimum qualification for anything calling itself a measure of mismatch. Second, it relates to cross-entropy by H(P,Q)=H(P)+DKL(PQ)H(P,Q) = H(P) + D_{\mathrm{KL}}(P\|Q). Since H(P)H(P) depends only on the data, it is a constant during training — so minimizing cross-entropy, the loss you use for classification and LLM pretraining, is exactly minimizing KL divergence. The training loop you run every day has been lowering a KL all along.

FIG 1Drag the temperature slider to sharpen or flatten the distribution. Treat the current bars as "model Q" and the temperature-1 shape as "true P" — the more the shapes drift apart, the larger the KL between them

Here is where KL gets interesting. Swap and in the definition and the value changes.

What's behind this

§

Members-only from here

371 walkthroughs, 26 textbook chapters, 48 student units and 6 close readings — all included for $4.99/mo, with three new explainers every day. Cancel any time; access runs to the end of the period.

Already a member? Sign in to keep reading

References

  1. Auto-Encoding Variational Bayes. arXiv:1312.6114Paper page·PDF
  2. Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida et al.. (2022-03-04) Training language models to follow instructions with human feedback. arXiv:2203.02155Paper page·PDF

This article is written from the source paper above. Where they differ, the original is authoritative.

Comments

Sign in to comment