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.
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:
Method
Bound or value of P(heads≥700)
Chebyshev, Var/t2=250/2002
6.3×10−3
Hoeffding, e−2nt2 with t=0.2
1.8×10−35
Sanov, 2−nKL(P∗∥Q)
1.8×10−36
Exact value (binomial sum)
8.8×10−38
Chebyshev is useless: atypical events for a sum of independent variables decay exponentially, not as a power of n. 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∗ times a factor that decays only as 1/n. That exponent 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. If you have tried 100 strategies, the chance that one achieves it is 0.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−6? The answer has the form n≈log(1/β)/KL(P0∥P1), which is why KL can be read as a decision speed.
One idea underlies all three, the method of types: classify the ∣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 of m=∣X∣ symbols and sequences xn=(x1,…,xn)∈Xn. Write N(a∣xn) for the number of times symbol a appears in xn.
With X={1,2,3} and x5=13121, the type is P=(3/5,1/5,1/5) and T(P) contains every rearrangement of the sequence: ∣T(P)∣=3!1!1!5!=20. In general, ∣T(P)∣ is the multinomial coefficient (nP(1),…,nP(m)n).
There are few types, because a type is determined by m counts between 0 and n:
The equality is the classical count of nonnegative integer solutions of k1+⋯+km=n (stars and bars); the bound follows because each of the m counts has at most n+1 values. The contrast matters: there are mn 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∼iidQ, the probability of a particular sequence is Qn(xn)=∏iQ(xi). Grouping equal factors:
And −∑aP(a)log2Q(a)=∑aP(a)log2P(a)1+∑aP(a)log2Q(a)P(a)=H(P)+KL(P∥Q), the cross-entropy decomposition. If Q(a)=0 for some a with P(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 Q.
The size of a type class
The upper bound takes one line: by the previous theorem with Q=P, 1≥Pn(T(P))=∣T(P)∣2−nH(P). The lower bound needs a lemma of independent interest: the most probable type class under P is that of P.
Proof
Use the inequality s!r!≥sr−s for integers r,s≥0: if r≥s, the quotient is the product of r−s factors greater than s; if r<s, it is the reciprocal of a product of s−r factors at most s. With ka=nP(a) and k^a=nP^(a),
because ka=nP(a). If P(a)=0 for an a with 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∣ classes: 1=∑P^Pn(T(P^))≤∣Pn∣Pn(T(P)), so Pn(T(P))≥(n+1)−m and ∣T(P)∣=Pn(T(P))2nH(P)≥(n+1)−m2nH(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 P when data come from Q is 2−nKL(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⟺n→∞limn1log2bnan=0,
so the theorem becomes Qn(T(P))≐2−nKL(P∥Q) and ∣T(P)∣≐2nH(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 n grows.
InteractiveType classes in the simplex
KL(P∥Q) bands and point colors, in bits:0.052.5 or more
Color of each type
Type P(2, 3, 5)/10
Types, bound (n+1)366 ≤ 1331
log2∣T(P)∣, nH(P)11.30 ≤ 14.85
Qn(T(P))0.00544
Upper bound 2−nKL0.064
Lower bound (n+1)32−nKL4.8·10⁻⁵
−n1log2Qn(T(P))0.752 bits
KL(P∥Q)0.397 bits
Difference0.356 bits
Mass with KL≤0.050.276
With n=10 many points are one or more color steps ahead of their band: the empirical exponent exceeds KL(P∥Q) by up to n3log2(n+1) bits. Increase n.
Each point is a type P∈Pn of the alphabet {1,2,3}, colored by its empirical exponent −n1log2Qn(T(P)) on the same scale as the background bands, which are levels of KL(P∥Q). With n=10 many points are one or more steps ahead of their band: the polynomial factor adds up to n3log2(n+1) bits. Raise n 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)) and almost all probability lies near Q in a region shrinking with n. Drag type P 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,
a series summable in n. By the Borel–Cantelli lemma, KL(PXn∥Q)→0 almost surely, and hence PXn→Q. This is a quantitative version of asymptotic equipartition: sequences whose type is near Q are in the typical set, since for them −n1log2Qn(xn)=H(Pxn)+KL(Pxn∥Q)≈H(Q).
Sanov’s theorem
Now return to the motivating question. Let E be a set of distributions on X, for example “the frequency of heads is at least 0.7”. We want the probability that the sample type lies in E, written Qn(E)=P(PXn∈E)=∑P∈E∩PnQn(T(P)). Since the sum has polynomially many terms, its largest term dominates, and that is the type in E with smallest KL divergence.
Proof
Upper bound.Qn(E)=∑P∈E∩PnQn(T(P))≤∑P∈E∩Pn2−nKL(P∥Q)≤∣Pn∣2−ninfP∈EKL(P∥Q), and ∣Pn∣≤(n+1)m.
Lower bound. Since Q has full support, P↦KL(P∥Q) is continuous on the entire simplex. Given η>0, because E is the closure of its interior there is a P in the interior of E with KL(P∥Q)≤KL(P∗∥Q)+η. Rounding nP yields a type Pn∈Pn with maxa∣Pn(a)−P(a)∣≤m/n; for large n, Pn lies in a ball around P contained in E, and KL(Pn∥Q)→KL(P∥Q) by continuity. Then
Qn(E)≥Qn(T(Pn))≥(n+1)−m2−nKL(Pn∥Q),
whence liminfnn1log2Qn(E)≥−KL(P∥Q)≥−KL(P∗∥Q)−η. Since η is arbitrary and the upper bound gives limsupnn1log2Qn(E)≤−KL(P∗∥Q), the limit exists and equals −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). All other points in E are exponentially less probable than the best and do not count. This is a large deviations result: the law of large numbers says PXn→Q; Sanov quantifies the price of a fixed deviation.
The regularity assumption on E is not an empty technicality. If E is, for instance, {P:P(1)=1/2}, no type lies in E (types have rational coordinates) and Qn(E)=0 for every n, even though the infimum of KL over E is finite.
Events involving a mean: exponential tilting
The most important case is a constraint on the empirical mean of a function g:X→R: E={P:EP[g]≥α}, with α>EQ[g] so that the event is rare. Since n1∑ig(Xi)=EPXn[g], this is the event “the sample mean of g is at least α”. In the simplex, E is a half-space. The KL minimum over it can be calculated explicitly.
Proof
The mean λ↦EQλ[g]=Λ′(λ) is continuous and strictly increasing, because Λ′′(λ)=VarQλ[g]>0 if g is not constant; it equals EQ[g] at λ=0 and tends to maxg as λ→∞, so λ∗ exists and is unique. For any P∈E and λ≥0,
Since KL(P∥Qλ)≥0, we have KL(P∥Q)≥λα−Λ(λ) for every λ≥0. With λ=λ∗ and P=Qλ∗, which belongs to E, both inequalities are equalities. Finally, λα−Λ(λ) is concave in λ and its derivative α−Λ′(λ) vanishes at λ∗, which is therefore its maximum.
∎
The expression supλ(λα−Λ(λ)) 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], α=0.7, and tilting the fair coin to mean 0.7 gives the coin (0.7,0.3), with λ∗=ln(7/3)=0.847 and KL(P∗∥Q)=1−h2(0.7)=0.1187 bits.
InteractiveSanov: the cheapest way for the unlikely to happen
event E and its boundary
contour KL(P∥Q)=D∗
types in E, area ∝ conditional probability
conditional mean P(X1=⋅∣E) (hollow circle)
Event probability versus n (log scale)
Plot
Event Emean of g ≥ 2.30, g = (1, 2, 3)
Q and its mean(0.500, 0.300, 0.200), 1.700
P∗ (I-projection)(0.200, 0.300, 0.500)
D∗=KL(P∗∥Q)0.3966 bits
Tilt λ0.916 nats
Qn(E) with n=402.2·10⁻⁶
−n1log2Qn(E) versus D∗0.4699 versus 0.3966
Exact P(X1=⋅∣E)(0.192, 0.302, 0.507)
The highest-weight types in E (magenta dots) cluster near P∗: if the event occurs, it almost certainly occurs “in the manner of P∗”. Naive Monte Carlo last sees the event at n=20 and estimates 0 thereafter.
The triangle is the simplex of a three-sided die with distribution Q (orange, draggable). The magenta region is the event E: the mean face, or the frequency of face 3, is at least α. Thin curves are levels of KL(P∥Q) and the thick curve is level D∗ touching E exactly at the I-projection P∗. Magenta points are the types in E for the chosen n, with area proportional to their probability conditional on E; the hollow circle is their mean. The plot shows the exact probability of E (sum over type classes), the bound 2−nD∗, and naive Monte Carlo with 1,000 samples, which disappears when the event is too rare. Raise α, switch to «Exponente» and see how slowly −n1log2Qn(E) approaches D∗. Increase n 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∗, as guaranteed by the preceding note, and the gap on a logarithmic scale grows slowly: this is the Θ(1/n) factor. For the coin, the refined calculation of Bahadur and Rao gives, for integer 0.7n, P(heads≥0.7n)∼2−nD∗/((1−e−λ∗)σ∗2πn), with σ∗2=0.21 the variance under the tilted coin; you will check it numerically in the cells. Second, the cloud: probability conditional on E is not spread over the whole event but concentrates near 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∗.
Proof
Let D∗=KL(P∗∥Q) and δ>0. Split E into cheap types A={P∈E:KL(P∥Q)≤D∗+δ} and expensive ones B={P∈E:KL(P∥Q)≥D∗+2δ}. Sanov’s upper bound applied to B gives Qn(B)≤(n+1)m2−n(D∗+2δ). Since E is convex with nonempty interior, A contains an open set (interior points of E near P∗), and as in Sanov’s proof there are types Pn∈A for large n, with Qn(A)≥(n+1)−m2−n(D∗+δ). Then
P(PXn∈B∣PXn∈E)≤Qn(A)Qn(B)≤(n+1)2m2−nδ→0.
Outside B, the Pythagorean inequality gives KL(P∥P∗)≤KL(P∥Q)−D∗<2δ, and by Pinsker’s inequality the type is within total variation distance δln2 of P∗ (with KL in bits). This proves convergence in probability of the type. For the marginal, the event {PXn∈E} is unchanged by permuting the sequence, so P(Xi=a∣E) is the same for every i, and averaging over i,
because PXn(a) is bounded and converges in probability to P∗(a) under the conditional distribution.
∎
The same argument, with a little more work, proves that (X1,…,Xk) conditional on E converge to k independent copies of P∗ for each fixed k. For the fair die with mean at least 4, tilting gives P∗∝e0.1746a, that is, 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 is (0.100,0.121,0.145,0.174,0.209,0.251). Rolls do not concentrate on {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∼iidQ and want to decide between H0:Q=P0 and H1:Q=P1. A test is an acceptance region An⊆Xn (accept H0 if xn∈An), with the two errors
αn=P0n(Anc)(type I),βn=P1n(An)(type II).
The Neyman–Pearson lemma says that, for a given level αn, the test minimizing βn accepts H0 when the likelihood ratio P0n(xn)/P1n(xn) 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, log2Pkn(xn)=−n(H(Pxn)+KL(Pxn∥Pk)), and subtraction cancels entropy:
The Neyman–Pearson test accepts H0 when the sample type is sufficiently closer to P0 than to P1, with KL measuring closeness. Since the difference is ∑aPxn(a)log2P1(a)P0(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) and ask how quickly type II error can fall. Write βnε=min{P1n(An):An⊆Xn,αn≤ε} for the best possible type II error with n observations.
The Chernoff–Stein lemma gives KL its cleanest operational interpretation: KL(P0∥P1) 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 ε: requiring αn≤0.05 or αn≤10−9 makes no difference to first order in the exponent.
Proof
For δ>0 define the relatively typical sequences, those whose average log ratio is close to its expectation under P0:
Under P0, the average log ratio is an average of iid variables log2P1(Xi)P0(Xi) with expectation KL(P0∥P1)=D (finite, and the variables are bounded on the finite alphabet), so by the weak law of large numbersP0n(Anδ)→1.
Converse (no test does better). Let Bn be any acceptance region with P0n(Bnc)≤ε. On Anδ we have P1n(xn)≥P0n(xn)2−n(D+δ), hence
The parenthesis tends to 1−ε>0, so liminfnn1log2βnε≥−D−δ for every δ>0.
Achievability (a particular test attains it). Using Anδ itself as the acceptance region gives limsupnn1log2βnε≤−D+δ; you will prove it in the second guided exercise. Combining both parts and taking δ→0 yields the limit.
∎
Why does KL(P0∥P1) appear instead of KL(P1∥P0)? Because to keep type I error bounded, the acceptance region must contain nearly all the mass of P0, namely sequences with type near P0. Type II error is the probability under P1 of those sequences, and by Sanov it is ≐2−nKL(P0∥P1): the “rare event” for P1 is looking like P0. 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 k1∑i≤klog2P1(Xi)P0(Xi) versus k
samples from H0: Xi∼P0
samples from H1: Xi∼P1
Exact type II error exponent with αn=ε
KL(P0∥P1)0.7370 bits
KL(P1∥P0)0.5310 bits
Chernoff information C0.1621 bits (λ* = 0.54)
β100 and β10005.8·10⁻¹⁷ and 3.9·10⁻²⁰⁰
n1log2βn at n=1000−0.6624 versus −0.7370
Minimum n with βn≤10−643 (naive: log₂10⁶/D = 27.0)
The magenta curve approaches −KL(P0∥P1) slowly, with an order-1/n offset depending on ε; the asymptote does not. The asymptotes differ: which hypothesis you protect changes the rate.
Testing H0:Xi∼Bern(p0) against H1:Xi∼Bern(p1). The first panel shows the average log likelihood ratio of eight simulated sequences under each hypothesis: blue ones head for KL(P0∥P1) and orange ones for −KL(P1∥P0). The second shows n1log2βn for the randomized Neyman–Pearson test with exactly αn=ε, computed without simulation using the binomial distribution, against both asymptotes. Press «Intercambiar hipótesis»: the magenta curve changes destination. Move ε 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.5, p1=0.1 and ε=0.05, KL(P0∥P1)=0.737 bits and KL(P1∥P0)=0.531 bits. The empirical exponent is −0.540 at n=100 and −0.662 at n=1000: it converges, but slowly. The reason is a second-order term calculated by Strassen in 1962:
where Φ is the standard normal distribution function. For ε<1/2, Φ−1(ε)<0 and the term of order nworsens the error relative to 2−nD. In the example, V=2.51 and with n=1000 the formula gives −654.5 versus the exact −662.4. The practical effect is large: the minimum n with βn≤10−6 is 43, while the naive calculation log2(106)/D gives 27.
Bayesian error and Chernoff information
If instead of fixing αn we minimize total error with prior probabilities π0,π1>0, Pe(n)=π0αn+π1βn, both errors must tend to zero together and the optimal exponent is different: Chernoff information,
which does not depend on the priors. Geometrically, the optimal Bayesian boundary in the simplex is {P:KL(P∥P0)=KL(P∥P1)}, the cheapest point of that boundary is the geometric mixture Pλ∗∝P0λ∗P11−λ∗, and C=KL(Pλ∗∥P0)=KL(Pλ∗∥P1). Since Pλ∗ lies “between” the two, C≤min{KL(P0∥P1),KL(P1∥P0)}: in the example, C=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θ from pθ+δ when δ is small? By Stein, the answer depends on KL(pθ∥pθ+δ), and that KL has a universal quadratic form.
Proof
Let f(δ)=KL(pθ∥pθ+δ)=Eθ[logpθ(X)]−Eθ[logpθ+δ(X)]. Apply multivariable Taylor expansion around δ=0. First, f(0)=0. The gradient is ∇f(0)=−Eθ[∇θlogpθ(X)]=−∑x∇θpθ(x)=−∇θ∑xpθ(x)=0: the score has zero mean. The Hessian is ∇2f(0)=−Eθ[∇θ2logpθ(X)], and since ∇2logp=p∇2p−∇logp∇logp⊤ and Eθ[∇2pθ/pθ]=∇2∑xpθ(x)=0, we get ∇2f(0)=I(θ). Taylor’s formula with Peano remainder gives the result. For the other direction, g(δ)=KL(pθ+δ∥pθ) also satisfies g(0)=0, ∇g(0)=0 and ∇2g(0)=∑xpθ(x)∇pθ(x)∇pθ(x)⊤=I(θ).
∎
This Fisher metric induced by KL gives parameter space its own geometry: infinitesimally, KL is half the square of a distance, 21∥δ∥I(θ)2, 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 21∑aδa2/pa is the Fisher metric of the multinomial family.
Two useful examples. For Bern(θ), the score is θ(1−θ)x−θ and I(θ)=θ(1−θ)1: distinguishing coins near θ=0 is much easier than near 0.5. For the Gaussian with θ=(μ,σ), I(θ)=diag(1/σ2,2/σ2), and the exact KL is from the Gaussian lesson:
With σ=σ0 it is exactly (μ−μ0)2/(2σ02): in the mean direction Fisher’s approximation is exact. In the scale direction, with μ=μ0 and σ=σ0(1+u), expansion gives KL(pθ0∥pθ)=u2−35u3+O(u4), whereas KL(pθ∥pθ0)=u2−31u3+O(u4): both directions share the quadratic term, 21⋅σ022(σ0u)2=u2, and asymmetry appears in the cubic term.
InteractiveKL up close
exact KL level c
ellipse 21δ⊤I(θ0)δ=c
KL bands: 0.02, 0.1, 0.25, 0.5, 1 and 2 nats
The two densities: pθ0 (blue) and pθ (orange)
Divergence
θ0=(μ0,σ0)(−0.80, 1.00)
θ=(μ,σ)(−0.50, 1.15)
Fisher I(θ0)diag(1.00, 2.00)
Exact KL KL(pθ0∥pθ)0.0519 nats
Quadratic 21δ⊤I(θ0)δ0.0675 nats
KL in the other direction0.0665 nats
Relative error: 30.2%. The quadratic form begins to fail, especially in the σ direction.
The parameter plane (μ,σ) of a Gaussian. Bands are levels of the exact KL between pθ0 (blue) and pθ (orange), in nats. The thick curve is level c and the dashed ellipse the same level of the approximation 21δ⊤I(θ0)δ. With small c the two nearly coincide; raise c and see how the exact curve deforms. Drag θ 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 toward small σ: 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:θ against H1:θ+δ with n observations (one parameter). By Stein, type II error behaves like exp(−n21δ2I(θ)), so making it small requires nδ2I(θ)≳1: the smallest separation detectable with n observations is of order 1/nI(θ). This is the same scale as the Cramér–Rao bound, which says no unbiased estimator has standard deviation below 1/nI(θ). These are two views of the same fact: estimating θ to precision δ is equivalent to distinguishing θ from θ±δ.
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 to21δ⊤I(θ)δ=ε,
Lagrange multipliers give δ∗=−2ε/∇L⊤I−1∇LI(θ)−1∇L(θ). 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) exists and simulation is needed. Naive Monte Carlo generates N samples from Qn and counts those in E. If p=Qn(E), the estimator p^=N1∑j1[Xn,(j)∈E] is unbiased with relative error
pVar(p^)=Np1−p,
so about 100/p samples are needed for 10% relative error. With p≐2−nD∗, cost grows exponentially in n. As seen in the Sanov figure, with 1,000 samples naive Monte Carlo stops seeing the event once p drops below 10−3.
Importance sampling generates samples from another distribution R and corrects with the likelihood ratio:
which is unbiased whenever R gives positive mass wherever Q does. The ideal proposal, which has zero variance, is the conditional Qn(⋅∣E), unusable because its normalizing constant is precisely p. But the conditional limit theorem says what it resembles: P∗n. Thus the natural choice is R=P∗, the exponential tilt of Q. The note on convex sets already gave the needed bound: on E, the weight satisfies P∗n(xn)Qn(xn)≤2−nD∗. Therefore
Since p≐2−nD∗, the ratio 2−nD∗/p grows only subexponentially (as 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∗ 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), all bounds hold, and the actual maximum gap is much smaller than the theoretical one: with n=80, 0.083 bits versus 0.238. The bound (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 λ, 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.254 at n=10 to 0.1193 at n=104, against the limit 0.1187: after ten thousand flips half a millibit remains, the trace of the 1/n factor. The die’s conditional distribution approaches P∗ with a divergence falling by one order of magnitude whenever n is multiplied by four or five.
The Stein test, using the exact Neyman–Pearson test. For two Bernoulli distributions, the number of ones K is a sufficient statistic and the likelihood ratio is monotone in K, so the optimal test rejects H0 when K is on the P1 side and randomizes at the boundary to make αn exactly ε.
[ ]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=1000 the exponent is −0.662 when protecting H0=Bern(0.5) and −0.488 when roles are swapped, heading toward −0.737 and −0.531. The effect of ε at finite n is enormous even though it disappears in the limit: −0.595 with ε=0.001 versus −0.743 with ε=0.5. The latter is below −D, as predicted by Strassen’s term with Φ−1(0.5)=0: only the logarithmic correction remains.
Finally, importance sampling for the die: P(Xˉ100≥4.5), equal to 1.5×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, ∏iP∗(xi)Q(xi)=e−λ∗Sn+nΛ(λ∗), and on the event never exceeds 2−nD∗: the maximum observed weight matches the bound, attained by sequences exactly at the boundary Sn=na.
The library version
SciPy provides almost everything above: binomial tails in log scale (stats.binom.logsf), the contribution pln(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)−21log2n converges to −0.607, the Bahadur–Rao constant for a lattice variable: excess exponent is not noise but exactly n21log2n+const. The numerical Hessian reproduces diag(1/σ2,2/σ2) to six digits, and for Bernoulli the quadratic approximation is excellent up to δ=0.1 (2% error) and poor at δ=0.4 (37%).
Common mistakes
Exercises
ProofProbability of a type class
Prove: For every P∈Pn and distribution Q on an alphabet of m symbols, (n+1)−m2−nKL(P∥Q)≤Qn(T(P))≤2−nKL(P∥Q).
0
You have two results: if xn∈T(P), then Qn(xn)=2−n(H(P)+KL(P∥Q)); and the distribution's own type class is most probable, Pn(T(P))≥Pn(T(P^)) for every P^∈Pn.
Step 1 of 4. How do you write Qn(T(P))?
ProofStein: a test achieving the exponent
Prove: Let P0,P1 be distributions on a finite alphabet with D=KL(P0∥P1)<∞, ε∈(0,1) and δ>0. Then limsupnn1log2βnε≤−D+δ.
0
Use as acceptance region the relatively typical sequences An={xn:D−δ≤n1log2P1n(xn)P0n(xn)≤D+δ}.
Step 1 of 4. Why does this test's type I error, αn=P0n(Anc), eventually fall below ε?
NumericThe coin's Sanov exponent
Flip a fair coin n times. Calculate, in bits, the exponent D∗ such that P(frequency of heads≥0.7)≐2−nD∗.
NumericFisher information of a coin
Calculate the Fisher information I(θ) of a Bern(θ) at θ=0.5 (using the natural logarithm, as usual).
NumericHow quickly does type II error fall?
You test H0:Xi∼Bern(0.5) against H1:Xi∼Bern(0.1) with type I error bounded by ε=0.05. How many bits per observation does the best test gain in type II error, that is, what is −limnn1log2βnε?
QuizThe order of arguments
Which arguments correctly explain why, with type I error bounded, the type II error exponent is KL(P0∥P1) rather than KL(P1∥P0)?
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 n iid samples and deciding between two regimes, P0 and P1, equally likely a priori. You want average error probability 21αn+21βn below 10−6. Which quantity determines the required n 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≥0 with E[Zj]=P(Xˉn≥a) for Xi∼iidBern(p) and a>p. Sample from the tilted distribution, which for a Bernoulli is Bern(a), and reweight each sample by ∏iQ(xi)/P∗(xi). Note the weight depends only on the number of ones K, so sampling K∼Bin(n,a) suffices. Compute the weight in log scale: with n=1000 the probability is of order 10−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); 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 types; the class of P has ≐2nH(P) sequences, each with probability 2−n(H(P)+KL(P∥Q)) under Qn, and the whole class receives Qn(T(P))≐2−nKL(P∥Q), with explicit bounds for each n.
Sanov.P(PXn∈E)≐2−nminP∈EKL(P∥Q). For a constraint on a mean, the minimizer is the exponential tilt Qλ∝Qeλg and the exponent is Cramér’s rate function: the Chernoff bound is Sanov on a half-space. For convex E 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∗ and each observation follows P∗. With uniform Q, P∗ is the maximum-entropy distribution.
Chernoff–Stein. With type I error bounded, the best type II error decays as 2−nKL(P0∥P1), independently of ε; Bayesian error decays more slowly, as 2−nC(P0,P1). At finite n, Strassen’s correction of order n matters.
Local geometry.KL(pθ∥pθ+δ)=21δ⊤I(θ)δ+o(∥δ∥2): Fisher information is the metric induced by KL, sets the Cramér–Rao scale 1/nI and defines the natural gradient. Far from the expansion point the approximation fails asymmetrically.
Rare-event simulation. Naive Monte Carlo needs ≈100/p samples; tilting toward P∗ and reweighting bounds the event weight by 2−nD∗ and makes relative error polynomial in n.