BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Alignment3 of 18 in topic

521. Estimate KL divergence from samples three ways

EasyAlignment

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.

Functiondef 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).

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.

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.

Topics
Alignment
Similar questions
  • Train a reward model with the Bradley-Terry lossEasy
  • Score a reward model by pairwise preference accuracyEasy
  • Compute the IPO preference lossEasy
  • Add label smoothing to the DPO loss (conservative DPO)Easy
All Alignment problems
Report
521 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def kl_estimators(pi_logp, ref_logp):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 3 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS