Module contents
Lesson 4 of 19Core 100 min

Asymptotic equipartition, typical sets and entropy rate

Apply the law of large numbers to −(1/n) log p(Xⁿ) to show that nearly all probability concentrates on about 2^(nH) typical sequences. Prove the fixed-length block source-coding theorem, then extend entropy to processes with memory. A language model’s loss upper-bounds the entropy rate.

After this lesson you can

  • State and prove the AEP for i.i.d. sources using the weak law of large numbers.
  • Prove that the typical set has probability tending to 1 and size between (1−ε)2^(n(H−ε)) and 2^(n(H+ε)).
  • Prove achievability and the converse of the fixed-length source-coding theorem.
  • Compute the entropy rate of a stationary Markov chain.
  • Explain why the most probable sequence need not be typical and what this means for sampling from generative models.

Before you start

Motivation: count sequences, not symbols

A coin yields 1 with probability p=0.1p = 0.1 and 0 with probability 0.90.9. Its entropy is h2(0.1)=0.469h_2(0.1) = 0.469 bits per toss. With 100 tosses there are 2100≈1.3⋅10302^{100} \approx 1.3 \cdot 10^{30} possible sequences and a naive code spends 100 bits naming one. But almost all these sequences practically never occur: probability piles up on about 2nH=246.9≈1.3⋅10142^{nH} = 2^{46.9} \approx 1.3 \cdot 10^{14} of them, fraction 10−1610^{-16} of the total. Reserving labels only for that small set costs about 47 bits to name a sequence, not 100.

This idea, Shannon’s (1948), explains why entropy limits compression without constructing a specific code: count sequences deserving a label. It also underlies three constantly useful facts:

  • Entropy is not just a mean: it is an exponent. 2H2^{H} is the “effective” number of source outcomes, and 2nH2^{nH} that of length-nn sequences. A language model’s perplexity, 2 raised to mean loss in bits, is the same effective choice count per token measured using the model instead of the source.
  • What happens is typical, not most probable. The individually most probable sequence (100 zeros here) almost never appears. Text generation seeking the maximum-probability sequence produces something the model’s own sampling almost never would.
  • Entropy rate sets a language model’s loss floor. For processes with memory, what is compressed and predicted is entropy rate, not isolated-symbol entropy.

The lesson begins by counting in the visible binary case. It then states and proves the asymptotic equipartition property, generalizing counting to any memoryless source. Typical sets and the source coding theorem (with converse) follow. Then the most-probable versus typical paradox and finally processes with memory. Unless stated otherwise, log⁡\log is base-2 logarithm and quantities are in bits.

Counting versus weighing

Let X1,…,Xn∼iidBern(p)X_1, \dots, X_n \iid \mathrm{Bern}(p), with q=1−pq = 1 - p. Sequence xn=(x1,…,xn)x^n = (x_1, \dots, x_n) with kk ones has probability pkqn−kp^k q^{n-k}, depending only on kk. Two things compete:

  1. How many sequences have kk ones: (nk)\binom{n}{k} (the combinatorial count).
  2. How much each weighs: pkqn−k=2−n c(κ)p^k q^{n-k} = 2^{-n\,c(\kappa)}, with κ=k/n\kappa = k/n the fraction of ones and
c(κ)=−κlog⁡p−(1−κ)log⁡qc(\kappa) = -\kappa \log p - (1 - \kappa) \log q

the per-symbol cost of each sequence in that class. It is a straight line in κ\kappa.

The first factor has exponential size bounded without approximations.

Proof

Upper bound. With 0<κ<10 < \kappa < 1, the binomial theorem gives 1=(κ+(1−κ))n≥(nk)κk(1−κ)n−k1 = (\kappa + (1 - \kappa))^n \ge \binom{n}{k} \kappa^k (1 - \kappa)^{n-k}, and κk(1−κ)n−k=2−nh2(κ)\kappa^k (1 - \kappa)^{n-k} = 2^{-n h_2(\kappa)}. Rearranging gives the bound. Cases k=0,nk = 0, n are trivial ((nk)=1=20\binom{n}{k} = 1 = 2^{0}).

Lower bound. In distribution Bin(n,κ)\mathrm{Bin}(n, \kappa) the most probable value is k=κnk = \kappa n: the ratio of consecutive terms P(j+1)P(j)=(n−j) κ(j+1)(1−κ)\frac{\Pr(j+1)}{\Pr(j)} = \frac{(n-j)\,\kappa}{(j+1)(1-\kappa)} exceeds 1 if and only if j<(n+1)κ−1j < (n+1)\kappa - 1, and since (n+1)κ=k+κ(n+1)\kappa = k + \kappa with 0<κ<10 < \kappa < 1, terms rise to j=kj = k and fall afterward. There are n+1n + 1 possible values summing to 1, so that term is at least 1n+1\frac{1}{n+1}: (nk)κk(1−κ)n−k≥1n+1\binom{n}{k}\kappa^k(1-\kappa)^{n-k} \ge \frac{1}{n+1}. Rearranging gives the other inequality.

∎

(Stirling’s formula gives the same result with precise correction (nk)≈2nh2(κ)/2πnκ(1−κ)\binom{n}{k} \approx 2^{n h_2(\kappa)} / \sqrt{2\pi n \kappa (1-\kappa)}, but the bounds above suffice for the exponential argument and hold for every nn.)

Combining both factors, total mass of the class of sequences with kk ones is

P(K=k)=(nk)pkqn−k≈2 n [ h2(κ)−c(κ) ].\Pr(K = k) = \binom{n}{k} p^k q^{n-k} \approx 2^{\,n\,[\,h_2(\kappa) - c(\kappa)\,]} .

Exponent h2(κ)−c(κ)h_2(\kappa) - c(\kappa) is minus a divergence: expanding gives c(κ)−h2(κ)=κlog⁡κp+(1−κ)log⁡1−κq=KL⁡(Bern(κ) ∥ Bern(p))c(\kappa) - h_2(\kappa) = \kappa \log\frac{\kappa}{p} + (1-\kappa)\log\frac{1-\kappa}{q} = \KL(\mathrm{Bern}(\kappa)\,\|\,\mathrm{Bern}(p)), Kullback–Leibler divergence. The two bounds give 1n+12−nKL⁡(κ∥p)≤P(K=k)≤2−nKL⁡(κ∥p)\frac{1}{n+1}2^{-n\KL(\kappa\|p)} \le \Pr(K = k) \le 2^{-n\KL(\kappa\|p)}: class mass decays exponentially with its divergence from pp. The figure shows it: curve h2(κ)h_2(\kappa) counts, line c(κ)c(\kappa) weighs, and their vertical gap is divergence. The line is tangent to the curve exactly at κ=p\kappa = p, where almost all mass lives.

InteractiveWhere probability lives
Weigh: mass P(K=k)\Pr(K = k) of each class (number kk of ones), n=100n = 100
0.130κ = pall 0Counting versus weighing, in bits per symbol012300.250.50.751κ = k/n, fraction of onesH ± εD = 0.15
  • 1nlog⁡2\frac{1}{n}\log_2 (class sequence count) ≈h2(κ)\approx h_2(\kappa)
  • cost per symbol of each, −1nlog⁡2p(xn)-\frac{1}{n}\log_2 p(x^n)
  • typical window
  • gap D(κ∥p)D(\kappa\|p) for inspected class
0.10
100
0.10
0.000
Typical-set mass P(Aε)\Pr(A_\varepsilon)0.7590
1nlog⁡2∣Aε∣\frac{1}{n}\log_2\abs{A_\varepsilon}0.529
1nlog⁡2\frac{1}{n}\log_2 of minimum with prob. ≥0.9\ge 0.90.547
h2(p)h_2(p)0.469
Most likely sequence (all 0)2−15.22^{−15.2}
Typical sequence2−46.92^{−46.9}
Class κ=0.000\kappa = 0.000: sequences20.02^{0.0}
Inspected class: total mass2−15.22^{−15.2}
Is it typical?no
Move the inspected class from κ=0\kappa = 0 to κ=p\kappa = p: the individual sequence goes from most likely to one among 2nH2^{nH}.
Above, mass P(K=k)\Pr(K = k) of each sequence class (by count kk of ones) for a coin with bias pp; green classes contain typical sequences. Below, the same story in bits per symbol: blue curve counts sequences per class (1nlog⁡2\frac{1}{n}\log_2 of the count), orange line is each one's per-symbol cost, and magenta gap KL⁡(κ ∥ p)\KL(\kappa\,\|\,p). Start with inspected class κ=0\kappa = 0 (most probable sequence, red point): lowest cost of all yet tiny mass because it is one sequence. Drag class to κ=p\kappa = p and watch the gap vanish. Increase nn from 10 to 2000: the peak sharpens and typical window retains all mass while 1nlog⁡2∣Aε∣\frac{1}{n}\log_2|A_\varepsilon| stabilizes somewhat above h2(p)h_2(p) (and below h2(p)+εh_2(p) + \varepsilon). The minimum set of mass 0.9 approaches h2(p)h_2(p) much more slowly (from above, with an order-1/n1/\sqrt{n} term).

Three readings of the figure proved generally in the rest of the lesson:

  1. Concentration. Mass concentrates in classes with κ\kappa near pp, and that region’s width shrinks as 1/n1/\sqrt{n}. This is a law of large numbers.
  2. Equipartition. All sequences in classes near κ=p\kappa = p have per-symbol cost near HH: they weigh almost the same on exponential scale, 2−nH2^{-nH}.
  3. The most probable does not count. All zeros has minimum cost (0.152 bits per symbol for p=0.1p = 0.1, versus H=0.469H = 0.469), but class mass is “number of sequences times weight of each”, and that class has one. Individually most probable and almost-sure behavior differ.

The asymptotic equipartition property

For binary sources a tangent line sufficed. Generally a sequence’s per-symbol cost is the average of symbol surprises, and iid averages concentrate.

Let X1,X2,…X_1, X_2, \dots be iid random variables with distribution pp on finite alphabet X\mathcal{X}, and p(xn)=∏i=1np(xi)p(x^n) = \prod_{i=1}^n p(x_i). By independence log⁡1p(Xn)=∑ilog⁡1p(Xi)\log\frac{1}{p(X^n)} = \sum_i \log\frac{1}{p(X_i)} is a sum of iid variables, each with surprise −log⁡p(Xi)-\log p(X_i) and common mean entropy H=H⁡(X)H = \Ent(X).

Proof

Variables Yi=−log⁡p(Xi)Y_i = -\log p(X_i) are iid, functions of iid variables. Each YiY_i takes finitely many values (p(Xi)>0p(X_i) > 0 with probability 1, and the alphabet is finite), so has finite mean and variance: E[Yi]=H⁡(X)\E[Y_i] = \Ent(X) and Var⁡[Yi]=V<∞\Var[Y_i] = V < \infty. Since Zn=1n∑i≤nYiZ_n = \frac{1}{n}\sum_{i \le n} Y_i, the weak law of large numbers gives Zn→E[Y1]=H⁡(X)Z_n \to \E[Y_1] = \Ent(X) in probability (convergence in probability). The quantitative bound is Chebyshev’s inequality applied to ZnZ_n, with mean H⁡(X)\Ent(X) and variance V/nV/n.

∎

The name comes from concentration: sequences actually appearing have almost identical probability on exponential scale, ≈2−nH\approx 2^{-nH}: probability is “equipartitioned” among them. Notice how little was used: only finite surprise variance and independent identically distributed observations. In the next figure verify this and especially see what happens when an assumption fails.

InteractiveAEP live
Surprise per symbol Zn=−1nlog⁡2p(X1,…,Xn)Z_n = -\frac{1}{n}\log_2 p(X_1, \dots, X_n) in 50 sequences, in bits
00.511.52150100150200250300length nH
  • 50 sequences ZnZ_n
  • theoretical limit
  • band ±ε\pm\varepsilon
  • envelope H±2V/nH \pm 2\sqrt{V/n}
Source
0.20
0.10
300
Marginal entropy H⁡(X1)\Ent(X_1)0.722 bits
Entropy rate0.722 bits
Mean ZnZ_n at n=300n = 3000.724 bits
Standard deviation of ZnZ_n0.047 bits
Inside the band (300 sequences)96 %
Chebyshev bound 1−V/(nε2)1 - V/(n\varepsilon^2)79 %
Paths narrow as V/n\sqrt{V/n} with V=0.640V = 0.640 (varentropy). Increase maximum nn and check that the fraction in the band approaches 1.
Each blue line is a realization of Zn=−1nlog⁡2p(X1,…,Xn)Z_n = -\frac{1}{n}\log_2 p(X_1, \dots, X_n) as nn grows (50 sequences drawn, 300 measured for readouts). The green band is ±ε\pm\varepsilon around the limit. With the iid source lines narrow within envelope H±2V/nH \pm 2\sqrt{V/n} (width decreases as n−1/2n^{-1/2}) and the fraction inside the band exceeds the very conservative Chebyshev bound. Switch to Markov: initially each isolated symbol has entropy 1 bit, but trajectories converge to another value. Which, and what quantity is it? Finally switch to the mixture (one coin chosen initially and used throughout): does it converge to one value?

With initial iid source (p=0.2p = 0.2), H=0.722H = 0.722 bits and V=0.64V = 0.64; at n=300n = 300 tosses standard deviation of ZnZ_n is about V/n=0.046\sqrt{V/n} = 0.046 bits, and almost all lines are within band ±0.1\pm 0.1. With the figure’s Markov chain (each symbol changes with probability 0.10.1 from the previous), 0 and 1 are equally likely and H⁡(X1)=1\Ent(X_1) = 1 bit, but ZnZ_n converges to 0.4690.469: not each symbol’s entropy, but how surprising each symbol is given its predecessor. This is entropy rate in later sections. The mixture shows there need not even be one limit: without ergodicity classical AEP fails (revisited at the end).

The typical set

AEP says which sequences to expect. To count them define the set satisfying the property.

It is a set of sequences (∣X∣n\abs{\mathcal{X}}^n possible), defined by each one’s probability, not “typical values”. Look at the earlier figure’s lower part: for Bernoulli, xnx^n is typical exactly when cost c(k/n)c(k/n) falls in band H⁡(X)±ε\Ent(X) \pm \varepsilon, and since cc is linear this means ∣k/n−p∣≤ε/∣log⁡(q/p)∣\abs{k/n - p} \le \varepsilon / \abs{\log(q/p)} (for p≠1/2p \ne 1/2). With p=0.1p = 0.1 and ε=0.1\varepsilon = 0.1 this is the figure’s window 0.0685≤k/n≤0.13150.0685 \le k/n \le 0.1315.

Proof
  1. By definition, xn∈Aε(n)x^n \in A_\varepsilon^{(n)} if and only if ∣Zn(xn)−H∣≤ε\abs{Z_n(x^n) - H} \le \varepsilon. Complement probability is, by quantitative AEP, ≤V/(nε2)\le V/(n\varepsilon^2). For n>V/ε3n > V/\varepsilon^3 this is below ε\varepsilon.

  2. Each xn∈Aε(n)x^n \in A_\varepsilon^{(n)} has p(xn)≥2−n(H+ε)p(x^n) \ge 2^{-n(H + \varepsilon)} and total mass is at most 1:

1  ≥  ∑xn∈Aε(n)p(xn)  ≥  ∣Aε(n)∣ 2−n(H+ε).1 \;\ge\; \sum_{x^n \in A_\varepsilon^{(n)}} p(x^n) \;\ge\; \abs{A_\varepsilon^{(n)}}\, 2^{-n(H+\varepsilon)} .
  1. Each xn∈Aε(n)x^n \in A_\varepsilon^{(n)} has p(xn)≤2−n(H−ε)p(x^n) \le 2^{-n(H - \varepsilon)}, so by part 1,
1−Vnε2  ≤  P(Aε(n))  =  ∑xn∈Aε(n)p(xn)  ≤  ∣Aε(n)∣ 2−n(H−ε).1 - \frac{V}{n\varepsilon^2} \;\le\; \Pr\big(A_\varepsilon^{(n)}\big) \;=\; \sum_{x^n \in A_\varepsilon^{(n)}} p(x^n) \;\le\; \abs{A_\varepsilon^{(n)}}\, 2^{-n(H - \varepsilon)} .∎

Part 2 uses nothing asymptotic (only probabilities summing to 1), while 1 needs large nn. With fixed ε\varepsilon, combining gives 1nlog⁡∣Aε(n)∣∈[H−ε−o(1), H+ε]\frac{1}{n}\log\abs{A_\varepsilon^{(n)}} \in [H - \varepsilon - o(1),\, H + \varepsilon]: the typical set has about 2nH2^{nH} elements on exponential scale. For the p=0.1p = 0.1 coin and ε=0.1\varepsilon = 0.1 exact calculation gives (reproduced in implementation):

nnP(Aε)\Pr(A_\varepsilon)1nlog⁡2∣Aε∣\frac{1}{n}\log_2\abs{A_\varepsilon}nHn H
100.3870.3324.7
1000.7590.52946.9
3000.9340.545140.7
10000.9990.556469.0
20001.0000.559938.0

Two points deserve attention. First, AEP is asymptotic: at n=100n = 100 the typical set retains only 76% mass, and Chebyshev requires n>V/ε3≈905n > V/\varepsilon^3 \approx 905 to ensure 90% when reality achieves it for all n≥267n \ge 267. Bounds are true but very conservative for small nn, and mass does not even grow monotonically: with n=30n = 30 the window contains only class k=3k = 3 and retains 24 %24\,\%, less than n=10n = 10. Second, ratio 1nlog⁡∣Aε∣\frac{1}{n}\log|A_\varepsilon| does not tend to HH: with fixed ε\varepsilon the typical set includes classes costing more than HH, which are more numerous, and count is dominated by the window’s largest class at edge κmax⁡=p+ε/log⁡(q/p)=0.1315\kappa_{\max} = p + \varepsilon/\log(q/p) = 0.1315. The limit is h2(κmax⁡)=0.562h_2(\kappa_{\max}) = 0.562, below H+ε=0.569H + \varepsilon = 0.569 exactly at KL⁡(κmax⁡ ∥ p)=0.007\KL(\kappa_{\max}\,\|\,p) = 0.007: that class’s cost is H+εH + \varepsilon, and its count is cost minus divergence. To approach HH let ε→0\varepsilon \to 0 as nn grows, or use the minimum set of given probability studied next.

The typical set is a tiny fraction of full space: if pp is nonuniform,

∣Aε(n)∣∣X∣n≤2−n(log⁡∣X∣−H−ε)=2−n(KL⁡(p ∥ u)−ε),\frac{\abs{A_\varepsilon^{(n)}}}{\abs{\mathcal{X}}^n} \le 2^{-n(\log\abs{\mathcal{X}} - H - \varepsilon)} = 2^{-n(\KL(p\,\|\,u) - \varepsilon)} ,

with uu uniform (lesson 2 showed KL⁡(p ∥ u)=log⁡∣X∣−H⁡(p)\KL(p\,\|\,u) = \log\abs{\mathcal{X}} - \Ent(p)). For ε<KL⁡(p ∥ u)\varepsilon < \KL(p\,\|\,u) that fraction tends to 0 exponentially even as set probability tends to 1. This enables compression.

The source coding theorem

A block of nn symbols is encoded with a fixed number of bits. A block code of rate RR and length nn is a pair of functions: encoder fn:Xn→{1,…,Mn}f_n : \mathcal{X}^n \to \{1, \dots, M_n\} with Mn=⌈2nR⌉M_n = \lceil 2^{nR} \rceil labels (i.e. ⌈nR⌉\lceil nR\rceil bits, RR bits per source symbol) and decoder gn:{1,…,Mn}→Xng_n : \{1, \dots, M_n\} \to \mathcal{X}^n. Its error probability is Pe(n)=P(gn(fn(Xn))≠Xn)P_e^{(n)} = \Pr\big(g_n(f_n(X^n)) \ne X^n\big). If R<log⁡∣X∣R < \log\abs{\mathcal{X}} there are far fewer labels than sequences (Mn≪∣X∣nM_n \ll \abs{\mathcal{X}}^n) and the code must give some up; which rates RR allow negligible error?

Proof

Achievability. Let ε=(R−H)/2>0\varepsilon = (R - H)/2 > 0, so H+ε<RH + \varepsilon < R. By property 2, ∣Aε(n)∣≤2n(H+ε)\abs{A_\varepsilon^{(n)}} \le 2^{n(H+\varepsilon)}, less than 2nR≤Mn2^{nR} \le M_n whenever 2n(R−H−ε)≥12^{n(R - H - \varepsilon)} \ge 1, i.e. always (with exponentially growing slack). Number typical-set elements with labels 1,…,∣Aε(n)∣1, \dots, \abs{A_\varepsilon^{(n)}} and map remaining sequences to any label. The decoder returns the numbered sequence. Failure occurs only outside the typical set:

Pe(n)≤P((Aε(n))c)≤Vnε2⟶0.P_e^{(n)} \le \Pr\big((A_\varepsilon^{(n)})^c\big) \le \frac{V}{n\varepsilon^2} \longrightarrow 0 .

Converse. Let ε=(H−R)/2>0\varepsilon = (H - R)/2 > 0. A code with MnM_n labels correctly decodes at most a set BB of ∣B∣≤Mn≤2nR+1\abs{B} \le M_n \le 2^{nR} + 1 sequences. Success probability is therefore at most

P(Xn∈B)≤P((Aε(n))c)+P(B∩Aε(n))≤Vnε2+∣B∣ 2−n(H−ε)≤Vnε2+(2nR+1) 2−n(H−ε).\Pr(X^n \in B) \le \Pr\big((A_\varepsilon^{(n)})^c\big) + \Pr\big(B \cap A_\varepsilon^{(n)}\big) \le \frac{V}{n\varepsilon^2} + \abs{B}\,2^{-n(H - \varepsilon)} \le \frac{V}{n\varepsilon^2} + (2^{nR} + 1)\,2^{-n(H-\varepsilon)} .

The last summand is 2−n(H−R−ε)+2−n(H−ε)=2−n(H−R)/2+2−n(H−ε)→02^{-n(H - R - \varepsilon)} + 2^{-n(H-\varepsilon)} = 2^{-n(H-R)/2} + 2^{-n(H - \varepsilon)} \to 0. Thus success tends to 0 and Pe(n)→1P_e^{(n)} \to 1.

∎

The theorem says that entropy is the compression threshold for block codes: above it, error vanishes; below it, error becomes almost certain (a “strong” converse, stronger than the weak version saying only that error cannot be small). The figure computes the error probability of the best possible code, exactly for a Bernoulli source: with 2nR2^{nR} labels, the optimum indexes the 2nR2^{nR} most probable sequences, and error is one minus the mass of that set.

InteractiveThe compression threshold
Error probability of the best block code with 2nR2^{nR} codewords
00.250.50.75100.250.50.751rate R (bits per symbol)R < H: error → 1R > H: error → 0H = 0.469n = 100
  • best code for selected block nn
  • other lengths (darker = longer)
  • point (R,Pe)(R, P_e)
0.10
0.55
Block length nn
Error axis
Entropy h2(p)h_2(p)0.469 bits
Bits per block nRnR55.0 of 100
Best code error0.0917
Error indexing AεA_\varepsilon, ε=R−H\varepsilon = R - H0.404
R−HR - H0.081 bits
With R>HR > H, error decreases as nn grows: from 0.116 at n=10n = 10 to 0.0014 at n=1000n = 1000.
Error probability of the best block code with 2nR2^{nR} codewords for a Bernoulli(pp) source, as a function of rate RR, for n=10,30,100,300,1000n = 10, 30, 100, 300, 1000 (the darkest curve is the longest; the thick one is selected). As nn grows the curve sharpens into a step at R=h2(p)R = h_2(p) (dashed line). Error tends to 1 on the left and 0 on the right. With p=0.1p = 0.1 and R=0.55R = 0.55, what is the error for n=100n = 100 and n=1000n = 1000? Switch to the logarithmic axis to see the exponential decay on the right. The ‘Error indexing AεA_\varepsilon’ reading is for the code in the proof, with ε=R−H\varepsilon = R - H: worse than optimal, but with the same trend.

The figure illustrates two subtleties. First, the step has width: the transition occupies a band of width ∼V/n\sim\sqrt{V/n} around HH (at n=1000n = 1000 and p=0.1p = 0.1, about 0.030.03 bits), and exactly at R=HR = H error tends neither to 0 nor to 1. A classical refinement (Strassen, 1962; Kontoyiannis and Verdú, 2014) gives the minimum size of a set of probability 1−δ1 - \delta: log⁡M∗(n,δ)≈nH+nV Q−1(δ)−12log⁡n\log M^\ast(n, \delta) \approx nH + \sqrt{nV}\,Q^{-1}(\delta) - \tfrac12 \log n, where Q−1Q^{-1} is the inverse normal tail. With p=0.1p = 0.1, n=1000n = 1000 and δ=0.1\delta = 0.1 it gives 468.996+38.54−4.98=502.6468.996 + 38.54 - 4.98 = 502.6 bits, versus the exact value 501.1501.1 shown by the minimum-set reading in the first figure. Second, the best code is not the one in the proof, but the proof suffices for the limit.

This theorem concerns fixed length and small error. The variable-length, zero-error version needs prefix codes (Kraft inequality, Huffman) and yields average length per symbol between HH and H+1/nH + 1/n when encoding blocks of nn symbols; lesson 5 develops it. Arithmetic coding in lesson 7 achieves this without enumerating anything. All of this returns from another angle in the method of types (lesson 16), which gives the exact exponent of the error probability.

The most probable sequence is not typical

Return to the coin with p=0.1p = 0.1 and n=100n = 100. Three different sequences:

SequenceOnesCost per symbolProbabilityTypical (ε=0.1\varepsilon = 0.1)?
100 zeros00.1520.152 bits2−15.2≈2.7⋅10−52^{-15.2} \approx 2.7\cdot 10^{-5}no (it is the most probable)
one with 10 ones100.4690.469 bits2−46.9≈7.6⋅10−152^{-46.9} \approx 7.6\cdot 10^{-15}yes
one with 20 ones200.7860.786 bits2−78.62^{-78.6}no

The all-zero sequence is 231.7≈3.5⋅1092^{31.7} \approx 3.5 \cdot 10^{9} times more probable than any sequence with 10 ones. Even so, you will not see it: its total probability is 2.7⋅10−52.7 \cdot 10^{-5}, while the (10010)≈1.7⋅1013\binom{100}{10} \approx 1.7\cdot 10^{13} sequences with exactly 10 ones account for 13.2 %13.2\,\% of the mass. The reason is counting: each weighs a lot, but there is only one. In the figure’s notation, the most probable sequence has c(0)=log⁡(1/q)c(0) = \log(1/q), the lowest cost on the line, while its class has h2(0)=0h_2(0) = 0 bits per symbol of multiplicity.

The proof is short. The cost per symbol of x∗x^\ast is the surprise of a∗a^\ast, the minimum of the surprises −log⁡p(a)-\log p(a) on the support. HH is the average of those surprises weighted by p(a)p(a), and an average of numbers that are not all equal is strictly greater than their minimum; hence −log⁡p(a∗)<H-\log p(a^\ast) < H and x∗x^\ast lies outside the band H±εH \pm \varepsilon if ε\varepsilon is less than the gap. The ratio to typical sequences follows because their probability is at most 2−n(H−ε)2^{-n(H-\varepsilon)}, whereas p(x∗)=2nlog⁡p(a∗)p(x^\ast) = 2^{n \log p(a^\ast)}.

What this means for text generation

An autoregressive language model qq defines a distribution over token sequences, and generating means choosing a sequence. There are two radically different ways to do so:

  • Sampling (at temperature 1) produces sequences distributed according to qq: by the AEP, their surprise per token concentrates around the entropy of qq. These are typical sequences for the model.
  • Searching for the mode (greedy decoding, beam search) attempts to maximize q(xn)q(x^n). It produces sequences with abnormally low surprise per token, which the model would almost never generate itself. And because repeating what the model already considers probable minimizes surprise, text falls into loops. It is the same phenomenon as x∗x^\ast = “all zeros”, in a much larger space.

The implementation below shows this with a toy character language model. It also explains the design of many techniques: temperature, top-pp sampling by Holtzman et al. (2020), and “locally typical sampling” by Meister et al. (2022) can be understood as ways to stay in the typical set (or nearby), trimming the absurd tail without falling into the mode. In the last case, the rule chooses tokens at each step whose surprise resembles that step’s conditional entropy.

Processes with memory: entropy rate

Text, a time series or a DNA strand is not iid: each symbol depends on previous ones. The entropy of each symbol, H⁡(X1)\Ent(X_1), no longer governs compression, as the AEP figure showed. It must be replaced by a quantity measuring how much each symbol adds to what has already been seen. First, the framework: a process {Xi}\{X_i\} is stationary if, for every ss and nn, (X1,…,Xn)(X_1, \dots, X_n) and (X1+s,…,Xn+s)(X_{1+s}, \dots, X_{n+s}) have the same joint distribution.

For an iid process both equal H⁡(X1)\Ent(X_1), by the chain rule. For a stationary process they always exist and coincide.

Proof

Let an=H⁡(Xn∣Xn−1,…,X1)a_n = \Ent(X_n \mid X_{n-1}, \dots, X_1). Conditioning reduces entropy (the difference H⁡(Y∣Z)−H⁡(Y∣X,Z)\Ent(Y \mid Z) - \Ent(Y \mid X, Z) is the conditional mutual information I(X;Y∣Z)I(X; Y \mid Z), an average of Kullback-Leibler divergences and, by Gibbs’ inequality, ≥0\ge 0) and stationarity shifts the indices, so

an+1=H⁡(Xn+1∣Xn,…,X1)  ≤  H⁡(Xn+1∣Xn,…,X2)  =  H⁡(Xn∣Xn−1,…,X1)=an.a_{n+1} = \Ent(X_{n+1} \mid X_n, \dots, X_1) \;\le\; \Ent(X_{n+1} \mid X_n, \dots, X_2) \;=\; \Ent(X_n \mid X_{n-1}, \dots, X_1) = a_n .

The sequence ana_n is nonincreasing and bounded below by 0, so it converges to a limit aa: H⁡′(X)=a\Ent'(\mathcal{X}) = a exists. By the chain rule, 1nH⁡(Xn)=1n∑i=1nai\frac{1}{n}\Ent(X^n) = \frac{1}{n}\sum_{i=1}^n a_i is the Cesàro mean of a sequence converging to aa and therefore also converges to aa. Since the aia_i are nonincreasing, the mean mn=1n∑i≤naim_n = \frac{1}{n}\sum_{i \le n} a_i satisfies mn≥an≥an+1m_n \ge a_n \ge a_{n+1}, so mn+1=n mn+an+1n+1≤mnm_{n+1} = \frac{n\,m_n + a_{n+1}}{n+1} \le m_n: it too is nonincreasing, and mn≥an≥am_n \ge a_n \ge a.

∎

The last sentence is useful in practice: 1nH⁡(Xn)\frac{1}{n}\Ent(X^n) always overestimates the rate, as does H⁡(Xn∣Xn−1)\Ent(X_n \mid X^{n-1}). Each new context observation can only lower the cost. The more memory a model uses, the closer it approaches the rate from above.

Markov chains

The tractable case is a Markov chain with kk states and transition matrix P\mat{P} (Pij=P(Xt+1=j∣Xt=i)P_{ij} = \Pr(X_{t+1} = j \mid X_t = i)). It is assumed stationary: its initial law is a stationary distribution μ\mu, with μP=μ\mu\mat{P} = \mu. By the Markov property, H⁡(Xn∣Xn−1,…,X1)=H⁡(Xn∣Xn−1)\Ent(X_n \mid X_{n-1}, \dots, X_1) = \Ent(X_n \mid X_{n-1}), and by stationarity that value is H⁡(X2∣X1)\Ent(X_2 \mid X_1).

It is simple and its proof is already done: H⁡(X2∣X1)=∑iμiH⁡(X2∣X1=i)\Ent(X_2 \mid X_1) = \sum_i \mu_i \Ent(X_2 \mid X_1 = i), and given X1=iX_1 = i, X2X_2 has distribution Pi⋅P_{i\cdot}. For two states with a=P01a = P_{01} and b=P10b = P_{10}, the balance equation μ0a=μ1b\mu_0 a = \mu_1 b gives μ=(b,a)/(a+b)\mu = (b, a)/(a + b), and hence H⁡(X)=ba+bh2(a)+aa+bh2(b)\Ent(\mathcal{X}) = \frac{b}{a+b}h_2(a) + \frac{a}{a+b}h_2(b).

InteractiveEntropy rate of a Markov chain
Transition diagram: arrow thickness = PijP_{ij}, node size = μi\mu_i
0μ=0.501μ=0.500.950.050.050.95
Bits per symbol
log₂ k (bound)1.000marginal H(X₁)1.000entropy rate0.286
  • state 0 contribution μiH⁡(Pi⋅)\mu_i \Ent(P_{i\cdot})
  • from state 1
A sequence of 100 symbols from the chain
States
0.05
0.05
Stationary μ\mu(0.500, 0.500)
Marginal H⁡(X1)\Ent(X_1)1.000 bits
Rate ∑iμiH⁡(Pi⋅)\sum_i \mu_i \Ent(P_{i\cdot})0.286 bits
Value of memory0.714 bits
Ideal size relative to raw28.6 %
State changes in sample8 of 99
A compressor treating symbols separately pays 1.0001.000 bits; one using the previous state pays 0.2860.286. Memory is worth 0.7140.714 bits per symbol (71%).
Top: the transition diagram, where arrow thickness is probability PijP_{ij} and node size is stationary probability μi\mu_i. Below: three bars in bits per symbol, the maximum log⁡2k\log_2 k, marginal entropy H⁡(X1)\Ent(X_1) (red) and rate ∑iμiH⁡(Pi⋅)\sum_i \mu_i \Ent(P_{i\cdot}) (colored in segments for each state's contribution). Bottom: a sequence of 100 symbols sampled from the chain. In the initial example the marginal is uniform (1 bit) and the rate is less than one third of that: can you see the structure in the colored sequence? Try the ‘disguised i.i.d.’ example (equal rows) and verify that the rate equals the marginal there. What must you do with the three-state chain sliders to make the rate nearly 0 with marginal log⁡23\log_2 3?

Shannon–McMillan–Breiman and ergodicity

The AEP of the previous sections extends: for stationary and ergodic processes, −1nlog⁡p(X1,…,Xn)-\frac{1}{n}\log p(X_1, \dots, X_n) converges to the entropy rate almost surely. This is the Shannon–McMillan–Breiman theorem (Shannon 1948 for Markov chains, McMillan 1953 in L1L^1, Breiman 1957 almost surely). The general proof is difficult; the one for Markov chains is not.

Proof

By the Markov property, −log⁡p(Xn)=−log⁡π1(X1)−∑t=2nlog⁡PXt−1Xt-\log p(X^n) = -\log\pi_1(X_1) - \sum_{t=2}^{n}\log P_{X_{t-1}X_t}. The first term is a finite random constant and divided by nn tends to 0. The second is a sum of f(Xt−1,Xt)=−log⁡PXt−1Xtf(X_{t-1}, X_t) = -\log P_{X_{t-1} X_t}, a function of the pair chain (Xt−1,Xt)(X_{t-1}, X_t), which is irreducible on the pairs with Pij>0P_{ij}>0 and has stationary distribution μiPij\mu_i P_{ij}. By the ergodic theorem for Markov chains, 1n∑tf(Xt−1,Xt)→∑i,jμiPij (−log⁡Pij)\frac{1}{n}\sum_t f(X_{t-1}, X_t) \to \sum_{i,j}\mu_i P_{ij}\,(-\log P_{ij}) almost surely. This is the rate.

∎

The ergodicity assumption matters. Consider a process that initially chooses a coin with bias p1=0.1p_1 = 0.1 or p2=0.4p_2 = 0.4, each with probability 12\tfrac12, and uses it forever. It is stationary, and its entropy rate is the average 12(0.469+0.971)=0.720\tfrac12(0.469 + 0.971) = 0.720 bits (because H⁡(Xn)=n⋅0.720+O(1)\Ent(X^n) = n\cdot 0.720 + \bigO(1): what is “unknown” about the coin choice costs at most one bit). But no sequence converges to 0.720: each converges to 0.4690.469 or 0.9710.971, depending on the coin chosen. The process is not ergodic (one realization does not explore everything the process can do), and although the entropy rate is well defined, it is no longer what is observed. This is the mixture shown in the AEP figure.

What a language model’s loss measures

An autoregressive language model qq assigns text xnx^n probability q(xn)=∏tq(xt∣x<t)q(x^n) = \prod_t q(x_t \mid x_{<t}). Its mean loss per token on unseen text, L=−1n∑tlog⁡q(xt∣x<t)L = -\frac{1}{n}\sum_t \log q(x_t \mid x_{<t}), is −1nlog⁡q(xn)-\frac{1}{n}\log q(x^n): the same quantity as in the AEP, now using the model instead of the truth. Suppose texts come from a stationary process pp. Its expectation is a cross entropy (lesson 6 studies it in depth), and adding and subtracting log⁡p(Xn)\log p(X^n) inside the expectation separates it into entropy plus divergence:

Ep[−1nlog⁡q(Xn)]=1nH⁡(Xn)+1nKL⁡(pn ∥ qn)  ≥  1nH⁡(Xn)  ≥  H⁡(X),\E_p\Big[-\frac{1}{n}\log q(X^n)\Big] = \frac{1}{n}\Ent(X^n) + \frac{1}{n}\KL\big(p_n\,\|\,q_n\big) \;\ge\; \frac{1}{n}\Ent(X^n) \;\ge\; \Ent(\mathcal{X}) ,

where pnp_n and qnq_n are the distributions of the first nn tokens and the theorem above has been used. A model’s loss on unseen text is an upper bound on the text’s entropy rate, with a gap equal to the per-token divergence between truth and model. The better the model, the tighter the bound. Three consequences:

  • No one goes below the floor. No architectural or scale improvement can give mean loss below the entropy rate (in expectation). The constant term obtained when fitting scaling laws is often interpreted this way: as an estimate of that floor, the irreducible loss (it is an interpretation, since the fit is empirical and the value depends on the assumed functional form).
  • The reference scale. Shannon (1951), using a human text prediction experiment, bounded the rate of English (27-symbol alphabet) between 0.6 and 1.3 bits per character. Every language model now provides a concrete upper bound; lesson 8 formalizes it as bits per byte.
  • nn-gram models are estimators. A fixed-context model kk (order-kk Markov assumption) estimates H⁡(Xn∣Xn−k,…,Xn−1)\Ent(X_n \mid X_{n-k}, \dots, X_{n-1}), which decreases toward the rate as kk increases. But with finite data, increasing kk produces unseen contexts, and then estimation error increases. This is the exercise in the second implementation.

Implementation from scratch

First, the exact computation of a Bernoulli typical set. There is no need to enumerate 2n2^n sequences: the class with kk ones has (nk)\binom{n}{k} elements, all with the same probability, and the logarithm of that number is computed with gammaln. The cell reproduces the table above and simulates 10510^5 sequences of n=100n = 100 to check that surprise per symbol concentrates where the AEP predicts.

[ ]The Bernoulli typical set, exact and simulatedBrowser
import numpy as np
from math import log2
from scipy.special import gammaln, logsumexp

p, eps = 0.1, 0.1
q = 1 - p
H = -(p * log2(p) + q * log2(q))

def coste(k, n):
    """Sorpresa por símbolo, -(1/n) log2 p(x), de una secuencia con k unos."""
    return -(k / n) * log2(p) - (1 - k / n) * log2(q)

def ventana(n, eps=eps):
    """Valores de k (número de unos) cuyas secuencias son eps-típicas."""
    return [k for k in range(n + 1) if abs(coste(k, n) - H) <= eps]

def log2_comb(n, k):
    k = np.asarray(k, dtype=float)
    return (gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1)) / np.log(2)

print(f"H = {H:.4f} bits;  ventana de kappa para n grande: {p - eps / log2(q / p):.4f} a {p + eps / log2(q / p):.4f}")
print(f"{'n':>5} {'P(A)':>7} {'log2|A|/n':>10} {'n·H':>7} {'log2|A|':>9}")
for n in (10, 30, 100, 300, 1000, 2000):
    ks = np.array(ventana(n))
    lw = log2_comb(n, ks) + ks * log2(p) + (n - ks) * log2(q)   # log2 de la masa de cada clase
    lA = logsumexp(log2_comb(n, ks) * np.log(2)) / np.log(2)    # log2 del número de secuencias típicas
    print(f"{n:>5} {np.exp2(lw).sum():7.4f} {lA / n:10.4f} {n * H:7.1f} {lA:9.1f}")

# simulación: la sorpresa por símbolo de 10^5 secuencias de n = 100
rng = np.random.default_rng(0)
n, N = 100, 100_000
K = (rng.random((N, n)) < p).sum(axis=1)
Z = coste(K, n)
V = p * q * log2(q / p) ** 2
print(f"\nn = {n}: media de Z_n = {Z.mean():.4f} (H = {H:.4f}), desviación = {Z.std():.4f} (raíz de V/n = {np.sqrt(V / n):.4f})")
print(f"fracción típica en la simulación: {np.mean(np.abs(Z - H) <= eps):.4f};  secuencias de 100 ceros: {np.sum(K == 0)} de {N}")

The typical-set probability grows toward 1 (not monotonically for small nn: note n=30n = 30) and 1nlog⁡∣Aε∣\frac{1}{n}\log|A_\varepsilon| rises toward h2(κmax⁡)=0.562h_2(\kappa_{\max}) = 0.562, as in the table. In the simulation, surprise per symbol has mean HH and standard deviation close to V/n=0.095\sqrt{V/n} = 0.095, and only 4 of the hundred thousand sequences are all zeros (105⋅2.7⋅10−5=2.710^5 \cdot 2.7\cdot 10^{-5} = 2.7 are expected): the most probable sequence is hardly ever seen. Now a real encoder. The typical set is numbered class by class, and within each class using the combinatorial number system (the positions of kk ones in nn slots give a number between 00 and (nk)−1\binom{n}{k} - 1), so encoding and decoding require no stored table, using Python arbitrary-precision integers. Index 0 is reserved for “failure”.

[ ]A typical-set index encoderBrowser
import numpy as np
from math import comb, log2
from scipy.stats import binom

p, eps = 0.1, 0.1
q = 1 - p
H = -(p * log2(p) + q * log2(q))

def ventana(n):
    return [k for k in range(n + 1) if abs(-(k / n) * log2(p) - (1 - k / n) * log2(q) - H) <= eps]

class CodigoTipico:
    """Indexa las secuencias típicas, clase a clase, con el índice 0 para 'fallo'."""
    def __init__(self, n):
        self.n, self.ks = n, ventana(n)
        self.base, total = {}, 1
        for k in self.ks:
            self.base[k] = total
            total += comb(n, k)
        self.bits = (total - 1).bit_length()          # ceil(log2(|A| + 1)) bits por bloque

    def codificar(self, x):
        pos = np.flatnonzero(x)                       # posiciones de los unos, crecientes
        k = len(pos)
        if k not in self.base:
            return 0                                  # atípica: el codificador se rinde
        return self.base[k] + sum(comb(int(c), i + 1) for i, c in enumerate(pos))

    def decodificar(self, idx):
        if idx == 0:
            return None
        k = max(k for k in self.ks if self.base[k] <= idx)
        r = idx - self.base[k]
        x = np.zeros(self.n, dtype=np.uint8)
        c = self.n - 1
        for i in range(k, 0, -1):                     # deshace la suma de binomiales
            while comb(c, i) > r:
                c -= 1
            r -= comb(c, i)
            x[c] = 1
            c -= 1
        return x

rng = np.random.default_rng(0)
print(f"H = {H:.3f} bits.  Tasa de cada código = bits por bloque / n")
print(f"{'n':>5} {'bits':>5} {'R':>7} {'fallos medidos':>15} {'P(fallo) exacta':>16} {'ida y vuelta':>13}")
for n in (50, 100, 200, 500):
    cod = CodigoTipico(n)
    X = rng.random((4000, n)) < p
    medido = np.mean([k not in cod.base for k in X.sum(axis=1)])
    exacta = 1 - binom.pmf(np.array(cod.ks), n, p).sum()
    ok = all(np.array_equal(cod.decodificar(cod.codificar(x)), x) for x in X[:40] if cod.codificar(x))
    print(f"{n:>5} {cod.bits:>5} {cod.bits / n:7.3f} {medido:15.4f} {exacta:16.4f} {str(ok):>13}")

The pattern matters. With fixed ε=0.1\varepsilon = 0.1, failure probability (falling outside the typical set) drops as nn grows, from 0.480.48 with n=50n = 50 to 0.020.02 with n=500n = 500, and matches the exact binomial value. Rate R=⌈log⁡2(∣A∣+1)⌉/nR = \lceil\log_2(\abs{A}+1)\rceil / n rises from 0.500.50 to 0.550.55 and tends to h2(κmax⁡)=0.562h_2(\kappa_{\max}) = 0.562 (the limit of 1nlog⁡∣Aε∣\frac{1}{n}\log\abs{A_\varepsilon} explained after the table), always above H=0.469H = 0.469 and, as property 2 guarantees, never above H+εH + \varepsilon except for rounding to a whole number of bits per block. The round trip is exact for sequences accepted by the encoder. Lowering ε\varepsilon brings the rate closer to HH, but a larger nn is needed to keep failure decreasing.

Estimating the entropy rate of text

Second implementation: estimate H⁡(Xn∣Xn−k,…,Xn−1)\Ent(X_n \mid X_{n-k}, \dots, X_{n-1}) for k=0,…,8k = 0, \dots, 8 in a corpus. To have an answer for comparison, the corpus is synthetic: sentences with a minimal grammar (determiner, noun, verb, determiner, noun, adverb), with uniform independent choices. Each sentence has exactly log⁡2(2⋅8⋅8⋅2⋅8⋅4)=13\log_2(2\cdot 8\cdot 8\cdot 2\cdot 8\cdot 4) = 13 bits of entropy and averages 32.932.9 characters, so the true rate is 13/32.9=0.39513/32.9 = 0.395 bits per character. For real text this figure is unknown: here it is the test bed. The model is an kk-gram counter with additive smoothing α\alpha, trained on 70% and evaluated on the remaining 30% (and, for contrast, on the training data themselves).

[ ]Entropy rate of a synthetic corpus with context kBrowser
import numpy as np
from collections import Counter, defaultdict

DET = ["el", "un"]
SUS = ["perro", "gato", "lobo", "tren", "rio", "viento", "motor", "barco"]
VER = ["mira", "sigue", "busca", "cruza", "deja", "evita", "rodea", "teme"]
ADV = ["despacio", "de noche", "otra vez", "sin ruido"]

def frase(r):
    f = lambda L: L[r.integers(len(L))]
    return f"{f(DET)} {f(SUS)} {f(VER)} {f(DET)} {f(SUS)} {f(ADV)}. "

rng = np.random.default_rng(7)
texto = "".join(frase(rng) for _ in range(300))
bits_frase = np.log2(len(DET) * len(SUS) * len(VER) * len(DET) * len(SUS) * len(ADV))
Lmed = np.mean([len(f"{d} {s} {v} {d2} {s2} {a}. ") for d in DET for s in SUS for v in VER for d2 in DET for s2 in SUS for a in ADV])
print(f"corpus: {len(texto)} caracteres, {len(set(texto))} símbolos distintos")
print(f"tasa verdadera = {bits_frase:.0f} bits / {Lmed:.2f} caracteres = {bits_frase / Lmed:.3f} bits por carácter")

corte = int(0.7 * len(texto))
entrenamiento, prueba = texto[:corte], texto[corte:]
V = len(set(texto))

def entrenar(txt, k):
    cuentas = defaultdict(Counter)
    for i in range(k, len(txt)):
        cuentas[txt[i - k:i]][txt[i]] += 1
    return cuentas

def perdida(cuentas, txt, k, alpha):
    """Pérdida media por carácter, en bits, con suavizado aditivo alpha."""
    total = 0.0
    for i in range(k, len(txt)):
        c = cuentas.get(txt[i - k:i], Counter())
        total += -np.log2((c[txt[i]] + alpha) / (sum(c.values()) + alpha * V))
    return total / (len(txt) - k)

alpha = 0.01
print(f"\n{'k':>2} {'entrenamiento':>14} {'no visto':>9}")
for k in range(9):
    m = entrenar(entrenamiento, k)
    print(f"{k:>2} {perdida(m, entrenamiento, k, alpha):14.3f} {perdida(m, prueba, k, alpha):9.3f}")

Three observations. Loss on unseen text falls with context (from 3.93.9 bits with k=0k = 0 to 0.480.48 with k=4k = 4) and always exceeds the true rate 0.3950.395: it is the upper bound from the previous section. Training loss misleads: it stays at 0.450.45 and does not rise, while unseen loss degrades from k=4k = 4 onward because long contexts are nearly unique. This is overfitting: the long-context model no longer estimates the rate but memorizes the corpus. The best kk (here 4) is chosen with data the model has not seen. Finally, contrast with the most-probable-sequence section: the frequency-based k=4k = 4 model (without smoothing) generates a sample and greedy output, and each one’s mean surprise per character is measured according to the model itself.

[ ]Sampling versus searching for the mode with the same modelBrowser
import numpy as np
from collections import Counter, defaultdict

DET = ["el", "un"]
SUS = ["perro", "gato", "lobo", "tren", "rio", "viento", "motor", "barco"]
VER = ["mira", "sigue", "busca", "cruza", "deja", "evita", "rodea", "teme"]
ADV = ["despacio", "de noche", "otra vez", "sin ruido"]
def frase(r):
    f = lambda L: L[r.integers(len(L))]
    return f"{f(DET)} {f(SUS)} {f(VER)} {f(DET)} {f(SUS)} {f(ADV)}. "

rng = np.random.default_rng(7)
texto = "".join(frase(rng) for _ in range(300))

k = 4
cuentas = defaultdict(Counter)
for i in range(k, len(texto)):
    cuentas[texto[i - k:i]][texto[i]] += 1

def generar(modo, n, semilla):
    """Devuelve el texto generado y su sorpresa media por carácter bajo el propio modelo."""
    r = np.random.default_rng(semilla)
    s, bits = texto[:k], 0.0
    for _ in range(n):
        c = cuentas[s[-k:]]
        simbolos = sorted(c)
        w = np.array([c[x] for x in simbolos], dtype=float)
        p = w / w.sum()
        j = int(np.argmax(w)) if modo == "voraz" else int(r.choice(len(simbolos), p=p))
        bits += -np.log2(p[j])
        s += simbolos[j]
    return s[k:], bits / n

muestras = [generar("muestreo", 1000, sd)[1] for sd in range(30)]
txt_m, _ = generar("muestreo", 1000, 0)
txt_v, bits_v = generar("voraz", 1000, 0)
print(f"muestreo: sorpresa media por carácter = {np.mean(muestras):.3f} ± {np.std(muestras):.3f} (30 muestras de 1000 caracteres)")
print(f"voraz:    sorpresa media por carácter = {bits_v:.3f}")
print(f"el voraz queda a {(np.mean(muestras) - bits_v) / np.std(muestras):.1f} desviaciones por debajo de lo típico")
print("\nmuestra :", repr(txt_m[:110]))
print("voraz   :", repr(txt_v[:110]))

Sampling yields surprise per character with mean 0.450.45 and small standard deviation, a narrow band: this is the model’s AEP. Greedy output has clearly lower surprise (0.360.36, more than five standard deviations below) and endlessly repeats “un rio despacio.”, which is not even a grammatical sentence (the verb and complement are missing): each step chooses the most frequent continuation, and with a context of 4 characters the model does not remember its position in the sentence, so locally optimal choices lead to a loop. The most probable sequence according to the model is not what the model would say. The cause is what you saw in the typical set, now with a real model.

The library version

With SciPy, typical-set mass is a sum of the binomial probability mass function: binom.pmf over the window of kk. For a Markov chain’s rate, the stationary distribution is the left eigenvector with eigenvalue 1 (scipy.linalg.eig on P⊤\mat{P}^\top). As a practical counterpoint, a general compressor (zlib, bz2, lzma) on a chain simulated with a=b=0.05a = b = 0.05 shows how much of the limit is reached without knowing the model: none reaches rate 0.2860.286, and shuffling the same sequence (same marginal entropy, no memory) makes it compress poorly.

[ ]Markov chain: rate, general compressors and shuffled sequenceBrowser
import zlib, bz2, lzma
import numpy as np
from scipy.linalg import eig

def tasa_entropia(P):
    P = np.asarray(P, dtype=float)
    w, v = eig(P.T)
    mu = np.real(v[:, np.argmin(np.abs(w - 1))])
    mu = mu / mu.sum()                                   # distribución estacionaria
    t = np.where(P > 0, P * np.log2(np.where(P > 0, P, 1.0)), 0.0)
    return -float(mu @ t.sum(axis=1)), mu

P = [[0.95, 0.05], [0.05, 0.95]]
tasa, mu = tasa_entropia(P)
print(f"estacionaria = {np.round(mu, 3)};  entropía marginal = 1.000 bit;  tasa = {tasa:.4f} bits")
print("caso 0.1 / 0.3:", np.round(tasa_entropia([[0.9, 0.1], [0.3, 0.7]])[0], 4))

rng = np.random.default_rng(1)
n = 200_000
cambios = rng.random(n) < 0.05
x = (np.cumsum(cambios) + rng.integers(2)) % 2          # cadena simétrica con cambio de estado 0.05
def bits_por_simbolo(s, comprime):
    return 8 * len(comprime((s.astype(np.uint8) + 48).tobytes())) / n

print(f"\n{'':>10} {'zlib':>7} {'bz2':>7} {'lzma':>7}   (bits por símbolo)")
for nombre, s in (("cadena", x), ("barajada", rng.permutation(x))):
    print(f"{nombre:>10} {bits_por_simbolo(s, lambda d: zlib.compress(d, 9)):7.3f} {bits_por_simbolo(s, lambda d: bz2.compress(d, 9)):7.3f} {bits_por_simbolo(s, lzma.compress):7.3f}")

General compressors do not see the model and pay 0.350.35 to 0.410.41 bits per symbol (against the bound 0.2860.286 and the marginal’s 11 bit). The shuffled version, with the same proportion of 0 and 1, exceeds 1 bit: without memory there is nothing to exploit. Entropy rate distinguishes the two sequences; marginal entropy does not. This is why, in lesson 7, a universal compressor must learn the model.

Common mistakes

Exercises

NumericSize of the typical set
For a Bernoulli source with p=0.1p = 0.1 and n=1000n = 1000 trials, how many bits is the typical-set size on the exponential scale? Estimate log⁡2∣Aε(n)∣\log_2\abs{A_\varepsilon^{(n)}} with ε→0\varepsilon \to 0 using n h2(p)n\,h_2(p).
NumericEntropy rate of a binary chain
A stationary binary Markov chain has P(1∣0)=0.1P(1 \mid 0) = 0.1 and P(0∣1)=0.3P(0 \mid 1) = 0.3. What is its entropy rate in bits per symbol?
NumericHow much can a file be compressed?
A file contains 8⋅1058 \cdot 10^5 binary symbols generated by the symmetric chain that changes state with probability 0.050.05 at each step. In the long-sequence limit, how many bytes does any lossless compressor need at minimum (in expectation)?
NumericHow much does Chebyshev need to guarantee it?
For p=0.1p = 0.1, ε=0.1\varepsilon = 0.1 and δ=0.1\delta = 0.1, what value of nn makes V/(nε2)=δV/(n\varepsilon^2) = \delta; that is, from how many trials does Chebyshev guarantee P(Aε(n))≥0.9\Pr(A_\varepsilon^{(n)}) \ge 0.9? Use V=p q (log⁡2(q/p))2V = p\,q\,(\log_2(q/p))^2.
QuizThe all-zero sequence
A coin comes up 1 with probability 0.10.1. It is tossed n=1000n = 1000 times. Let xx be the sequence of 1000 zeros. What is true?
QuizA coin chosen at the start
At the start, coin A with p1=0.1p_1 = 0.1 or B with p2=0.4p_2 = 0.4 is chosen, each with probability 12\tfrac12, and the chosen coin is tossed nn times. The process is stationary. With h2(0.1)=0.469h_2(0.1) = 0.469, h2(0.4)=0.971h_2(0.4) = 0.971 and h2(0.25)=0.811h_2(0.25) = 0.811, what does −1nlog⁡2p(Xn)-\frac{1}{n}\log_2 p(X^n) converge to as n→∞n \to \infty?
QuizWhen is ignoring memory free?
For which of these binary transition matrices does entropy rate equal the stationary distribution's marginal entropy H⁡(X1)\Ent(X_1)?
QuizSampling or searching for the mode
Long texts are generated with an autoregressive language model qq in two ways: ancestral sampling (temperature 1) and greedy decoding. For each text, mean surprise per token −1nlog⁡q(xn)-\frac{1}{n}\log q(x^n) is measured according to the model itself. What is expected?
ProofThe typical set is not large
Prove: For every ε>0\varepsilon > 0 and every n≥1n \ge 1, ∣Aε(n)∣≤2n(H+ε)\abs{A_\varepsilon^{(n)}} \le 2^{n(H + \varepsilon)}.
0
Use definition Aε(n)={xn:2−n(H+ε)≤p(xn)≤2−n(H−ε)}A_\varepsilon^{(n)} = \{x^n : 2^{-n(H+\varepsilon)} \le p(x^n) \le 2^{-n(H-\varepsilon)}\} and the fact that pp is a probability distribution on Xn\mathcal{X}^n.

Step 1 of 3. What inequality relates the size of Aε(n)A_\varepsilon^{(n)} to total mass?

ProofEvery high-probability set is large
Prove: Let 0<δ<10 < \delta < 1 and 0<ε<1−δ0 < \varepsilon < 1 - \delta. If nn is sufficiently large, every set B⊆XnB \subseteq \mathcal{X}^n with P(B)≥1−δ\Pr(B) \ge 1 - \delta satisfies ∣B∣≥(1−δ−ε) 2n(H−ε)\abs{B} \ge (1 - \delta - \varepsilon)\, 2^{n(H - \varepsilon)}.
0
Use P(Aε(n))>1−ε\Pr(A_\varepsilon^{(n)}) > 1 - \varepsilon for large nn (property 1) and p(xn)≤2−n(H−ε)p(x^n) \le 2^{-n(H-\varepsilon)} on Aε(n)A_\varepsilon^{(n)}.

Step 1 of 3. What lower bound do you have for the mass of B∩Aε(n)B \cap A_\varepsilon^{(n)}?

CodeEntropy rate of a transition matrix
Implement entropy_rate(P): the entropy rate in bits per symbol of the stationary Markov chain with transition matrix P (rows sum to 1). Compute the stationary distribution as the solution of μP=μ\mu\mat{P} = \mu, ∑iμi=1\sum_i\mu_i = 1 (prefer least squares using np.linalg.lstsq to inverting a matrix) and return −∑iμi∑jPijlog⁡2Pij-\sum_i\mu_i\sum_j P_{ij}\log_2 P_{ij} with the convention 0log⁡0=00\log 0 = 0. Tests include periodic and nearly deterministic chains: no nan should appear.
import numpy as np

def entropy_rate(P):
  """Tasa de entropía en bits por símbolo de la cadena con matriz de transición P."""
  P = np.asarray(P, dtype=float)
  # tu código: distribución estacionaria mu y luego -sum_i mu_i sum_j P_ij log2 P_ij
  return 0.0
Shift+Enter to run

Summary

Key idea
Entropy is an exponent: nearly all the probability of nn iid symbols is in about 2nH2^{nH} typical sequences, each with probability ≈2−nH\approx 2^{-nH}, because −1nlog⁡p(Xn)-\frac{1}{n}\log p(X^n) is an iid average and converges to HH (AEP). Thus HH is the exact block-compression threshold, and the most probable sequence (the mode) is not typical. With memory, what matters is entropy rate, the surprise of a symbol given the past, and a language model’s loss on unseen text is an upper bound on it.
  • Counting versus weighing. (nk)≈2nh2(k/n)\binom{n}{k} \approx 2^{n h_2(k/n)} and each sequence with kk ones weighs 2−nc(k/n)2^{-n c(k/n)}, with cc a straight line. Class mass is 2−nKL⁡(κ∥p)2^{-n\KL(\kappa\|p)} (up to a polynomial factor): it concentrates where the line is tangent, at κ=p\kappa = p.
  • AEP. For iid, −1nlog⁡p(Xn)→H-\frac{1}{n}\log p(X^n) \to H in probability, by the weak law; with Chebyshev, P(∣Zn−H∣>ε)≤V/(nε2)\Pr(\abs{Z_n - H} > \varepsilon) \le V/(n\varepsilon^2), with V=Var⁡[−log⁡p(X)]V = \Var[-\log p(X)] the varentropy.
  • Typical set. P(Aε(n))→1\Pr(A_\varepsilon^{(n)}) \to 1, ∣Aε(n)∣≤2n(H+ε)\abs{A_\varepsilon^{(n)}} \le 2^{n(H+\varepsilon)} (for every nn) and ∣Aε(n)∣≥(1−ε)2n(H−ε)\abs{A_\varepsilon^{(n)}} \ge (1 - \varepsilon)2^{n(H-\varepsilon)} for large nn. It is an exponentially small fraction of ∣X∣n\abs{\mathcal{X}}^n if pp is not uniform.
  • Source coding. With R>HR > H block codes have error →0\to 0 (index AεA_\varepsilon); with R<HR < H every code has error →1\to 1 (strong converse). The transition has width ∼V/n\sim\sqrt{V/n}.
  • The most probable is not typical. The maximum-probability sequence has surprise per symbol −log⁡p(a∗)<H-\log p(a^\ast) < H and does not appear. Searching for the mode (greedy, beam) generates atypical, repetitive sequences; sampling generates typical sequences.
  • Entropy rate. H⁡(X)=lim⁡1nH⁡(Xn)=lim⁡H⁡(Xn∣Xn−1)\Ent(\mathcal{X}) = \lim \frac{1}{n}\Ent(X^n) = \lim \Ent(X_n \mid X^{n-1}) for stationary processes, and both sequences decrease toward it. For a Markov chain, ∑iμiH⁡(Pi⋅)\sum_i \mu_i \Ent(P_{i\cdot}). Ignoring memory overestimates cost: a chain with uniform marginal and rate 0.2860.286 compresses to 29%.
  • Shannon–McMillan–Breiman. For stationary ergodic processes, −1nlog⁡p(Xn)→H⁡(X)-\frac{1}{n}\log p(X^n) \to \Ent(\mathcal{X}) almost surely (for Markov chains, this is the ergodic theorem). Without ergodicity (mixtures) there is no single limit.
  • Modern reading. E[−1nlog⁡q(Xn)]=1nH⁡(Xn)+1nKL⁡(pn∥qn)≥H⁡(X)\E[-\frac{1}{n}\log q(X^n)] = \frac{1}{n}\Ent(X^n) + \frac{1}{n}\KL(p_n\|q_n) \ge \Ent(\mathcal{X}): a model’s loss on unseen text upper-bounds the rate. Estimating it with long contexts on training data is misleading.