vamsi aribandi

The best estimate of KL ≢ the best estimate of its gradient

KL divergence \mathrm{KL}[p\,\|\,q] = \mathbb{E}_{x\sim p}\!\left[\log\frac{p(x)}{q(x)}\right] is an important quantity in AI.

In reinforcement learning for language models, \mathrm{KL}[\pi_\theta\,\|\,\pi_\mathrm{ref}] is used as a regularizer to keep a learned policy \pi_\theta near a reference policy \pi_\mathrm{ref}, and on-policy distillation (OPD) lets a student policy \pi_\mathrm{student} learn from a teacher policy \pi_\mathrm{teacher} by minimizing \mathrm{KL}[\pi_\mathrm{student}\,\|\,\pi_\mathrm{teacher}].

Exactly computing KL between two language models is intractable, because the expectation \mathbb{E}_p is a sum over every possible sequence of tokens. Instead we estimate it from samples x \sim p.

Three estimators of KL are common:

\begin{aligned} k_1(x) &= \log\frac{p(x)}{q(x)}\\ k_2(x) &= \frac12\left(\log\frac{p(x)}{q(x)}\right)^2\\ k_3(x) &= \log\frac{p(x)}{q(x)} + \frac{q(x)}{p(x)} - 1 \end{aligned}

You might recall these estimators from an excellent post by John Schulman. It shows that k_3 in particular is unbiased like k_1 and never negative like k_2, with lower variance.

We can use these functions to estimate KL, but how should we use them to minimize it? Let’s explore how to minimize reverse KL (\min_p\mathrm{KL}[p\,\|\,q]), since it is relevant for reinforcement learning.

Estimating the value of KL #

Before trying to minimize KL, let’s compare the estimators on two Gaussians, p = \mathcal{N}(\mu, 1) and q = \mathcal{N}(0, 1). Here, \mathrm{KL}[p\,\|\,q] is exactly \mu^2/2why?\displaystyle\log\frac{p}{q} = -\frac{(x-\mu)^2}{2} + \frac{x^2}{2} = \mu x - \frac{\mu^2}{2}. Taking the expectation under p, where \mathbb{E}_p[x] = \mu, gives \displaystyle\mathrm{KL}[p\,\|\,q] = \mu\mathbb{E}_p[x] - \frac{\mu^2}{2} = \frac{\mu^2}{2}..

Let’s first examine bias. An estimator is unbiased when its expectation equals the true KL.

k_1 is unbiased by the definition of KL:

\mathbb{E}_p[k_1] = \mathbb{E}_p\!\left[\log\frac{p}{q}\right] = \mathrm{KL}[p\,\|\,q].

k_2 is biased. For these Gaussians,

\mathbb{E}_p[k_2] = \frac12\mathbb{E}_p\!\left[\left(\mu x - \frac{\mu^2}{2}\right)^2\right] = \frac{\mu^2}{2} + \frac{\mu^4}{8} = \mathrm{KL}[p\,\|\,q] + \frac{\mu^4}{8}.

k_3 adds a zero-mean term to k_1, so it stays unbiased:

\begin{aligned} &\mathbb{E}_p\!\left[\frac{q}{p} - 1\right] = \int p\frac{q}{p}\,dx - 1 = 0,\\ \Longrightarrow\quad &\mathbb{E}_p[k_3] = \mathbb{E}_p[k_1] + \underbrace{\mathbb{E}_p\!\left[\frac{q}{p} - 1\right]}_{0} = \mathrm{KL}[p\,\|\,q]. \end{aligned}

p = \mathcal{N}(\mu, 1) · q = \mathcal{N}(0, 1)

Loading interactive figure…

Expected value of each estimator. Hover to see p and q.

As the graph shows, k_1 and k_3 are unbiased, while k_2 overestimates KL. The key to k_3 staying unbiased is that its added term, q/p - 1, is zero in expectation. It can be nonzero for an individual sample, but it does not change the estimator’s mean.

This zero-mean term is a control variate: we add it to an estimator to adjust its variance without changing its expectation. It can cancel noise and decrease variance, or add noise and increase variance. For these Gaussians, k_3 has lower variance near q and higher variance farther away:

p = \mathcal{N}(\mu, 1) · q = \mathcal{N}(0, 1)

Loading interactive figure…

Variance of each estimator, logarithmic scale. Hover to see p and q.
How the control variate changes varianceDerivation

Write c = q/p - 1, so k_3 = k_1 + c. The variance of their sum separates into the original noise, the added noise, and their covariance:

\operatorname{Var}_p(k_3) = \operatorname{Var}_p(k_1) + \operatorname{Var}_p(c) + 2\operatorname{Cov}_p(k_1,c).

For the Gaussians, write a sample as x = \mu + z, where z \sim \mathcal{N}(0,1). Substituting into the log ratio derived above gives

\begin{aligned} k_1 &= \mu x - \frac{\mu^2}{2} = \frac{\mu^2}{2} + \mu z,\\ c &= e^{-\mu^2/2 - \mu z} - 1. \end{aligned}

Since \mathbb{E}[z] = 0 and \operatorname{Var}(z) = 1, \operatorname{Var}_p(k_1) = \mu^2. The Gaussian identity \mathbb{E}[e^{tz}] = e^{t^2/2} gives the added term’s variance:

\operatorname{Var}_p(c) = \mathbb{E}_p[c^2] = e^{-\mu^2}\mathbb{E}[e^{-2\mu z}] - 1 = e^{\mu^2} - 1.

Its covariance with k_1 is negative. Using \mathbb{E}[z e^{tz}] = t e^{t^2/2},

\operatorname{Cov}_p(k_1,c) = \mathbb{E}[\mu z\,c] = \mu e^{-\mu^2/2}\mathbb{E}[z e^{-\mu z}] = -\mu^2.

Putting these together,

\operatorname{Var}_p(k_3) = \underbrace{\mu^2}_{\text{original noise}} + \underbrace{(e^{\mu^2} - 1)}_{\text{added noise}} \underbrace{-\,2\mu^2}_{\text{cancellation}} = e^{\mu^2} - 1 - \mu^2.

For completeness, k_2 = \frac12(\mu^2/2 + \mu z)^2. Using \mathbb{E}[z^3] = 0 and \mathbb{E}[z^4] = 3 gives

\operatorname{Var}_p(k_2) = \frac{\mu^4}{2} + \frac{\mu^6}{4}.

If we weight the control variate by \lambda, the cancellation scales linearly while the added variance scales quadratically:

\operatorname{Var}_p(k_1 + \lambda c) = \mu^2 - 2\lambda\mu^2 + \lambda^2(e^{\mu^2} - 1).

Because the control variate is zero-mean, any multiple of it can be added without biasing the estimator, yielding the family of estimators:

k_\lambda = \log\frac{p}{q} + \lambda\left(\frac{q}{p} - 1\right).

Here, \lambda = 0 gives k_1, and \lambda = 1 gives k_3. We’ll revisit how to choose \lambda.

So choosing the best estimate depends on how far p is from q. If all you want is to estimate KL, k_3 is the best choice near q and k_1 far from it.

The gradient of KL #

In RL, the KL estimate is not the end product. We differentiate it. Using the log derivative trick \nabla p = p\,\nabla\log pwhy?By the chain rule, \displaystyle\nabla\log p = \frac{\nabla p}{p}. Multiplying by p gives \nabla p = p\,\nabla\log p. This lets us rewrite \sum_x \nabla p\,f(x) as \mathbb{E}_p[f(x)\,\nabla\log p]., the gradient of KL is as follows:

\begin{aligned} \nabla\,\mathrm{KL}[p\,\|\,q] &= \nabla \sum_x p \log\frac{p}{q} = \sum_x \nabla p\,\log\frac{p}{q} + \sum_x p\,\nabla \log p\\ &= \mathbb{E}_p\!\left[\log\frac{p}{q}\,\nabla\log p\right] + \mathbb{E}_p\!\left[\nabla\log p\right]\\ &= \mathbb{E}_p\!\left[\Big(\log\frac{p}{q} + 1\Big)\nabla\log p\right]. \end{aligned}

We can drop the second term, \mathbb{E}_p[\nabla\log p], as its expectation is zerowhy?Probabilities always sum to one, so their changes sum to zero: \displaystyle\mathbb{E}_p[\nabla\log p] = \sum_x p\,\frac{\nabla p}{p} = \sum_x \nabla p = \nabla \sum_x p = \nabla 1 = 0.:

\nabla\,\mathrm{KL}[p\,\|\,q] = \mathbb{E}_p\!\left[\log\frac{p}{q}\,\nabla\log p\right].

This tidies up the math. However, notice that \nabla\log p plays the same role for the gradient that \frac{q}{p} - 1 plays for the estimate: a control variate with mean zero.

\nabla\,\mathrm{KL} \equiv k_1 in the reward \equiv k_2 as a loss #

The most common implementations of minimizing KL use one of two mechanisms: adding k_1 to the reward, or k_2 as a surrogate loss.

k_1 in the reward yields the correct gradient. In policy gradient, a sample x with a fixed reward R(x) contributes R(x)\,\nabla\log p. Notice that directly setting R(x) as k_1 yields the correct gradient:

\begin{aligned} &k_1\,\nabla\log p = \log\frac{p}{q}\,\nabla\log p\\ \therefore\ &\mathbb{E}_p[k_1\,\nabla\log p] = \nabla\,\mathrm{KL}[p\,\|\,q]. \end{aligned}

Similarly, using k_2 directly as a loss function also yields the correct gradient:

\begin{aligned} &\nabla k_2 = \nabla\,\frac12\left(\log\frac{p}{q}\right)^2 = \log\frac{p}{q}\,\nabla\!\left(\log p - \log q\right) = \log\frac{p}{q}\,\nabla\log p\\ \therefore\ &\mathbb{E}_p[\nabla k_2] = \nabla\,\mathrm{KL}[p\,\|\,q]. \end{aligned}

\nabla\,\mathrm{KL} \equiv \nabla\mathbb{E}_p[k_\lambda] \equiv scaling the control variate #

Now return to the family k_\lambda = \log\frac{p}{q} + \lambda\left(\frac{q}{p} - 1\right) from the estimation section, where \lambda sets the magnitude of the estimate’s control variate. Since k_\lambda is unbiased, we should be able to show that the gradient of its expectation is the same as the gradient of KL:

\begin{aligned} \nabla\mathbb{E}_p[k_\lambda] &= \nabla \sum_x p\,k_\lambda = \sum_x \nabla p\,k_\lambda + \sum_x p\,\nabla k_\lambda\\ &= \mathbb{E}_p\!\left[k_\lambda\,\nabla\log p + \nabla k_\lambda\right]\\ &= \mathbb{E}_p\Big[\Big(\log\frac{p}{q} + \cancel{\lambda\,\frac{q}{p}} - \lambda\Big)\nabla\log p + \Big(1 - \cancel{\lambda\,\frac{q}{p}}\Big)\nabla\log p\Big]\\ &= \mathbb{E}_p\Big[\log\frac{p}{q}\,\nabla\log p + (1 - \lambda)\,\nabla\log p\Big]. \end{aligned}

The second term can be canceled, as \mathbb{E}_p[ (1 - \lambda)\,\nabla\log p] = 0why?Probabilities always sum to one, so their changes sum to zero: \displaystyle\mathbb{E}_p[\nabla\log p] = \sum_x p\,\frac{\nabla p}{p} = \sum_x \nabla p = \nabla \sum_x p = \nabla 1 = 0.:

\begin{aligned} \nabla\mathbb{E}_p[k_\lambda] &= \mathbb{E}_p[\log\frac{p}{q}\,\nabla\log p + (1 - \lambda)\,\nabla\log p]\\ &= \mathbb{E}_p[\log\frac{p}{q}\,\nabla\log p]\\ &= \nabla\,\mathrm{KL}[p\,\|\,q]\\ \end{aligned}

Notice that again, we’ve found a zero-mean term (1 - \lambda)\,\nabla\log p that does not bias the expectation when added, i.e. a control variate. In k_\lambda it is \lambda\left(\frac{q}{p} - 1\right), but in the \nabla\mathbb{E}_p[k_\lambda] it is (1 - \lambda)\,\nabla\log p. This suggests that choosing \lambda to minimize the variance of KL might not minimize the variance of its gradient.

\nabla\mathbb{E}_p[k_1] (\lambda=0) keeps all of the \nabla\log p term in the gradient, and is the exact same as \nabla\,\mathrm{KL}. Similarly, \nabla\mathbb{E}_p[k_3] (\lambda=1) keeps none of it, and is the exact same as setting k_1 as the reward or k_2 as a loss. All of these are unbiased gradients of KL, but with different variances as a result of adding different magnitudes of the control variate.

In RL language, we are shifting the reward (\log\frac{p}{q}) by a baseline (1-\lambda), the standard tool for reducing a policy gradient’s variance.

The best estimate does not yield the best gradient #

Schulman’s note says that choosing \lambda to minimize the variance of k_\lambda depends on p and q and is hard to calculate analytically. Instead, it uses \lambda = 1, because then the estimate can never be negative.

What if we wanted to choose \lambda optimally? The variance of k_\lambda is quadratic in \lambda, smallest at

\lambda_\text{value} = -\frac{\operatorname{Cov}_p\!\left(\log\frac{p}{q},\ \frac{q}{p}\right)}{\operatorname{Var}_p\!\left(\frac{q}{p}\right)}.

However, in training we usually don’t use the value of KL. We use its gradient. The corresponding per-sample gradient is \big(\log\frac{p}{q} + 1 - \lambda\big)\nabla\log p, where \lambda sets the size of a control variate (1 - \lambda)\,\nabla\log p. The variance of this gradient is smallest at

\lambda_\text{gradient} = 1 + \frac{\mathbb{E}_p\!\left[\log\frac{p}{q}\,\|\nabla\log p\|^2\right]}{\mathbb{E}_p\!\left[\|\nabla\log p\|^2\right]},

Let’s consider the Gaussians again, p = \mathcal{N}(\mu, 1) and q = \mathcal{N}(0, 1).

Taking the gradient taken with respect to \mu, \nabla\log p = x - \mu. Let g_\lambda = \big(\log\frac{p}{q} + 1 - \lambda\big)\nabla\log p for the gradient. Then

\begin{aligned} \operatorname{Var}(k_\lambda) &= \mu^2\,(1 - 2\lambda) + \lambda^2\left(e^{\mu^2} - 1\right)\\ \operatorname{Var}(g_\lambda) &= \left(\frac{\mu^2}{2} + 1 - \lambda\right)^2 + 2\mu^2 \end{aligned}

These variances are smallest at

\lambda_\text{value} = \frac{\mu^2}{e^{\mu^2} - 1} \qquad\text{and}\qquad \lambda_\text{gradient} = 1 + \frac{\mu^2}{2}.
Derive the two variancesDerivation

Write x = \mu + z with z \sim \mathcal{N}(0, 1). Then \log\frac{p}{q} = \frac{\mu^2}{2} + \mu z, \frac{q}{p} = e^{-\mu z - \mu^2/2}, and \nabla_\mu \log p = x - \mu = z.

The estimate. \operatorname{Var}(\log\frac{p}{q}) = \mu^2. From \mathbb{E}[e^{-2\mu z}] = e^{2\mu^2}, \operatorname{Var}(\frac{q}{p}) = e^{\mu^2} - 1. From \mathbb{E}[z\,e^{-\mu z}] = -\mu\,e^{\mu^2/2}, \operatorname{Cov}(\log\frac{p}{q}, \frac{q}{p}) = -\mu^2. So \operatorname{Var}(k_\lambda) = \mu^2 - 2\lambda\mu^2 + \lambda^2(e^{\mu^2} - 1), a quadratic in \lambda with its minimum at \mu^2 / (e^{\mu^2} - 1).

The gradient. Let a = \frac{\mu^2}{2} + 1 - \lambda, so the gradient is (a + \mu z)\,z. Its mean is \mu, the gradient of \mu^2/2. Since \mathbb{E}[z^2] = 1, \mathbb{E}[z^3] = 0 and \mathbb{E}[z^4] = 3, its second moment is a^2 + 3\mu^2, and its variance is a^2 + 2\mu^2, smallest at a = 0.

The two optima move in opposite directions. As p moves away from q, the best estimate slides from k_3 toward k_1, while the best gradient wants a larger and larger baseline. Move the slider to see it.

Loading interactive figure…

Diamonds mark each minimum. Near q, both minima sit at \lambda = 1, which is k_3. Far from q, they are on opposite sides of it.

A simple bandit experiment: optimizing KL with each \lambda #

Does the difference matter in training?

Let’s take a softmax policy over 1,000 actions (i.e. a bandit) and a fixed reference q, and initializing the policy q far from q (\mathrm{KL} = 2.43). We’ll minimize \mathrm{KL}[p\,\|\,q] alone by plain SGD on the logits using policy gradient. Each step samples 16 actions and averages \big(\log\frac{p}{q} + 1 - \lambda\big)\nabla\log p, with \lambda set four ways: \lambda = 0 (k_1 differentiated exactly); \lambda = 1 (k_3); \lambda_\text{value}; and \lambda_\text{gradient}, the last two computed exactly from the current policy. Every choice gives an unbiased gradient, so any difference comes from variance.

Loading interactive figure…

KL and gradient variance are exact at each step. A policy that collapses onto a single action stops moving, because \nabla\log p is then zero for the only action it samples.

Epilogue #

A KL estimator can be used to either estimate KL, or estimate the gradient of KL. Usually, we want the latter, which can be unstable if we mistakenly optimize for lower KL estimate variance instead of lower KL gradient variance.

Practically, this doesn’t change much for the LLM status-quo of using k_1 in the reward or k_2 as a loss, but it is useful to understand the distinction.

Appendix #

Mixing up “the estimator” with “how the estimator enters the gradient” is prevalent despite others pointing out these pitfalls before (Tang and Munos; Liu et al.). This shows up in popular code and reports: open-source RL frameworks, the Composer 2 report, and DeepSeek’s GRPO papers.

Libraries that were wrong: TRL, NeMo-RL, OpenInstructNote

Popular RL libraries computed k_3 for each sampled token and added it to the loss: Hugging Face TRL, NVIDIA NeMo-RL, and AI2 open-instruct. This uses \nabla k_3 instead of \nabla\mathbb{E}_p[k_3], which is wrong.

Let’s see what their implementation was actually optimizing. The gradient of the expectation has two terms, and they kept only one:

\nabla\mathbb{E}_p[k_3] = \mathbb{E}_p\big[\underbrace{k_3\,\nabla\log p}_{\text{dropped}} + \underbrace{\nabla k_3}_{\text{kept}}\big].

The kept term is the gradient of forward KL instead of reverse KL:

\mathbb{E}_p[\nabla k_3] = \mathbb{E}_p\!\left[\Big(1 - \frac{q}{p}\Big)\nabla\log p\right] = \underbrace{\mathbb{E}_p[\nabla\log p]}_{0} - \sum_x q\,\nabla\log p = \nabla\,\mathrm{KL}[q\,\|\,p].

The mistake can be quiet because forward KL is also minimized at p = q, so the penalty still pulls toward the reference. But each sample is weighted by 1 - q/p, which is huge for a token the policy rarely picks but the reference likes.

TRL and NeMo-RL have since fixed their defaults. At the time of writing, open-instruct’s GRPO still uses it by default.

DeepSeek's original mistake corrected in V3.2Note

DeepSeekMath, which introduced GRPO, made the same mistake as the libraries: it added a per-token k_3 to the loss. Appendix A.1.6 writes out the resulting gradient coefficient for each token,

\hat{A}_t + \beta\left(\frac{q}{p} - 1\right),

which is the advantage minus the forward-KL gradient from the previous note. DeepSeek-V3 and DeepSeek-R1 reuse this form.

DeepSeek-V3.2 corrects this mistake by putting k_3 inside the expectation the objective takes over sampled responses, which is correct (Section 3.1):

\begin{gathered} \mathcal{J}_\mathrm{GRPO} = \mathbb{E}_{\{o_i\} \sim p_\mathrm{old}}\!\left[\frac{1}{G}\sum_{i=1}^{G}\frac{1}{|o_i|}\sum_{t=1}^{|o_i|}\min\!\big(r_{i,t}\hat{A}_{i,t},\ \mathrm{clip}(r_{i,t}, 1-\varepsilon, 1+\varepsilon)\,\hat{A}_{i,t}\big) - \beta\,\mathbb{D}_\mathrm{KL}\right],\\[6pt] \mathbb{E}_{p_\mathrm{old}}[\mathbb{D}_\mathrm{KL}] = \mathbb{E}_{p_\mathrm{old}}\!\left[\frac{p}{p_\mathrm{old}}\left(\frac{q}{p} - \log\frac{q}{p} - 1\right)\right] = \mathbb{E}_{p_\mathrm{old}}\!\left[\frac{p}{p_\mathrm{old}}\,k_3\right] = \mathbb{E}_p[k_3]. \end{gathered}
Composer 2's wrong reason for the correct implementationNote

The Composer 2 report (Section 4.1) notes that k_3 is unbiased with low variance when the two policies are close, but its variance grows quickly as they drift apart, so they “use the standard estimator k_1 instead.”

It’s unclear how they use either estimator. However, since k_1 is only correct when it’s used in reward, we can assume they are comparing k_1 in reward with k_3 in reward. k_3 in reward is not a valid choice. With R = k_3, the expected policy gradient is

\begin{aligned} \mathbb{E}_p[k_3\,\nabla\log p] &= \mathbb{E}_p\!\left[\log\frac{p}{q}\,\nabla\log p\right] + \mathbb{E}_p\!\left[\Big(\frac{q}{p} - 1\Big)\nabla\log p\right]\\ &= \nabla\,\mathrm{KL}[p\,\|\,q] + \sum_x q\,\nabla\log p\\ &= \nabla\,\mathrm{KL}[p\,\|\,q] - \nabla\,\mathrm{KL}[q\,\|\,p], \end{aligned}

which is not a divergence and is unbounded below: the policy can lower it forever by moving mass away from actions the reference likes. k_1 in the reward is the right choice, but because its gradient is correct, not because its estimate has lower variance.