Compare two token distributions with Jensen-Shannon divergence

KL divergence is not symmetric and blows up when one distribution has a zero. Jensen-Shannon fixes both and is a common drift and diversity score.

Write js_divergence(p, q) for two 1D non-negative arrays that each sum to 1. With m = (p + q) / 2, return 0.5 KL(p || m) + 0.5 KL(q || m) in nats. Terms where the first distribution is 0 contribute 0.

Signaturedef js_divergence(p, q)

Example

js_divergence([1, 0], [0, 1]) is log 2.

Understand the idea

KL divergence measures how one distribution differs from another, but it is not symmetric and becomes infinite when the second distribution has a zero where the first does not. Jensen-Shannon divergence fixes both: compare each distribution to their average m, which is never zero where either one is positive, and average the two KLs. The result is symmetric and at most ln 2. Worked example: p = [0.5, 0.5], q = [1, 0]. m = [0.75, 0.25]. KL(p || m) = 0.5 * ln(0.5 / 0.75) + 0.5 * ln(0.5 / 0.25) = -0.2027 + 0.3466 = 0.1438. KL(q || m) = 1 * ln(1 / 0.75) = 0.2877, and the zero term adds nothing. JS = 0.5 * 0.1438 + 0.5 * 0.2877 = 0.2158 nats. Completely different distributions such as [1, 0] and [0, 1] give ln 2 = 0.6931. Rule: m = (p + q) / 2; JS = 0.5 * KL(p || m) + 0.5 * KL(q || m), with KL(a || b) = sum of a * ln(a / b) over entries where a > 0. Used to measure drift between token distributions and diversity of generated text.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplejs_divergence([1, 0], [0, 1])
  • Sample 2: identicaljs_divergence([0.2, 0.8], [0.2, 0.8])
  • Test 3: randomjs_divergence([0.1, 0.4, 0.5], [0.3, 0.3, 0.4])