Module contents
Lesson 16 of 19Advanced 110 min

Method of types, Sanov's theorem and hypothesis testing

Connect information theory to classical statistics with the method of types: count sequences of a given composition and bound their probabilities. Derive Sanov's theorem, Chernoff–Stein's lemma, and the local Fisher-information approximation to KL divergence.

After this lesson you can

  • Bound the number of types and the probability of a type class using KL divergence.
  • Prove Sanov's theorem for closed convex sets and identify the limiting conditional distribution as an I-projection.
  • Prove the Chernoff–Stein lemma and compute error exponents for concrete tests.
  • Derive D(p_θ‖p_{θ+δ}) ≈ (1/2) δᵀ I(θ) δ and relate it to the Cramér–Rao bound and the natural gradient.
  • Estimate rare-event probabilities by exponentially tilted importance sampling.

Before you start

Motivation: how unlikely is what I am seeing?

You flip a coin you believe is fair 1,000 times and get 700 heads. How unlikely is that? Elementary probability tools give answers that differ by 35 orders of magnitude:

MethodBound or value of P(heads≥700)\Pr(\text{heads} \ge 700)
Chebyshev, Var⁡/t2=250/2002\Var/t^2 = 250/200^26.3×10−36.3 \times 10^{-3}
Hoeffding, e−2nt2e^{-2n t^2} with t=0.2t = 0.21.8×10−351.8 \times 10^{-35}
Sanov, 2−nKL⁡(P∗ ∥ Q)2^{-n\KL(P^*\,\|\,Q)}1.8×10−361.8 \times 10^{-36}
Exact value (binomial sum)8.8×10−388.8 \times 10^{-38}

Chebyshev is useless: atypical events for a sum of independent variables decay exponentially, not as a power of nn. Hoeffding gets the scale right but misses the exponent. The third row, the subject of this lesson, gives the exact exponent: the true value is 2−nD∗2^{-n D^*} times a factor that decays only as 1/n1/\sqrt{n}. That exponent D∗D^* is a Kullback–Leibler divergence.

The same question appears in disguise in many places:

  • Tests and anomalies. A fraud detector sees a burst of transactions with an unusual composition. Is it noise or an attack? The quantitative answer is the probability, under the normal model, of an empirical frequency that extreme.
  • Overly good backtests. A strategy with no actual edge and Gaussian daily returns achieves an annualized Sharpe of 2 in one year (252 sessions) with probability P(Z≥2)=0.023\Pr(Z \ge 2) = 0.023. If you have tried 100 strategies, the chance that one achieves it is 0.900.90. The deflated Sharpe ratio corrects exactly this.
  • Deciding quickly. You have two models of a system and observe data. How many observations are needed to distinguish them with errors below 10−610^{-6}? The answer has the form n≈log⁡(1/β)/KL⁡(P0 ∥ P1)n \approx \log(1/\beta)/\KL(P_0\,\|\,P_1), which is why KL can be read as a decision speed.

One idea underlies all three, the method of types: classify the ∣X∣n\abs{\mathcal{X}}^n possible sequences by composition (how often each symbol appears), observe that there are very few compositions, and that the probability of each depends only on a KL divergence. This yields Sanov’s theorem (the cost of a rare event), the conditional limit theorem (how it occurs), the Chernoff–Stein lemma (how quickly two hypotheses can be distinguished) and, by looking closely at KL, Fisher information. This lesson thus connects Kullback–Leibler divergence to classical statistical hypothesis testing.

Types and type classes

Work with a finite alphabet X\mathcal{X} of m=∣X∣m = \abs{\mathcal{X}} symbols and sequences xn=(x1,…,xn)∈Xnx^n = (x_1, \dots, x_n) \in \mathcal{X}^n. Write N(a∣xn)N(a \given x^n) for the number of times symbol aa appears in xnx^n.

With X={1,2,3}\mathcal{X} = \{1, 2, 3\} and x5=1 3 1 2 1x^5 = 1\,3\,1\,2\,1, the type is P=(3/5,1/5,1/5)P = (3/5, 1/5, 1/5) and T(P)T(P) contains every rearrangement of the sequence: ∣T(P)∣=5!3! 1! 1!=20\abs{T(P)} = \frac{5!}{3!\,1!\,1!} = 20. In general, ∣T(P)∣\abs{T(P)} is the multinomial coefficient (nnP(1),…,nP(m))\binom{n}{nP(1), \dots, nP(m)}.

There are few types, because a type is determined by mm counts between 00 and nn:

The equality is the classical count of nonnegative integer solutions of k1+⋯+km=nk_1 + \dots + k_m = n (stars and bars); the bound follows because each of the mm counts has at most n+1n + 1 values. The contrast matters: there are mnm^n sequences, exponentially many, but only polynomially many types. So some type class must be exponentially large, and any sum over types behaves like its largest term up to a polynomial factor. That is the whole strategy.

A sequence’s probability depends only on its type

If X1,…,Xn∼iidQX_1, \dots, X_n \iid Q, the probability of a particular sequence is Qn(xn)=∏iQ(xi)Q^n(x^n) = \prod_i Q(x_i). Grouping equal factors:

Proof
Qn(xn)=∏a∈XQ(a)N(a∣xn)=∏aQ(a)nP(a)=2 n∑aP(a)log⁡2Q(a).Q^n(x^n) = \prod_{a \in \mathcal{X}} Q(a)^{N(a \given x^n)} = \prod_a Q(a)^{nP(a)} = 2^{\,n\sum_a P(a)\log_2 Q(a)}.

And −∑aP(a)log⁡2Q(a)=∑aP(a)log⁡21P(a)+∑aP(a)log⁡2P(a)Q(a)=H⁡(P)+KL⁡(P ∥ Q)-\sum_a P(a)\log_2 Q(a) = \sum_a P(a)\log_2\frac{1}{P(a)} + \sum_a P(a)\log_2\frac{P(a)}{Q(a)} = \Ent(P) + \KL(P\,\|\,Q), the cross-entropy decomposition. If Q(a)=0Q(a) = 0 for some aa with P(a)>0P(a) > 0, both sides are zero (KL is infinite).

∎

Notice what this says: a sequence’s probability depends neither on the order of its symbols nor on anything except its type, and the dependence uses two quantities from lessons 1 and 2. Entropy measures how many sequences the class contains; KL measures the penalty for each being unlike QQ.

The size of a type class

The upper bound takes one line: by the previous theorem with Q=PQ = P, 1≥Pn(T(P))=∣T(P)∣ 2−nH⁡(P)1 \ge P^n(T(P)) = \abs{T(P)}\, 2^{-n\Ent(P)}. The lower bound needs a lemma of independent interest: the most probable type class under PP is that of PP.

Proof

Use the inequality r!s!≥s r−s\frac{r!}{s!} \ge s^{\,r - s} for integers r,s≥0r, s \ge 0: if r≥sr \ge s, the quotient is the product of r−sr - s factors greater than ss; if r<sr < s, it is the reciprocal of a product of s−rs - r factors at most ss. With ka=nP(a)k_a = nP(a) and k^a=nP^(a)\hat k_a = n\hat P(a),

Pn(T(P))Pn(T(P^))=∣T(P)∣∏aP(a)ka∣T(P^)∣∏aP(a)k^a=∏ak^a!ka! P(a)ka−k^a≥∏akak^a−ka P(a)ka−k^a=∏ank^a−ka=n n−n=1,\frac{P^n(T(P))}{P^n(T(\hat P))} = \frac{\abs{T(P)} \prod_a P(a)^{k_a}}{\abs{T(\hat P)} \prod_a P(a)^{\hat k_a}} = \prod_a \frac{\hat k_a!}{k_a!}\, P(a)^{k_a - \hat k_a} \ge \prod_a k_a^{\hat k_a - k_a}\, P(a)^{k_a - \hat k_a} = \prod_a n^{\hat k_a - k_a} = n^{\,n - n} = 1,

because ka=nP(a)k_a = nP(a). If P(a)=0P(a) = 0 for an aa with P^(a)>0\hat P(a) > 0, the denominator is zero and there is nothing to prove.

∎

With the lemma, the lower size bound follows by summing the ∣Pn∣\abs{\mathcal{P}_n} classes: 1=∑P^Pn(T(P^))≤∣Pn∣ Pn(T(P))1 = \sum_{\hat P} P^n(T(\hat P)) \le \abs{\mathcal{P}_n}\, P^n(T(P)), so Pn(T(P))≥(n+1)−mP^n(T(P)) \ge (n+1)^{-m} and ∣T(P)∣=Pn(T(P)) 2nH⁡(P)≥(n+1)−m2nH⁡(P)\abs{T(P)} = P^n(T(P))\, 2^{n\Ent(P)} \ge (n+1)^{-m}2^{n\Ent(P)}. This is the exact, nonasymptotic version of what Stirling’s formula gives for the multinomial coefficient.

Probability of a type class

Combining the two previous theorems, the probability of a whole class is its size times its sequences’ common probability, and entropy cancels:

You will complete the proof in the first guided exercise. This is the lesson’s central result: the probability of observing composition PP when data come from QQ is 2−nKL⁡(P ∥ Q)2^{-n\KL(P\,\|\,Q)}, up to a polynomial factor. To express this “up to a polynomial factor” conveniently, use first-order equality in the exponent:

an≐bn⟺lim⁡n→∞1nlog⁡2anbn=0,a_n \doteq b_n \quad\Longleftrightarrow\quad \lim_{n \to \infty} \frac1n \log_2 \frac{a_n}{b_n} = 0,

so the theorem becomes Qn(T(P))≐2−nKL⁡(P ∥ Q)Q^n(T(P)) \doteq 2^{-n\KL(P\,\|\,Q)} and ∣T(P)∣≐2nH⁡(P)\abs{T(P)} \doteq 2^{n\Ent(P)}.

The interactive shows the type grid for a three-symbol alphabet: each type is a point in the triangle of distributions, the simplex, and the grid becomes finer as nn grows.

InteractiveType classes in the simplex
symbol 1symbol 2symbol 3
KL⁡(P ∥ Q)\KL(P\,\|\,Q) bands and point colors, in bits:0.052.5 or more
10
Color of each type
Type PP(2, 3, 5)/10
Types, bound (n+1)3(n+1)^366 ≤ 1331
log⁡2∣T(P)∣\log_2\abs{T(P)}, nH⁡(P)n\Ent(P)11.30 ≤ 14.85
Qn(T(P))Q^n(T(P))0.00544
Upper bound 2−nKL⁡2^{-n\KL}0.064
Lower bound 2−nKL⁡(n+1)3\frac{2^{-n\KL}}{(n+1)^{3}}4.8·10⁻⁵
−1nlog⁡2Qn(T(P))-\tfrac1n\log_2 Q^n(T(P))0.752 bits
KL⁡(P ∥ Q)\KL(P\,\|\,Q)0.397 bits
Difference0.356 bits
Mass with KL⁡≤0.05\KL \le 0.050.276
With n=10n = 10 many points are one or more color steps ahead of their band: the empirical exponent exceeds KL⁡(P ∥ Q)\KL(P\,\|\,Q) by up to 3nlog⁡2(n+1)\tfrac{3}{n}\log_2(n+1) bits. Increase nn.
Each point is a type P∈PnP \in \mathcal{P}_n of the alphabet {1,2,3}\{1, 2, 3\}, colored by its empirical exponent −1nlog⁡2Qn(T(P))-\tfrac1n\log_2 Q^n(T(P)) on the same scale as the background bands, which are levels of KL⁡(P ∥ Q)\KL(P\,\|\,Q). With n=10n = 10 many points are one or more steps ahead of their band: the polynomial factor adds up to 3nlog⁡2(n+1)\tfrac3n\log_2(n+1) bits. Raise nn to 60 and watch each point merge with its band until only its border is visible. Then switch to «Masa»: each point's area is Qn(T(P))Q^n(T(P)) and almost all probability lies near QQ in a region shrinking with nn. Drag type PP and compare its class's exact probability with the two bounds in the readings.

The «Masa» mode is the law of large numbers viewed through types, at exponential speed. For any ε>0\eps > 0,

Qn(KL⁡(PXn ∥ Q)>ε)=∑P∈Pn: KL⁡(P ∥ Q)>εQn(T(P))≤(n+1)m 2−nε,Q^n\big(\KL(P_{X^n}\,\|\,Q) > \eps\big) = \sum_{P \in \mathcal{P}_n:\ \KL(P\,\|\,Q) > \eps} Q^n(T(P)) \le (n+1)^m\, 2^{-n\eps},

a series summable in nn. By the Borel–Cantelli lemma, KL⁡(PXn ∥ Q)→0\KL(P_{X^n}\,\|\,Q) \to 0 almost surely, and hence PXn→QP_{X^n} \to Q. This is a quantitative version of asymptotic equipartition: sequences whose type is near QQ are in the typical set, since for them −1nlog⁡2Qn(xn)=H⁡(Pxn)+KL⁡(Pxn ∥ Q)≈H⁡(Q)-\tfrac1n\log_2 Q^n(x^n) = \Ent(P_{x^n}) + \KL(P_{x^n}\,\|\,Q) \approx \Ent(Q).

Sanov’s theorem

Now return to the motivating question. Let EE be a set of distributions on X\mathcal{X}, for example “the frequency of heads is at least 0.7”. We want the probability that the sample type lies in EE, written Qn(E)=P(PXn∈E)=∑P∈E∩PnQn(T(P))Q^n(E) = \Pr(P_{X^n} \in E) = \sum_{P \in E \cap \mathcal{P}_n} Q^n(T(P)). Since the sum has polynomially many terms, its largest term dominates, and that is the type in EE with smallest KL divergence.

Proof

Upper bound. Qn(E)=∑P∈E∩PnQn(T(P))≤∑P∈E∩Pn2−nKL⁡(P ∥ Q)≤∣Pn∣ 2−ninf⁡P∈EKL⁡(P ∥ Q)Q^n(E) = \sum_{P \in E \cap \mathcal{P}_n} Q^n(T(P)) \le \sum_{P \in E \cap \mathcal{P}_n} 2^{-n\KL(P\,\|\,Q)} \le \abs{\mathcal{P}_n}\, 2^{-n\inf_{P \in E}\KL(P\,\|\,Q)}, and ∣Pn∣≤(n+1)m\abs{\mathcal{P}_n} \le (n+1)^m.

Lower bound. Since QQ has full support, P↦KL⁡(P ∥ Q)P \mapsto \KL(P\,\|\,Q) is continuous on the entire simplex. Given η>0\eta > 0, because EE is the closure of its interior there is a PP in the interior of EE with KL⁡(P ∥ Q)≤KL⁡(P∗ ∥ Q)+η\KL(P\,\|\,Q) \le \KL(P^*\,\|\,Q) + \eta. Rounding nPnP yields a type Pn∈PnP_n \in \mathcal{P}_n with max⁡a∣Pn(a)−P(a)∣≤m/n\max_a\abs{P_n(a) - P(a)} \le m/n; for large nn, PnP_n lies in a ball around PP contained in EE, and KL⁡(Pn ∥ Q)→KL⁡(P ∥ Q)\KL(P_n\,\|\,Q) \to \KL(P\,\|\,Q) by continuity. Then

Qn(E)≥Qn(T(Pn))≥(n+1)−m 2−nKL⁡(Pn ∥ Q),Q^n(E) \ge Q^n(T(P_n)) \ge (n+1)^{-m}\, 2^{-n\KL(P_n\,\|\,Q)},

whence lim inf⁡n1nlog⁡2Qn(E)≥−KL⁡(P ∥ Q)≥−KL⁡(P∗ ∥ Q)−η\liminf_n \frac1n\log_2 Q^n(E) \ge -\KL(P\,\|\,Q) \ge -\KL(P^*\,\|\,Q) - \eta. Since η\eta is arbitrary and the upper bound gives lim sup⁡n1nlog⁡2Qn(E)≤−KL⁡(P∗ ∥ Q)\limsup_n \frac1n\log_2 Q^n(E) \le -\KL(P^*\,\|\,Q), the limit exists and equals −KL⁡(P∗ ∥ Q)-\KL(P^*\,\|\,Q).

∎

Sanov’s theorem says that the probability of a rare event involving the empirical distribution is set by the event’s least costly point, measured by KL: Qn(E)≐2−nKL⁡(P∗ ∥ Q)Q^n(E) \doteq 2^{-n\KL(P^*\,\|\,Q)}. All other points in EE are exponentially less probable than the best and do not count. This is a large deviations result: the law of large numbers says PXn→QP_{X^n} \to Q; Sanov quantifies the price of a fixed deviation.

The regularity assumption on EE is not an empty technicality. If EE is, for instance, {P:P(1)=1/2}\{P : P(1) = 1/\sqrt{2}\}, no type lies in EE (types have rational coordinates) and Qn(E)=0Q^n(E) = 0 for every nn, even though the infimum of KL over EE is finite.

Events involving a mean: exponential tilting

The most important case is a constraint on the empirical mean of a function g:X→Rg : \mathcal{X} \to \R: E={P:EP[g]≥α}E = \{P : \E_P[g] \ge \alpha\}, with α>EQ[g]\alpha > \E_Q[g] so that the event is rare. Since 1n∑ig(Xi)=EPXn[g]\frac1n\sum_i g(X_i) = \E_{P_{X^n}}[g], this is the event “the sample mean of gg is at least α\alpha”. In the simplex, EE is a half-space. The KL minimum over it can be calculated explicitly.

Proof

The mean λ↦EQλ[g]=Λ′(λ)\lambda \mapsto \E_{Q_\lambda}[g] = \Lambda'(\lambda) is continuous and strictly increasing, because Λ′′(λ)=Var⁡Qλ[g]>0\Lambda''(\lambda) = \Var_{Q_\lambda}[g] > 0 if gg is not constant; it equals EQ[g]\E_Q[g] at λ=0\lambda = 0 and tends to max⁡g\max g as λ→∞\lambda \to \infty, so λ∗\lambda^* exists and is unique. For any P∈EP \in E and λ≥0\lambda \ge 0,

KL⁡(P ∥ Q)−KL⁡(P ∥ Qλ)=∑aP(a)ln⁡Qλ(a)Q(a)=λ EP[g]−Λ(λ)≥λα−Λ(λ).\KL(P\,\|\,Q) - \KL(P\,\|\,Q_\lambda) = \sum_a P(a)\ln\frac{Q_\lambda(a)}{Q(a)} = \lambda\,\E_P[g] - \Lambda(\lambda) \ge \lambda\alpha - \Lambda(\lambda).

Since KL⁡(P ∥ Qλ)≥0\KL(P\,\|\,Q_\lambda) \ge 0, we have KL⁡(P ∥ Q)≥λα−Λ(λ)\KL(P\,\|\,Q) \ge \lambda\alpha - \Lambda(\lambda) for every λ≥0\lambda \ge 0. With λ=λ∗\lambda = \lambda^* and P=Qλ∗P = Q_{\lambda^*}, which belongs to EE, both inequalities are equalities. Finally, λα−Λ(λ)\lambda\alpha - \Lambda(\lambda) is concave in λ\lambda and its derivative α−Λ′(λ)\alpha - \Lambda'(\lambda) vanishes at λ∗\lambda^*, which is therefore its maximum.

∎

The expression sup⁡λ(λα−Λ(λ))\sup_\lambda(\lambda\alpha - \Lambda(\lambda)) is Cramér’s rate function, the Legendre transform of the cumulant generating function, familiar from the Chernoff method. Thus the Chernoff bound is Sanov’s theorem applied to a half-space: Chernoff considers only the mean, Sanov the entire empirical distribution, and in the mean case their exponents agree (Cramér’s theorem). For the motivating coin, g(a)=1[a=head]g(a) = \ind[a = \text{head}], α=0.7\alpha = 0.7, and tilting the fair coin to mean 0.70.7 gives the coin (0.7,0.3)(0.7, 0.3), with λ∗=ln⁡(7/3)=0.847\lambda^* = \ln(7/3) = 0.847 and KL⁡(P∗ ∥ Q)=1−h2(0.7)=0.1187\KL(P^*\,\|\,Q) = 1 - h_2(0.7) = 0.1187 bits.

InteractiveSanov: the cheapest way for the unlikely to happen
face 1face 2face 3
  • event EE and its boundary
  • contour KL⁡(P ∥ Q)=D∗\KL(P\,\|\,Q) = D^*
  • types in EE, area ∝ conditional probability
  • conditional mean P(X1=⋅∣E)\Pr(X_1 = \cdot \mid E) (hollow circle)
Event probability versus n (log scale)
2.30
40
Plot
Event EEmean of g ≥ 2.30, g = (1, 2, 3)
QQ and its mean(0.500, 0.300, 0.200), 1.700
P∗P^* (I-projection)(0.200, 0.300, 0.500)
D∗=KL⁡(P∗ ∥ Q)D^* = \KL(P^*\,\|\,Q)0.3966 bits
Tilt λ\lambda0.916 nats
Qn(E)Q^n(E) with n=40n = 402.2·10⁻⁶
−1nlog⁡2Qn(E)-\tfrac1n\log_2 Q^n(E) versus D∗D^*0.4699 versus 0.3966
Exact P(X1=⋅∣E)\Pr(X_1 = \cdot \mid E)(0.192, 0.302, 0.507)
The highest-weight types in EE (magenta dots) cluster near P∗P^*: if the event occurs, it almost certainly occurs “in the manner of P∗P^*”. Naive Monte Carlo last sees the event at n=20n = 20 and estimates 0 thereafter.
The triangle is the simplex of a three-sided die with distribution QQ (orange, draggable). The magenta region is the event EE: the mean face, or the frequency of face 3, is at least α\alpha. Thin curves are levels of KL⁡(P ∥ Q)\KL(P\,\|\,Q) and the thick curve is level D∗D^* touching EE exactly at the I-projection P∗P^*. Magenta points are the types in EE for the chosen nn, with area proportional to their probability conditional on EE; the hollow circle is their mean. The plot shows the exact probability of EE (sum over type classes), the bound 2−nD∗2^{-nD^*}, and naive Monte Carlo with 1,000 samples, which disappears when the event is too rare. Raise α\alpha, switch to «Exponente» and see how slowly −1nlog⁡2Qn(E)-\tfrac1n\log_2 Q^n(E) approaches D∗D^*. Increase nn for the cloud: where does the conditional mean go?

Two features of the figure deserve attention. First, the exact curve always stays below 2−nD∗2^{-nD^*}, as guaranteed by the preceding note, and the gap on a logarithmic scale grows slowly: this is the Θ(1/n)\Theta(1/\sqrt{n}) factor. For the coin, the refined calculation of Bahadur and Rao gives, for integer 0.7n0.7n, P(heads≥0.7n)∼2−nD∗/((1−e−λ∗) σ∗2πn)\Pr(\text{heads} \ge 0.7n) \sim 2^{-nD^*}/\big((1 - e^{-\lambda^*})\,\sigma^*\sqrt{2\pi n}\big), with σ∗2=0.21\sigma^{*2} = 0.21 the variance under the tilted coin; you will check it numerically in the cells. Second, the cloud: probability conditional on EE is not spread over the whole event but concentrates near P∗P^*. This has its own name.

The conditional limit theorem

If you are told the rare event occurred, what do the data look like? The answer is surprisingly rigid: they look like P∗P^*.

Proof

Let D∗=KL⁡(P∗ ∥ Q)D^* = \KL(P^*\,\|\,Q) and δ>0\delta > 0. Split EE into cheap types A={P∈E:KL⁡(P ∥ Q)≤D∗+δ}A = \{P \in E : \KL(P\,\|\,Q) \le D^* + \delta\} and expensive ones B={P∈E:KL⁡(P ∥ Q)≥D∗+2δ}B = \{P \in E : \KL(P\,\|\,Q) \ge D^* + 2\delta\}. Sanov’s upper bound applied to BB gives Qn(B)≤(n+1)m2−n(D∗+2δ)Q^n(B) \le (n+1)^m 2^{-n(D^* + 2\delta)}. Since EE is convex with nonempty interior, AA contains an open set (interior points of EE near P∗P^*), and as in Sanov’s proof there are types Pn∈AP_n \in A for large nn, with Qn(A)≥(n+1)−m2−n(D∗+δ)Q^n(A) \ge (n+1)^{-m}2^{-n(D^* + \delta)}. Then

P(PXn∈B∣PXn∈E)≤Qn(B)Qn(A)≤(n+1)2m 2−nδ→0.\Pr(P_{X^n} \in B \given P_{X^n} \in E) \le \frac{Q^n(B)}{Q^n(A)} \le (n+1)^{2m}\, 2^{-n\delta} \to 0.

Outside BB, the Pythagorean inequality gives KL⁡(P ∥ P∗)≤KL⁡(P ∥ Q)−D∗<2δ\KL(P\,\|\,P^*) \le \KL(P\,\|\,Q) - D^* < 2\delta, and by Pinsker’s inequality the type is within total variation distance δln⁡2\sqrt{\delta \ln 2} of P∗P^* (with KL in bits). This proves convergence in probability of the type. For the marginal, the event {PXn∈E}\{P_{X^n} \in E\} is unchanged by permuting the sequence, so P(Xi=a∣E)\Pr(X_i = a \given E) is the same for every ii, and averaging over ii,

P(X1=a∣E)=1n∑i=1nP(Xi=a∣E)=E[PXn(a)∣E]→P∗(a),\Pr(X_1 = a \given E) = \frac1n\sum_{i=1}^n \Pr(X_i = a \given E) = \E\big[P_{X^n}(a) \given E\big] \to P^*(a),

because PXn(a)P_{X^n}(a) is bounded and converges in probability to P∗(a)P^*(a) under the conditional distribution.

∎

The same argument, with a little more work, proves that (X1,…,Xk)(X_1, \dots, X_k) conditional on EE converge to kk independent copies of P∗P^* for each fixed kk. For the fair die with mean at least 4, tilting gives P∗∝e0.1746 aP^* \propto e^{0.1746\,a}, that is, P∗=(0.103,0.123,0.146,0.174,0.207,0.247)P^* = (0.103, 0.123, 0.146, 0.174, 0.207, 0.247), and the cells will check that the exact distribution of the first roll conditional on Xˉ200≥4\bar X_{200} \ge 4 is (0.100,0.121,0.145,0.174,0.209,0.251)(0.100, 0.121, 0.145, 0.174, 0.209, 0.251). Rolls do not concentrate on {4,5,6}\{4, 5, 6\} or become uniform above 4: all faces shift slightly, in the cheapest possible way.

Hypothesis testing: KL as decision speed

We observe X1,…,Xn∼iidQX_1, \dots, X_n \iid Q and want to decide between H0:Q=P0H_0: Q = P_0 and H1:Q=P1H_1: Q = P_1. A test is an acceptance region An⊆XnA_n \subseteq \mathcal{X}^n (accept H0H_0 if xn∈Anx^n \in A_n), with the two errors

αn=P0n(Anc)(type I),βn=P1n(An)(type II).\alpha_n = P_0^n(A_n^c) \quad\text{(type I)}, \qquad \beta_n = P_1^n(A_n) \quad\text{(type II)}.

The Neyman–Pearson lemma says that, for a given level αn\alpha_n, the test minimizing βn\beta_n accepts H0H_0 when the likelihood ratio P0n(xn)/P1n(xn)P_0^n(x^n)/P_1^n(x^n) exceeds a threshold (randomizing at the boundary if needed). The method of types rewrites that ratio in a revealing way. By the sequence probability theorem, log⁡2Pkn(xn)=−n(H⁡(Pxn)+KL⁡(Pxn ∥ Pk))\log_2 P_k^n(x^n) = -n(\Ent(P_{x^n}) + \KL(P_{x^n}\,\|\,P_k)), and subtraction cancels entropy:

1nlog⁡2P0n(xn)P1n(xn)=KL⁡(Pxn ∥ P1)−KL⁡(Pxn ∥ P0).\frac1n\log_2\frac{P_0^n(x^n)}{P_1^n(x^n)} = \KL(P_{x^n}\,\|\,P_1) - \KL(P_{x^n}\,\|\,P_0).

The Neyman–Pearson test accepts H0H_0 when the sample type is sufficiently closer to P0P_0 than to P1P_1, with KL measuring closeness. Since the difference is ∑aPxn(a)log⁡2P0(a)P1(a)\sum_a P_{x^n}(a)\log_2\frac{P_0(a)}{P_1(a)}, linear in the type, the decision boundary is a hyperplane of the simplex: the acceptance region is a half-space, as with the events in the previous section.

The Chernoff–Stein lemma

Fix the type I error below ε∈(0,1)\eps \in (0, 1) and ask how quickly type II error can fall. Write βnε=min⁡{P1n(An):An⊆Xn, αn≤ε}\beta_n^\eps = \min\{P_1^n(A_n) : A_n \subseteq \mathcal{X}^n,\ \alpha_n \le \eps\} for the best possible type II error with nn observations.

The Chernoff–Stein lemma gives KL its cleanest operational interpretation: KL⁡(P0 ∥ P1)\KL(P_0\,\|\,P_1) is the number of bits per observation by which the best test reduces type II error, when type I error only needs to remain bounded. The exponent does not depend on ε\eps: requiring αn≤0.05\alpha_n \le 0.05 or αn≤10−9\alpha_n \le 10^{-9} makes no difference to first order in the exponent.

Proof

For δ>0\delta > 0 define the relatively typical sequences, those whose average log ratio is close to its expectation under P0P_0:

Anδ={xn:KL⁡(P0 ∥ P1)−δ≤1nlog⁡2P0n(xn)P1n(xn)≤KL⁡(P0 ∥ P1)+δ}.A_n^\delta = \Big\{x^n : \KL(P_0\,\|\,P_1) - \delta \le \frac1n\log_2\frac{P_0^n(x^n)}{P_1^n(x^n)} \le \KL(P_0\,\|\,P_1) + \delta\Big\}.

Under P0P_0, the average log ratio is an average of iid variables log⁡2P0(Xi)P1(Xi)\log_2\frac{P_0(X_i)}{P_1(X_i)} with expectation KL⁡(P0 ∥ P1)=D\KL(P_0\,\|\,P_1) = D (finite, and the variables are bounded on the finite alphabet), so by the weak law of large numbers P0n(Anδ)→1P_0^n(A_n^\delta) \to 1.

Converse (no test does better). Let BnB_n be any acceptance region with P0n(Bnc)≤εP_0^n(B_n^c) \le \eps. On AnδA_n^\delta we have P1n(xn)≥P0n(xn) 2−n(D+δ)P_1^n(x^n) \ge P_0^n(x^n)\,2^{-n(D + \delta)}, hence

P1n(Bn)≥P1n(Bn∩Anδ)≥2−n(D+δ) P0n(Bn∩Anδ)≥2−n(D+δ)(1−ε−P0n((Anδ)c)).P_1^n(B_n) \ge P_1^n(B_n \cap A_n^\delta) \ge 2^{-n(D + \delta)}\,P_0^n(B_n \cap A_n^\delta) \ge 2^{-n(D + \delta)}\big(1 - \eps - P_0^n((A_n^\delta)^c)\big).

The parenthesis tends to 1−ε>01 - \eps > 0, so lim inf⁡n1nlog⁡2βnε≥−D−δ\liminf_n\frac1n\log_2\beta_n^\eps \ge -D - \delta for every δ>0\delta > 0.

Achievability (a particular test attains it). Using AnδA_n^\delta itself as the acceptance region gives lim sup⁡n1nlog⁡2βnε≤−D+δ\limsup_n\frac1n\log_2\beta_n^\eps \le -D + \delta; you will prove it in the second guided exercise. Combining both parts and taking δ→0\delta \to 0 yields the limit.

∎

Why does KL⁡(P0 ∥ P1)\KL(P_0\,\|\,P_1) appear instead of KL⁡(P1 ∥ P0)\KL(P_1\,\|\,P_0)? Because to keep type I error bounded, the acceptance region must contain nearly all the mass of P0P_0, namely sequences with type near P0P_0. Type II error is the probability under P1P_1 of those sequences, and by Sanov it is ≐2−nKL⁡(P0 ∥ P1)\doteq 2^{-n\KL(P_0\,\|\,P_1)}: the “rare event” for P1P_1 is looking like P0P_0. Swapping the hypotheses changes the exponent. KL asymmetry is not a flaw: it reflects the different costs of protecting either hypothesis.

InteractiveKL as decision speed
Mean log ratio 1k∑i≤klog⁡2P0(Xi)P1(Xi)\tfrac1k\sum_{i \le k}\log_2\frac{P_0(X_i)}{P_1(X_i)} versus kk
  • samples from H0H_0: Xi∼P0X_i \sim P_0
  • samples from H1H_1: Xi∼P1X_i \sim P_1
Exact type II error exponent with αn=ε\alpha_n = \varepsilon
0.50
0.10
0.050
KL⁡(P0 ∥ P1)\KL(P_0\,\|\,P_1)0.7370 bits
KL⁡(P1 ∥ P0)\KL(P_1\,\|\,P_0)0.5310 bits
Chernoff information CC0.1621 bits (λ* = 0.54)
β100\beta_{100} and β1000\beta_{1000}5.8·10⁻¹⁷ and 3.9·10⁻²⁰⁰
1nlog⁡2βn\tfrac1n\log_2\beta_n at n=1000n = 1000−0.6624 versus −0.7370
Minimum nn with βn≤10−6\beta_n \le 10^{-6}43 (naive: log₂10⁶/D = 27.0)
The magenta curve approaches −KL⁡(P0 ∥ P1)-\KL(P_0\,\|\,P_1) slowly, with an order-1/n1/\sqrt{n} offset depending on ε\varepsilon; the asymptote does not. The asymptotes differ: which hypothesis you protect changes the rate.
Testing H0:Xi∼Bern(p0)H_0: X_i \sim \mathrm{Bern}(p_0) against H1:Xi∼Bern(p1)H_1: X_i \sim \mathrm{Bern}(p_1). The first panel shows the average log likelihood ratio of eight simulated sequences under each hypothesis: blue ones head for KL⁡(P0 ∥ P1)\KL(P_0\,\|\,P_1) and orange ones for −KL⁡(P1 ∥ P0)-\KL(P_1\,\|\,P_0). The second shows 1nlog⁡2βn\tfrac1n\log_2\beta_n for the randomized Neyman–Pearson test with exactly αn=ε\alpha_n = \eps, computed without simulation using the binomial distribution, against both asymptotes. Press «Intercambiar hipótesis»: the magenta curve changes destination. Move ε\eps between 0.001 and 0.5: the curve changes, but its asymptote does not. Enable Chernoff information and compare its exponent with the two Stein exponents.

With p0=0.5p_0 = 0.5, p1=0.1p_1 = 0.1 and ε=0.05\eps = 0.05, KL⁡(P0 ∥ P1)=0.737\KL(P_0\,\|\,P_1) = 0.737 bits and KL⁡(P1 ∥ P0)=0.531\KL(P_1\,\|\,P_0) = 0.531 bits. The empirical exponent is −0.540-0.540 at n=100n = 100 and −0.662-0.662 at n=1000n = 1000: it converges, but slowly. The reason is a second-order term calculated by Strassen in 1962:

log⁡2βnε=−nKL⁡(P0 ∥ P1)−nV Φ−1(ε)+O(log⁡n),V=Var⁡P0[log⁡2P0(X)P1(X)],\log_2\beta_n^\eps = -n\KL(P_0\,\|\,P_1) - \sqrt{nV}\,\Phi^{-1}(\eps) + \bigO(\log n), \qquad V = \Var_{P_0}\Big[\log_2\frac{P_0(X)}{P_1(X)}\Big],

where Φ\Phi is the standard normal distribution function. For ε<1/2\eps < 1/2, Φ−1(ε)<0\Phi^{-1}(\eps) < 0 and the term of order n\sqrt n worsens the error relative to 2−nD2^{-nD}. In the example, V=2.51V = 2.51 and with n=1000n = 1000 the formula gives −654.5-654.5 versus the exact −662.4-662.4. The practical effect is large: the minimum nn with βn≤10−6\beta_n \le 10^{-6} is 43, while the naive calculation log⁡2(106)/D\log_2(10^6)/D gives 27.

Bayesian error and Chernoff information

If instead of fixing αn\alpha_n we minimize total error with prior probabilities π0,π1>0\pi_0, \pi_1 > 0, Pe(n)=π0αn+π1βnP_e^{(n)} = \pi_0\alpha_n + \pi_1\beta_n, both errors must tend to zero together and the optimal exponent is different: Chernoff information,

Pe(n)≐2−nC(P0,P1),C(P0,P1)=−min⁡0≤λ≤1log⁡2∑aP0(a)λP1(a)1−λ,P_e^{(n)} \doteq 2^{-nC(P_0, P_1)}, \qquad C(P_0, P_1) = -\min_{0 \le \lambda \le 1}\log_2\sum_a P_0(a)^\lambda P_1(a)^{1 - \lambda},

which does not depend on the priors. Geometrically, the optimal Bayesian boundary in the simplex is {P:KL⁡(P ∥ P0)=KL⁡(P ∥ P1)}\{P : \KL(P\,\|\,P_0) = \KL(P\,\|\,P_1)\}, the cheapest point of that boundary is the geometric mixture Pλ∗∝P0λ∗P11−λ∗P_{\lambda^*} \propto P_0^{\lambda^*}P_1^{1 - \lambda^*}, and C=KL⁡(Pλ∗ ∥ P0)=KL⁡(Pλ∗ ∥ P1)C = \KL(P_{\lambda^*}\,\|\,P_0) = \KL(P_{\lambda^*}\,\|\,P_1). Since Pλ∗P_{\lambda^*} lies “between” the two, C≤min⁡{KL⁡(P0 ∥ P1),KL⁡(P1 ∥ P0)}C \le \min\{\KL(P_0\,\|\,P_1), \KL(P_1\,\|\,P_0)\}: in the example, C=0.162C = 0.162 bits, well below both Stein exponents. Requiring both errors to disappear costs much more than protecting only one.

Local geometry: KL up close

In the previous test the hypotheses were far apart. In parametric statistics the interesting question is local: how many observations distinguish pθp_\theta from pθ+δp_{\theta + \boldsymbol\delta} when δ\boldsymbol\delta is small? By Stein, the answer depends on KL⁡(pθ ∥ pθ+δ)\KL(p_\theta\,\|\,p_{\theta + \boldsymbol\delta}), and that KL has a universal quadratic form.

Proof

Let f(δ)=KL⁡(pθ ∥ pθ+δ)=Eθ[log⁡pθ(X)]−Eθ[log⁡pθ+δ(X)]f(\boldsymbol\delta) = \KL(p_\theta\,\|\,p_{\theta + \boldsymbol\delta}) = \E_\theta[\log p_\theta(X)] - \E_\theta[\log p_{\theta + \boldsymbol\delta}(X)]. Apply multivariable Taylor expansion around δ=0\boldsymbol\delta = \vb{0}. First, f(0)=0f(\vb{0}) = 0. The gradient is ∇f(0)=−Eθ[∇θlog⁡pθ(X)]=−∑x∇θpθ(x)=−∇θ∑xpθ(x)=0\grad f(\vb{0}) = -\E_\theta[\grad_\theta\log p_\theta(X)] = -\sum_x \grad_\theta p_\theta(x) = -\grad_\theta\sum_x p_\theta(x) = \vb{0}: the score has zero mean. The Hessian is ∇2f(0)=−Eθ[∇θ2log⁡pθ(X)]\hess f(\vb{0}) = -\E_\theta[\hess_\theta\log p_\theta(X)], and since ∇2log⁡p=∇2pp−∇log⁡p ∇log⁡p⊤\hess\log p = \frac{\hess p}{p} - \grad\log p\,\grad\log p\T and Eθ[∇2pθ/pθ]=∇2∑xpθ(x)=0\E_\theta[\hess p_\theta/p_\theta] = \hess\sum_x p_\theta(x) = \mat{0}, we get ∇2f(0)=I(θ)\hess f(\vb{0}) = \mat{I}(\theta). Taylor’s formula with Peano remainder gives the result. For the other direction, g(δ)=KL⁡(pθ+δ ∥ pθ)g(\boldsymbol\delta) = \KL(p_{\theta + \boldsymbol\delta}\,\|\,p_\theta) also satisfies g(0)=0g(\vb{0}) = 0, ∇g(0)=0\grad g(\vb{0}) = \vb{0} and ∇2g(0)=∑x∇pθ(x) ∇pθ(x)⊤pθ(x)=I(θ)\hess g(\vb{0}) = \sum_x \frac{\grad p_\theta(x)\,\grad p_\theta(x)\T}{p_\theta(x)} = \mat{I}(\theta).

∎

This Fisher metric induced by KL gives parameter space its own geometry: infinitesimally, KL is half the square of a distance, 12∥δ∥I(θ)2\tfrac12\norm{\boldsymbol\delta}^2_{\mat{I}(\theta)}, and the Fisher information matrix acts as a metric tensor. Rao observed this in 1945; Chentsov later proved that, up to a constant factor, it is the unique metric on distribution families unchanged by sufficient statistics. You saw a special case in the KL lesson: on the simplex, the quadratic approximation 12∑aδa2/pa\tfrac12\sum_a\delta_a^2/p_a is the Fisher metric of the multinomial family.

Two useful examples. For Bern(θ)\mathrm{Bern}(\theta), the score is x−θθ(1−θ)\frac{x - \theta}{\theta(1 - \theta)} and I(θ)=1θ(1−θ)I(\theta) = \frac{1}{\theta(1 - \theta)}: distinguishing coins near θ=0\theta = 0 is much easier than near 0.50.5. For the Gaussian with θ=(μ,σ)\theta = (\mu, \sigma), I(θ)=diag⁡(1/σ2, 2/σ2)\mat{I}(\theta) = \diag(1/\sigma^2,\ 2/\sigma^2), and the exact KL is from the Gaussian lesson:

KL⁡(N(μ0,σ02) ∥ N(μ,σ2))=ln⁡σσ0+σ02+(μ−μ0)22σ2−12.\KL\big(\Normal(\mu_0, \sigma_0^2)\,\|\,\Normal(\mu, \sigma^2)\big) = \ln\frac{\sigma}{\sigma_0} + \frac{\sigma_0^2 + (\mu - \mu_0)^2}{2\sigma^2} - \frac12.

With σ=σ0\sigma = \sigma_0 it is exactly (μ−μ0)2/(2σ02)(\mu - \mu_0)^2/(2\sigma_0^2): in the mean direction Fisher’s approximation is exact. In the scale direction, with μ=μ0\mu = \mu_0 and σ=σ0(1+u)\sigma = \sigma_0(1 + u), expansion gives KL⁡(pθ0 ∥ pθ)=u2−53u3+O(u4)\KL(p_{\theta_0}\,\|\,p_\theta) = u^2 - \tfrac53 u^3 + \bigO(u^4), whereas KL⁡(pθ ∥ pθ0)=u2−13u3+O(u4)\KL(p_\theta\,\|\,p_{\theta_0}) = u^2 - \tfrac13u^3 + \bigO(u^4): both directions share the quadratic term, 12⋅2σ02(σ0u)2=u2\tfrac12 \cdot \tfrac{2}{\sigma_0^2}(\sigma_0 u)^2 = u^2, and asymmetry appears in the cubic term.

InteractiveKL up close
σ → 0: KL divergesμ
  • exact KL level cc
  • ellipse 12δ⊤I(θ0)δ=c\tfrac12\boldsymbol{\delta}\T\mat{I}(\theta_0)\boldsymbol{\delta} = c
  • KL bands: 0.02, 0.1, 0.25, 0.5, 1 and 2 nats
The two densities: pθ0p_{\theta_0} (blue) and pθp_\theta (orange)
0.100
Divergence
θ0=(μ0,σ0)\theta_0 = (\mu_0, \sigma_0)(−0.80, 1.00)
θ=(μ,σ)\theta = (\mu, \sigma)(−0.50, 1.15)
Fisher I(θ0)\mat{I}(\theta_0)diag(1.00, 2.00)
Exact KL KL⁡(pθ0 ∥ pθ)\KL(p_{\theta_0}\,\|\,p_\theta)0.0519 nats
Quadratic 12δ⊤I(θ0)δ\tfrac12\boldsymbol{\delta}\T\mat{I}(\theta_0)\boldsymbol{\delta}0.0675 nats
KL in the other direction0.0665 nats
Relative error: 30.2%. The quadratic form begins to fail, especially in the σ\sigma direction.
The parameter plane (μ,σ)(\mu, \sigma) of a Gaussian. Bands are levels of the exact KL between pθ0p_{\theta_0} (blue) and pθp_\theta (orange), in nats. The thick curve is level cc and the dashed ellipse the same level of the approximation 12δ⊤I(θ0)δ\tfrac12\boldsymbol\delta\T\mat{I}(\theta_0)\boldsymbol\delta. With small cc the two nearly coincide; raise cc and see how the exact curve deforms. Drag θ\theta horizontally (only the mean changes) and then vertically: in which direction does the approximation fail sooner? Reverse the KL direction: the ellipse does not change, the curve does. Finally, lower θ0\theta_0 toward small σ\sigma: ellipses shrink, because distributions are easier to distinguish with little dispersion.

Fisher, Cramér–Rao and the natural gradient

The quadratic form connects the lesson’s three parts. Test H0:θH_0: \theta against H1:θ+δH_1: \theta + \delta with nn observations (one parameter). By Stein, type II error behaves like exp⁡(−n 12δ2I(θ))\exp(-n\,\tfrac12\delta^2 I(\theta)), so making it small requires nδ2I(θ)≳1n\delta^2 I(\theta) \gtrsim 1: the smallest separation detectable with nn observations is of order 1/nI(θ)1/\sqrt{nI(\theta)}. This is the same scale as the Cramér–Rao bound, which says no unbiased estimator has standard deviation below 1/nI(θ)1/\sqrt{nI(\theta)}. These are two views of the same fact: estimating θ\theta to precision δ\delta is equivalent to distinguishing θ\theta from θ±δ\theta \pm \delta.

The metric also identifies the “correct” descent direction. The ordinary gradient is the steepest descent direction for a fixed Euclidean step size, a choice that depends on model parameterization. If instead step size is measured by how much the distribution changes,

min⁡δ ∇L(θ)⊤δsubject to12δ⊤I(θ)δ=ε,\min_{\boldsymbol\delta}\ \grad L(\theta)\T\boldsymbol\delta \quad\text{subject to}\quad \tfrac12\boldsymbol\delta\T\mat{I}(\theta)\boldsymbol\delta = \eps,

Lagrange multipliers give δ∗=−2ε / ∇L⊤I−1∇L I(θ)−1∇L(θ)\boldsymbol\delta^* = -\sqrt{2\eps\,/\,\grad L\T\mat{I}^{-1}\grad L}\ \mat{I}(\theta)^{-1}\grad L(\theta). This is Amari’s natural gradient: the gradient premultiplied by the inverse Fisher metric, invariant (to first order) to reparameterizations. With exact KL as constraint instead of its quadratic approximation, and KL averaged over states, this is the problem solved by TRPO in reinforcement learning.

Rare-event simulation: tilted importance sampling

Sometimes no formula for Qn(E)Q^n(E) exists and simulation is needed. Naive Monte Carlo generates NN samples from QnQ^n and counts those in EE. If p=Qn(E)p = Q^n(E), the estimator p^=1N∑j1[Xn,(j)∈E]\hat p = \frac1N\sum_j\ind[X^{n,(j)} \in E] is unbiased with relative error

Var⁡(p^)p=1−pNp,\frac{\sqrt{\Var(\hat p)}}{p} = \sqrt{\frac{1 - p}{Np}},

so about 100/p100/p samples are needed for 10% relative error. With p≐2−nD∗p \doteq 2^{-nD^*}, cost grows exponentially in nn. As seen in the Sanov figure, with 1,000 samples naive Monte Carlo stops seeing the event once pp drops below 10−310^{-3}.

Importance sampling generates samples from another distribution RR and corrects with the likelihood ratio:

p^R=1N∑j=1N1[Xn,(j)∈E] Qn(Xn,(j))Rn(Xn,(j)),Xn,(j)∼Rn,\hat p_R = \frac1N\sum_{j=1}^N \ind[X^{n,(j)} \in E]\,\frac{Q^n(X^{n,(j)})}{R^n(X^{n,(j)})}, \qquad X^{n,(j)} \sim R^n,

which is unbiased whenever RR gives positive mass wherever QQ does. The ideal proposal, which has zero variance, is the conditional Qn(⋅∣E)Q^n(\cdot \given E), unusable because its normalizing constant is precisely pp. But the conditional limit theorem says what it resembles: P∗nP^{*n}. Thus the natural choice is R=P∗R = P^*, the exponential tilt of QQ. The note on convex sets already gave the needed bound: on EE, the weight satisfies Qn(xn)P∗n(xn)≤2−nD∗\frac{Q^n(x^n)}{P^{*n}(x^n)} \le 2^{-nD^*}. Therefore

EP∗[(1E Qn/P∗n)2]=EQ[1E Qn/P∗n]≤2−nD∗ p,Var⁡(p^P∗)p2≤1N(2−nD∗p−1).\E_{P^*}\big[(\ind_E\,Q^n/P^{*n})^2\big] = \E_Q\big[\ind_E\,Q^n/P^{*n}\big] \le 2^{-nD^*}\,p, \qquad \frac{\Var(\hat p_{P^*})}{p^2} \le \frac1N\Big(\frac{2^{-nD^*}}{p} - 1\Big).

Since p≐2−nD∗p \doteq 2^{-nD^*}, the ratio 2−nD∗/p2^{-nD^*}/p grows only subexponentially (as n\sqrt{n} in this lesson’s examples): relative error changes from exponential to polynomial. An estimator with this property is asymptotically efficient; Siegmund (1976) and Sadowsky and Bucklew (1990) showed that tilting toward the dominant point P∗P^* has this property, and among exponential tilts is essentially the only one. It is the standard tool for importance sampling of rare events.

Implementation from scratch

Start with types: enumerate them, compute each class’s exact probability with log-gamma (never forming huge factorials), and check the bounds for all types at once.

[ ]Types and type classes with log-gammaBrowser
import numpy as np
from math import lgamma, log, log2

LN2 = log(2)

def log2_multinom(k):
    n = sum(k)
    return (lgamma(n + 1) - sum(lgamma(x + 1) for x in k)) / LN2

def kl_bits(p, q):
    return sum(pi * log2(pi / qi) for pi, qi in zip(p, q) if pi > 0)

def ent_bits(p):
    return -sum(pi * log2(pi) for pi in p if pi > 0)

def log2_prob_type_class(k, q):
    """log2 Q^n(T(P)) para el tipo de recuentos k."""
    return log2_multinom(k) + sum(ki * log2(qi) for ki, qi in zip(k, q) if ki > 0)

def types(n, m=3):
    """Todos los vectores de recuentos (k_1, ..., k_m) que suman n."""
    if m == 1:
        yield (n,)
        return
    for k in range(n + 1):
        for rest in types(n - k, m - 1):
            yield (k,) + rest

q = (0.5, 0.3, 0.2)
for n in [5, 20, 80]:
    T = list(types(n))
    p = [[x / n for x in k] for k in T]
    lp = np.array([log2_prob_type_class(k, q) for k in T])
    D = np.array([kl_bits(pk, q) for pk in p])
    H = np.array([ent_bits(pk) for pk in p])
    lT = np.array([log2_multinom(k) for k in T])
    cota = 3 * log2(n + 1)
    assert np.all(lT <= n * H + 1e-9) and np.all(lT >= n * H - cota - 1e-9)
    assert np.all(lp <= -n * D + 1e-9) and np.all(lp >= -n * D - cota - 1e-9)
    holgura = -lp / n - D
    print(f"n = {n:2d}: {len(T):4d} tipos (cota {(n + 1) ** 3:6d}), suma de las Q^n(T(P)) = {np.sum(2.0 ** lp):.12f}")
    print(f"        -(1/n) log2 Q^n(T(P)) - D(P||Q) entre {holgura.min():.4f} y {holgura.max():.4f};  3 log2(n+1)/n = {cota / n:.4f}")

k = (70, 30)
print("\nmoneda justa, 70 caras en 100 tiradas:")
print(f"  log2 Q^n(T(P)) = {log2_prob_type_class(k, (0.5, 0.5)):.3f}   -n D = {-100 * kl_bits((0.7, 0.3), (0.5, 0.5)):.3f}")
print(f"  log2 |T(P)| = {log2_multinom(k):.3f}   n H(P) = {100 * ent_bits((0.7, 0.3)):.3f}")

The class probabilities sum to 1 (they partition Xn\mathcal{X}^n), all bounds hold, and the actual maximum gap is much smaller than the theoretical one: with n=80n = 80, 0.0830.083 bits versus 0.2380.238. The bound (n+1)m(n+1)^m is convenient for proofs but pessimistic.

Now Sanov for the coin, with the exact binomial tail calculated in log scale, the I-projection by bisection over λ\lambda, and the die’s conditional limit using the exact distribution of the sum.

[ ]Sanov, tilting and the conditional limitBrowser
def log2_binom_pmf(n, kk, p):
    return log2_multinom((kk, n - kk)) + kk * log2(p) + (n - kk) * log2(1 - p)

def log2sumexp2(a):
    a = np.asarray(a, dtype=float)
    m = a.max()
    return m + np.log2(np.sum(2.0 ** (a - m)))

def h2(x):
    return ent_bits((x, 1 - x))

print(f"exponente de Sanov, frecuencia de caras >= 0.7: D* = 1 - h2(0.7) = {1 - h2(0.7):.4f} bits")
for n in [10, 100, 1000, 10000]:
    k0 = int(np.ceil(0.7 * n - 1e-9))
    lP = log2sumexp2([log2_binom_pmf(n, kk, 0.5) for kk in range(k0, n + 1)])
    print(f"  n = {n:5d}:  log2 P = {lP:10.2f}   -(1/n) log2 P = {-lP / n:.4f}")

# I-proyección sobre {media >= a} por inclinación exponencial (bisección en lambda)
def tilt(q, g, lam):
    w = q * np.exp(lam * (g - g.max()))
    return w / w.sum()

def i_projection(q, g, a, lo=0.0, hi=50.0):
    for _ in range(100):
        mid = (lo + hi) / 2
        if tilt(q, g, mid) @ g < a:
            lo = mid
        else:
            hi = mid
    lam = (lo + hi) / 2
    return tilt(q, g, lam), lam

caras = np.arange(1, 7)
Qd = np.full(6, 1 / 6)
Pst, lam = i_projection(Qd, caras, 4.0)
Dst = kl_bits(Pst, Qd)
print(f"\ndado justo, media >= 4:  lambda = {lam:.4f} nats,  P* = {np.round(Pst, 4)},  D* = {Dst:.4f} bits")

def dist_suma(n, q):
    """Distribución exacta de X_1 + ... + X_n con X_i en {1, ..., 6} (convolución)."""
    d = np.array([1.0])
    for _ in range(n):
        d = np.convolve(d, np.r_[0.0, q])
    return d   # d[s] = P(suma = s)

for n in [10, 50, 200]:
    d, d1 = dist_suma(n, Qd), dist_suma(n - 1, Qd)
    s, s1 = np.arange(len(d)), np.arange(len(d1))
    pE = d[s >= 4 * n].sum()
    # P(X_1 = a | media >= 4) = Q(a) P(S_{n-1} >= 4n - a) / P(E)
    cond = np.array([Qd[a - 1] * d1[s1 >= 4 * n - a].sum() for a in caras]) / pE
    print(f"  n = {n:3d}: P(E) = {pE:.2e}, -(1/n) log2 P(E) = {-np.log2(pE) / n:.4f}, "
          f"P(X1 = . | E) = {np.round(cond, 3)},  D(cond||P*) = {kl_bits(cond, Pst):.1e}")

The coin exponent decreases from 0.2540.254 at n=10n = 10 to 0.11930.1193 at n=104n = 10^4, against the limit 0.11870.1187: after ten thousand flips half a millibit remains, the trace of the 1/n1/\sqrt n factor. The die’s conditional distribution approaches P∗P^* with a divergence falling by one order of magnitude whenever nn is multiplied by four or five.

The Stein test, using the exact Neyman–Pearson test. For two Bernoulli distributions, the number of ones KK is a sufficient statistic and the likelihood ratio is monotone in KK, so the optimal test rejects H0H_0 when KK is on the P1P_1 side and randomizes at the boundary to make αn\alpha_n exactly ε\eps.

[ ]Chernoff–Stein with the exact Neyman–Pearson testBrowser
def np_test_beta(p0, p1, n, eps):
    """Test de Neyman-Pearson aleatorizado para Bern(p0) frente a Bern(p1) con alpha_n = eps exacto.
    Devuelve log2 beta_n. El estadístico suficiente es el número de unos K."""
    ks = np.arange(n + 1)
    if p0 < p1:                       # orientamos: H0 favorece los K grandes
        ks = ks[::-1]
    l0 = np.array([log2_binom_pmf(n, kk, p0) for kk in ks])
    l1 = np.array([log2_binom_pmf(n, kk, p1) for kk in ks])
    acum = np.cumsum(2.0 ** l0)       # P0(K <= k) en el orden orientado
    c = int(np.searchsorted(acum, eps, side="right"))   # se rechaza H0 si K < c ...
    debajo = acum[c - 1] if c > 0 else 0.0
    gamma = min(1.0, (eps - debajo) / 2.0 ** l0[c])     # ... y con probabilidad gamma si K = c
    partes = list(l1[c + 1:])
    if gamma < 1:
        partes.append(l1[c] + np.log2(1 - gamma))
    return log2sumexp2(partes)

def kl_bern(a, b):
    return kl_bits((a, 1 - a), (b, 1 - b))

p0, p1, eps = 0.5, 0.1, 0.05
print(f"D(P0||P1) = {kl_bern(p0, p1):.4f} bits,  D(P1||P0) = {kl_bern(p1, p0):.4f} bits")
for n in [10, 100, 1000]:
    lb = np_test_beta(p0, p1, n, eps)
    lb_inv = np_test_beta(p1, p0, n, eps)
    print(f"  n = {n:4d}:  (1/n) log2 beta_n = {lb / n:.4f}   con las hipótesis intercambiadas: {lb_inv / n:.4f}")

# la log-razón media bajo cada hipótesis, por simulación
rng = np.random.default_rng(0)
a1, a0 = np.log2(p0 / p1), np.log2((1 - p0) / (1 - p1))
for nombre, p in [("H0", p0), ("H1", p1)]:
    X = rng.random((2000, 1000)) < p
    llr = np.where(X, a1, a0).mean(axis=1)
    print(f"bajo {nombre}: media de (1/n) LLR = {llr.mean():+.4f}, desviación típica = {llr.std():.4f}")

# el exponente no depende de eps, pero la convergencia sí
for e in [0.001, 0.05, 0.5]:
    print(f"eps = {e}:  (1/n) log2 beta_n con n = 1000: {np_test_beta(p0, p1, 1000, e) / 1000:.4f}")

With n=1000n = 1000 the exponent is −0.662-0.662 when protecting H0=Bern(0.5)H_0 = \mathrm{Bern}(0.5) and −0.488-0.488 when roles are swapped, heading toward −0.737-0.737 and −0.531-0.531. The effect of ε\eps at finite nn is enormous even though it disappears in the limit: −0.595-0.595 with ε=0.001\eps = 0.001 versus −0.743-0.743 with ε=0.5\eps = 0.5. The latter is below −D-D, as predicted by Strassen’s term with Φ−1(0.5)=0\Phi^{-1}(0.5) = 0: only the logarithmic correction remains.

Finally, importance sampling for the die: P(Xˉ100≥4.5)\Pr(\bar X_{100} \ge 4.5), equal to 1.5×10−91.5 \times 10^{-9}, with 20,000 samples from each method.

[ ]Importance sampling tilted toward P*Browser
Qd = np.full(6, 1 / 6)
n, a = 100, 4.5
Pst, lam = i_projection(Qd, caras, a)
logM = np.log(Qd @ np.exp(lam * caras))          # Lambda(lambda) = log E_Q[e^{lambda X}], en nats
d = dist_suma(n, Qd)
exacta = d[np.arange(len(d)) >= a * n].sum()
print(f"P(media de {n} dados >= {a}) exacta = {exacta:.4e};  2^(-n D*) = {2 ** (-n * kl_bits(Pst, Qd)):.4e}")

N = 20000
rng = np.random.default_rng(1)
# Monte Carlo ingenuo
S = rng.choice(caras, size=(N, n), p=Qd).sum(axis=1)
ingenuo = (S >= a * n).astype(float)
# muestreo de importancia: se muestrea con P* y se reponderan las muestras con dQ^n/dP*^n
S = rng.choice(caras, size=(N, n), p=Pst).sum(axis=1)
w = np.exp(-lam * S + n * logM)                   # prod_i Q(x_i) / P*(x_i)
inclinado = (S >= a * n) * w
for nombre, z in [("ingenuo", ingenuo), ("inclinado", inclinado)]:
    m = z.mean()
    er = z.std() / (np.sqrt(N) * m) if m > 0 else float("inf")
    print(f"{nombre:10s}: estimación = {m:.4e}   error relativo estimado = {er:.3f}   aciertos = {(z > 0).sum()}")
print(f"cota del peso en el suceso: 2^(-n D*) = {2 ** (-n * kl_bits(Pst, Qd)):.3e};  peso máximo observado = {w[S >= a * n].max():.3e}")

The naive method sees no hits; the tilted method hits in half its samples and estimates the probability with 2% relative error. A sequence’s weight depends only on its sum, ∏iQ(xi)P∗(xi)=e−λ∗Sn+nΛ(λ∗)\prod_i\frac{Q(x_i)}{P^*(x_i)} = e^{-\lambda^* S_n + n\Lambda(\lambda^*)}, and on the event never exceeds 2−nD∗2^{-nD^*}: the maximum observed weight matches the bound, attained by sequences exactly at the boundary Sn=naS_n = na.

The library version

SciPy provides almost everything above: binomial tails in log scale (stats.binom.logsf), the contribution pln⁡(p/q)p\ln(p/q) with support conventions (special.rel_entr, in nats), and a root finder for tilting (optimize.brentq). Use these to check the coin’s Bahadur–Rao factor and KL’s quadratic form with a numerical Hessian.

[ ]Bahadur–Rao, brentq and the Fisher metricBrowser
import numpy as np
from scipy import stats, special, optimize
import matplotlib.pyplot as plt

# 1. colas binomiales exactas sin bucles; n múltiplo de 10 para que 0.7 n sea entero
D_moneda = special.rel_entr([0.7, 0.3], [0.5, 0.5]).sum() / np.log(2)   # rel_entr usa nats
ns = 10 * np.unique(np.logspace(0, 2.6, 40).astype(int))
log2P = stats.binom.logsf(7 * ns // 10 - 1, ns, 0.5) / np.log(2)      # log2 P(K >= 0.7 n)
hueco = -log2P / ns - D_moneda
lam_m = np.log(7 / 3)
constante = np.log2((1 - np.exp(-lam_m)) * np.sqrt(0.21 * 2 * np.pi))
print(f"D* = {D_moneda:.5f} bits;  Bahadur-Rao: n (hueco) - (1/2) log2 n -> {constante:.4f}")
for n, h in list(zip(ns, hueco))[::6]:
    print(f"  n = {n:5d}:  hueco = {h:.5f}   n (hueco) - (1/2) log2 n = {n * h - 0.5 * np.log2(n):.4f}")

# 2. la I-proyección del dado con brentq
caras = np.arange(1, 7)
media = lambda l: (np.exp(l * caras) / np.exp(l * caras).sum()) @ caras
print(f"\nlambda del dado con media 4: {optimize.brentq(lambda l: media(l) - 4.0, 0.0, 10.0):.6f} nats")

# 3. la KL vista de cerca: hessiano numérico de theta -> D(p_theta0 || p_theta) frente a I(theta0)
def kl_gauss(t0, t1):
    (m0, s0), (m1, s1) = t0, t1
    return np.log(s1 / s0) + (s0**2 + (m0 - m1)**2) / (2 * s1**2) - 0.5    # nats

def hessiano(f, x, h=1e-4):
    x = np.asarray(x, float)
    d = len(x)
    H = np.zeros((d, d))
    for i in range(d):
        for j in range(d):
            ei, ej = np.eye(d)[i] * h, np.eye(d)[j] * h
            H[i, j] = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (4 * h * h)
    return H

theta0 = np.array([0.5, 1.5])
print("hessiano numérico de la KL:\n", np.round(hessiano(lambda t: kl_gauss(theta0, t), theta0), 6))
print("información de Fisher diag(1/s^2, 2/s^2):", np.round([1 / 1.5**2, 2 / 1.5**2], 6))

# Bernoulli: D(Bern(t) || Bern(t + d)) frente a (1/2) d^2 I(t), con I(t) = 1 / (t (1 - t))
t = 0.5
for dl in [0.01, 0.05, 0.1, 0.2, 0.4]:
    exacta = special.rel_entr([t, 1 - t], [t + dl, 1 - t - dl]).sum()
    print(f"  delta = {dl:4.2f}:  KL = {exacta:.6f} nats,  (1/2) delta^2 I = {0.5 * dl**2 / (t * (1 - t)):.6f}")

fig, ax = plt.subplots(figsize=(6, 3.2))
ax.semilogx(ns, hueco, label="−(1/n) log₂ P − D*")
ax.semilogx(ns, (0.5 * np.log2(ns) + constante) / ns, "--", color="gray", label="Bahadur-Rao")
ax.set_xlabel("n"); ax.set_ylabel("bits por símbolo"); ax.legend(); plt.tight_layout(); plt.show()

The quantity n⋅(gap)−12log⁡2nn\cdot(\text{gap}) - \tfrac12\log_2 n converges to −0.607-0.607, the Bahadur–Rao constant for a lattice variable: excess exponent is not noise but exactly 12log⁡2n+constn\frac{\frac12\log_2 n + \text{const}}{n}. The numerical Hessian reproduces diag⁡(1/σ2,2/σ2)\diag(1/\sigma^2, 2/\sigma^2) to six digits, and for Bernoulli the quadratic approximation is excellent up to δ=0.1\delta = 0.1 (2% error) and poor at δ=0.4\delta = 0.4 (37%).

Common mistakes

Exercises

ProofProbability of a type class
Prove: For every P∈PnP \in \mathcal{P}_n and distribution QQ on an alphabet of mm symbols, (n+1)−m 2−nKL⁡(P ∥ Q)≤Qn(T(P))≤2−nKL⁡(P ∥ Q)(n+1)^{-m}\,2^{-n\KL(P\,\|\,Q)} \le Q^n(T(P)) \le 2^{-n\KL(P\,\|\,Q)}.
0
You have two results: if xn∈T(P)x^n \in T(P), then Qn(xn)=2−n(H⁡(P)+KL⁡(P ∥ Q))Q^n(x^n) = 2^{-n(\Ent(P) + \KL(P\,\|\,Q))}; and the distribution's own type class is most probable, Pn(T(P))≥Pn(T(P^))P^n(T(P)) \ge P^n(T(\hat P)) for every P^∈Pn\hat P \in \mathcal{P}_n.

Step 1 of 4. How do you write Qn(T(P))Q^n(T(P))?

ProofStein: a test achieving the exponent
Prove: Let P0,P1P_0, P_1 be distributions on a finite alphabet with D=KL⁡(P0 ∥ P1)<∞D = \KL(P_0\,\|\,P_1) < \infty, ε∈(0,1)\eps \in (0, 1) and δ>0\delta > 0. Then lim sup⁡n1nlog⁡2βnε≤−D+δ\limsup_{n} \frac1n\log_2\beta_n^\eps \le -D + \delta.
0
Use as acceptance region the relatively typical sequences An={xn:D−δ≤1nlog⁡2P0n(xn)P1n(xn)≤D+δ}A_n = \{x^n : D - \delta \le \frac1n\log_2\frac{P_0^n(x^n)}{P_1^n(x^n)} \le D + \delta\}.

Step 1 of 4. Why does this test's type I error, αn=P0n(Anc)\alpha_n = P_0^n(A_n^c), eventually fall below ε\eps?

NumericThe coin's Sanov exponent
Flip a fair coin nn times. Calculate, in bits, the exponent D∗D^* such that P(frequency of heads≥0.7)≐2−nD∗\Pr(\text{frequency of heads} \ge 0.7) \doteq 2^{-nD^*}.
NumericFisher information of a coin
Calculate the Fisher information I(θ)I(\theta) of a Bern(θ)\mathrm{Bern}(\theta) at θ=0.5\theta = 0.5 (using the natural logarithm, as usual).
NumericHow quickly does type II error fall?
You test H0:Xi∼Bern(0.5)H_0: X_i \sim \mathrm{Bern}(0.5) against H1:Xi∼Bern(0.1)H_1: X_i \sim \mathrm{Bern}(0.1) with type I error bounded by ε=0.05\eps = 0.05. How many bits per observation does the best test gain in type II error, that is, what is −lim⁡n1nlog⁡2βnε-\lim_n \frac1n\log_2\beta_n^\eps?
QuizThe order of arguments
Which arguments correctly explain why, with type I error bounded, the type II error exponent is KL⁡(P0 ∥ P1)\KL(P_0\,\|\,P_1) rather than KL⁡(P1 ∥ P0)\KL(P_1\,\|\,P_0)?

More than one answer may be correct.

QuizWhat you know about the first roll
You roll a fair die 1,000 times and are told, with no further detail, that the mean roll was at least 4. What is the approximate distribution of the first roll?
QuizWhich exponent do you need?
You design a detector observing nn iid samples and deciding between two regimes, P0P_0 and P1P_1, equally likely a priori. You want average error probability 12αn+12βn\tfrac12\alpha_n + \tfrac12\beta_n below 10−610^{-6}. Which quantity determines the required nn to first order in the exponent?
CodeTilted importance sampling
Implement tilted_is(p, a, n, N, rng), returning an array of N independent samples Zj≥0Z_j \ge 0 with E[Zj]=P(Xˉn≥a)\E[Z_j] = \Pr(\bar X_n \ge a) for Xi∼iidBern(p)X_i \iid \mathrm{Bern}(p) and a>pa > p. Sample from the tilted distribution, which for a Bernoulli is Bern(a)\mathrm{Bern}(a), and reweight each sample by ∏iQ(xi)/P∗(xi)\prod_i Q(x_i)/P^*(x_i). Note the weight depends only on the number of ones KK, so sampling K∼Bin(n,a)K \sim \mathrm{Bin}(n, a) suffices. Compute the weight in log scale: with n=1000n = 1000 the probability is of order 10−3710^{-37}. Use the supplied rng generator (an np.random.Generator). The tests compare against exact probability and check that relative variance is at least 100 times smaller than naive Monte Carlo.
import numpy as np

def tilted_is(p, a, n, N, rng):
  """Devuelve N muestras Z_j >= 0 con E[Z_j] = P(media de n Bern(p) >= a), muestreando con Bern(a)."""
  # tu código: muestrea K ~ Bin(n, a), calcula log(peso) = K log(p/a) + (n - K) log((1-p)/(1-a)),
  # y devuelve el indicador de K >= a n multiplicado por el peso
  return np.zeros(N)
Shift+Enter to run

Summary

Key idea
There are only polynomially many possible sample compositions and each has probability 2−nKL⁡(P ∥ Q)2^{-n\KL(P\,\|\,Q)}; consequently KL is simultaneously the exponential cost of a rare event (Sanov), the speed of the best test (Chernoff–Stein), and, up close, the Fisher metric.
  • Method of types. There are at most (n+1)m(n+1)^m types; the class of PP has ≐2nH⁡(P)\doteq 2^{n\Ent(P)} sequences, each with probability 2−n(H⁡(P)+KL⁡(P ∥ Q))2^{-n(\Ent(P) + \KL(P\,\|\,Q))} under QnQ^n, and the whole class receives Qn(T(P))≐2−nKL⁡(P ∥ Q)Q^n(T(P)) \doteq 2^{-n\KL(P\,\|\,Q)}, with explicit bounds for each nn.
  • Sanov. P(PXn∈E)≐2−nmin⁡P∈EKL⁡(P ∥ Q)\Pr(P_{X^n} \in E) \doteq 2^{-n\min_{P \in E}\KL(P\,\|\,Q)}. For a constraint on a mean, the minimizer is the exponential tilt Qλ∝QeλgQ_\lambda \propto Qe^{\lambda g} and the exponent is Cramér’s rate function: the Chernoff bound is Sanov on a half-space. For convex EE the polynomial factor in the upper bound is unnecessary.
  • Conditional limit. Conditional on a rare convex event, the type concentrates at the I-projection P∗P^* and each observation follows P∗P^*. With uniform QQ, P∗P^* is the maximum-entropy distribution.
  • Chernoff–Stein. With type I error bounded, the best type II error decays as 2−nKL⁡(P0 ∥ P1)2^{-n\KL(P_0\,\|\,P_1)}, independently of ε\eps; Bayesian error decays more slowly, as 2−nC(P0,P1)2^{-nC(P_0, P_1)}. At finite nn, Strassen’s correction of order n\sqrt n matters.
  • Local geometry. KL⁡(pθ ∥ pθ+δ)=12δ⊤I(θ)δ+o(∥δ∥2)\KL(p_\theta\,\|\,p_{\theta + \boldsymbol\delta}) = \tfrac12\boldsymbol\delta\T\mat{I}(\theta)\boldsymbol\delta + o(\norm{\boldsymbol\delta}^2): Fisher information is the metric induced by KL, sets the Cramér–Rao scale 1/nI1/\sqrt{nI} and defines the natural gradient. Far from the expansion point the approximation fails asymmetrically.
  • Rare-event simulation. Naive Monte Carlo needs ≈100/p\approx 100/p samples; tilting toward P∗P^* and reweighting bounds the event weight by 2−nD∗2^{-nD^*} and makes relative error polynomial in nn.