521. 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 1
if the log-probs are equal, all three are 0.
Example 2
Input: pi_logp = [-1, -2], ref_logp = [-1, -2]
Output: (0.0, 0.0, 0.0)
Example 3
Input: pi_logp = [-0.5, -1.0, -2.0], ref_logp = [-0.7, -0.9, -2.5]
Output: (0.2, 0.05, 0.043477)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
r = ref - pi, elementwise.
Hint 2
r = ref_logp - pi_logp.
Hint 3
Use np.expm1 for exp(r) - 1.
Common mistakes
- Swapping the sign of r.
- Adding instead of subtracting r in k3.
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).
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.
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.