v9.1.1
Menu

KL Divergence Penalty

easyFREEPreference OptimizationLLM 2: Training & Alignment

Compute the KL divergence between two discrete probability distributions.

DKL(P∥Q)=∑iP(i)log⁡P(i)Q(i)D_{KL}(P \| Q) = \sum_i P(i) \log \frac{P(i)}{Q(i)}

Here log⁡\log is the natural logarithm. This is used in RLHF to penalize the policy from deviating too far from the reference model.

Input:

  • P: a 1D NumPy array of floats (distribution P)
  • Q: a 1D NumPy array of floats (distribution Q), same length as P

Output: the KL divergence as a single float. The tests round it to 4 decimal places.

Example

Input
0.5 0.5
0.5 0.5
Output
0.0
Reasoning
  • P and Q are two probability distributions over the same 2 outcomes: P=(0.5,0.5)P = (0.5, 0.5) is the policy and Q=(0.5,0.5)Q = (0.5, 0.5) is the reference model. Each entry is the probability of one outcome, and each sums to 1.
  • Outcome ii contributes P(i)ln⁡P(i)Q(i)P(i) \ln \frac{P(i)}{Q(i)}: the log of how much more likely PP makes that outcome than QQ does, weighted by how often PP actually picks it.
  • Here both ratios are 0.50.5=1\frac{0.5}{0.5} = 1 and ln⁡1=0\ln 1 = 0, so each term is 0.5⋅0=00.5 \cdot 0 = 0 and the total is 00, shown as 0.0.
  • Notice that the divergence is zero exactly when the two distributions agree on every outcome: a policy that has not moved from the reference pays no penalty.
  • For contrast, P=(0.9,0.1)P = (0.9, 0.1) against the same QQ gives 0.9ln⁡1.8≈0.52900.9 \ln 1.8 \approx 0.5290 and 0.1ln⁡0.2≈−0.16090.1 \ln 0.2 \approx -0.1609. One term is negative, yet the total 0.36810.3681 is positive; KL divergence is never below zero. Swapping the roles of PP and QQ gives 0.51080.5108, so it is not symmetric.

Constraints

  • P and Q are valid probability distributions (sum to 1, all positive)
  • Same length
  • Round to 4 decimal places

Learn this in

More from LLM 2: Training & Alignment

solution.py

Test results

Sign in to run your code against the test cases.