KL Divergence

easy
Unit 7 · Safety & Prompting0/3 to milestone

KL divergence measures how different one probability distribution PP is from another QQ:

DKL(P ∥ Q)=∑ipilog⁡piqiD_{KL}(P \,\|\, Q) = \sum_i p_i \log \frac{p_i}{q_i}

It's everywhere in AI engineering: the KL penalty that keeps RLHF-tuned models close to the base model, distillation losses, and comparing a fine-tuned model's token distribution with the original's.

Implement kl_divergence(p, q) using the natural log.

Rules

  • Terms where pi=0p_i = 0 contribute 0, even if qi=0q_i = 0.
  • If some pi>0p_i > 0 where qi=0q_i = 0, the divergence is infinite: return float("inf").
  • Inputs are probability vectors (non-negative, summing to 1).

Note that KL is not symmetric: DKL(P∥Q)≠DKL(Q∥P)D_{KL}(P\|Q) \ne D_{KL}(Q\|P) in general.

#probability#llm#numpy3 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
KL Divergence · TechGradify