Estimate KL divergence from samples three ways
Why it matters PPO and GRPO trainers log these KL estimators every step to keep the policy near the reference.
RLHF code estimates KL(pi || ref) from sampled tokens. With r = ref_logprob - pi_logprob for samples drawn from pi, three common estimators are k1 = -r, k2 = r^2 / 2 and k3 = (exp(r) - 1) - r.
Write kl_estimators(pi_logp, ref_logp). Return (k1, k2, k3), each the mean over samples.
def kl_estimators(pi_logp, ref_logp)Example
if the log-probs are equal, all three are 0.
Understand the idea
In RLHF you keep the policy close to a reference model by penalising KL(pi || ref). You cannot sum over every possible sequence, so you estimate it from samples drawn from pi. Let r = ref_logprob - pi_logprob for each sample. Three estimators are common: k1 = -r (unbiased but can be negative), k2 = r^2 / 2 (always positive, slightly biased, low variance), and k3 = (e^r - 1) - r (unbiased and never negative). Worked example: pi_logp [-1, -2], ref_logp [-1.5, -1.5], so r = [-0.5, 0.5]. k1 = mean(0.5, -0.5) = 0, even though the two models differ. k2 = mean(0.125, 0.125) = 0.125. k3: e^-0.5 - 1 + 0.5 = 0.1065 and e^0.5 - 1 - 0.5 = 0.1487, mean about 0.128. Rule: r = ref_logp - pi_logp; return the means of -r, r^2 / 2 and exp(r) - 1 - r. Watch the sign of r: it is ref minus pi, and k3 subtracts r. Used in: PPO and GRPO training of LLMs, where these estimators form the KL penalty or loss term.