Experiment — Entropy, KL and predictive coding
Manipulate distributions and verify the identities
← Revision sheet · Lesson: Cross-entropy
Question
How can we distinguish target uncertainty, prediction mismatch and ideal coding cost?
Run the experiment
From the repository root:
uv run --locked python experiments/information-theory/run.pyThe script uses two synthetic distributions:
- target q = (0.5, 0.5);
- prediction p = (0.75, 0.25).
It computes metrics in nats and bits, ideal code lengths, and checks that cross-entropy equals target entropy plus KL divergence.
Expected result
| Measure | Approximate value |
|---|---|
| Target entropy H(q) | 0.693 nats |
| Cross-entropy H(q,p) | 0.837 nats |
| KL divergence D(q‖p) | 0.144 nats |
| Perplexity under q | 2.309 |
| Target entropy H(q) | 1 bit |
| Cross-entropy H(q,p) | 1.208 bits |
| KL divergence D(q‖p) | 0.208 bits |
The identity to verify is:
0.837 ≈ 0.693 + 0.144
Try changing the distributions
Open experiments/information-theory/run.py and modify q and p while keeping them normalized. Try:
- p = q: KL divergence should be zero.
- p = (0.5, 0.5): the prediction becomes uniform.
- A one-hot target: cross-entropy becomes the observed token’s NLL.
- A predicted zero probability where q is positive: cross-entropy and KL become infinite.
Perplexity is the exponential of mean NLL using the same logarithm base: here exp(0.837) ≈ 2.309. For the one-hot case with an observed probability of 0.25, perplexity is 4.
Reusable functions and their tests live in src/llm_lab/foundations/information_theory.py and tests/unit/test_information_theory.py.
Guided experiments on surprisal
These manipulations extend the worked calculation in the lesson. They use fictional probabilities and do not represent outputs from a trained model.
Change the target probability. Keep the context and observed token fixed, then vary its probability from \(0.8\) to \(0.4\), \(0.1\), and \(0.01\). Calculate \(I(x\mid c)=-\log_2 p(x\mid c)\) each time. Surprisal should increase whenever probability decreases.
Change the context. Keep the target token
Parisfixed, but compare two fictional contexts:Context \(p(\text{Paris}\mid c)\) Surprisal “The capital of France is…” \(0.80\) \(0.32\) bits “The capital of Japan is…” \(0.01\) \(6.64\) bits The token does not change; its conditional probability and therefore its surprisal do.
Change the probabilities of other tokens. Keep the target probability constant, then redistribute the remaining probability mass among other candidates. The target’s surprisal stays fixed, but the distribution’s entropy may change.
Expected takeaway: distinguish the observed event, the context that conditions its probability, and the full distribution of possible outcomes. An event does not have one unique surprisal independently of the model and context.
Extension — predictive (V)-information
Predictive (V)-information formalizes a question different from Shannon mutual information: how much can an allowed family of models improve its prediction of (Y) by observing (X)?
For a predictive family (V) and logarithmic loss:
[ H_{V}(YX) = _{fV} E[-f_X(Y)] ]
[ I_{V}(XY) =H_{V}(Y) -H_{V}(YX). ]
The family must satisfy optional ignorance: every probability distribution produced by a predictor must also be available from a predictor that ignores its input. This condition ensures, among other properties, non-negativity at the population level.
Run the controlled toy example
uv run --locked python experiments/information-theory/v_information.pyThe script exactly compares three situations using synthetic joint distributions:
| Situation | (V)-entropy without input | Conditional (V)-entropy | Predictive information |
|---|---|---|---|
| Correlated feature, family can exploit it | 1 bit | 0.469 bits | 0.531 bits |
| Independent feature | 1 bit | 1 bit | 0 bits |
| Correlated feature, constant-only family | 1 bit | 1 bit | 0 bits |
The last case is the key teaching point: the data contain a dependency, but a restricted predictive family cannot exploit it. The quantity therefore depends explicitly on the family (V), not only on the joint distribution.
XOR example: a dependency some predictors cannot exploit
Let \(X_1\) and \(X_2\) be independent uniform bits, and let \(Y=X_1\oplus X_2\). The pair \((X_1,X_2)\) determines \(Y\) perfectly, so the mutual information \(I((X_1,X_2);Y)\) is 1 bit. Yet a family restricted to constant predictors gains nothing from observing the inputs: its conditional logarithmic loss remains 1 bit and its predictive information is zero. A family able to represent the XOR interaction can predict Y exactly and reduce that loss to zero. The example shows that predictive information depends on the capabilities of the predictor family, not only on dependencies present in the data.
This intuition is discussed by Xu et al. (ICLR 2020), A Theory of Usable Information under Computational Constraints. A complementary experiment on synthetic XOR-style tasks illustrates the distinction; it is not an evaluation of a trained LLM.
Unlike Shannon mutual information, predictive information depends on the predictor family and on the directed task from X to Y. It does not replace mutual information or mean that computation creates Shannon information: it quantifies what a specified predictor family can exploit.
Limitations: this is an exact population-risk calculation on a small discrete example and a hand-specified finite family. No model is trained; it is neither a sample-based estimate, nor an architecture comparison, nor evidence that attention extracts more information than a bag-of-words model. A trained-model experiment would require train/test splits, a pre-specified model class and selection protocol, and an overfitting analysis.
Extension — entropy rate and practical compression
To avoid comparing marginal single-character entropy with a compressed file size from an algorithm that also exploits dependencies, run a second experiment:
uv run --locked python experiments/information-theory/compression.pyThe script generates three equal-length sources over a four-symbol alphabet: a constant sequence, an IID-uniform source, and a symmetric first-order Markov chain whose probability of staying on the same symbol is 0.9. The seed is fixed. It compares:
- empirical marginal entropy per symbol;
- the theoretical source entropy rate;
- zlib output size in bits per symbol, including container overhead.
The Markov case is instructive: its stationary marginal is uniform (2 bits per symbol), but its entropy rate is lower because successive symbols are dependent. For asymptotic coding of a dependent source, entropy rate—not marginal entropy alone—is the relevant benchmark.
Limitations: zlib is not an optimal code; results depend on the algorithm, compression level, finite sequence length and container overhead. This comparison illustrates a mechanism; it does not prove the source-coding theorem.
For a stationary source, the entropy rate is:
[ h(X)=_{n}H(X_1,,X_n). ]
For a first-order Markov chain, it is the conditional transition entropy (H(X_tX_{t-1})). It can be much lower than marginal entropy (H(X_t)) when successive symbols are correlated.
For a separate deterministic comparison of empirical marginal entropy H0, first-order conditional entropy H1, and the size of an actual zlib stream over three sequences, see the complementary sequence-compression experiment. It uses a distinct protocol from the source-entropy simulation above.
What this experiment does — and does not — show
It verifies mathematical identities on discrete distributions. It does not measure model intelligence, generalization or the quality of a trained LLM. Ideal lengths -log₂(p) may be fractional; a practical code adds constraints and overhead.
Extension — attention-row KL versus mutual information
A non-uniform attention row can have positive KL divergence from the uniform distribution even when it reveals no dependency between queries and keys. Run:
uv run --locked python experiments/information-theory/attention_kl_vs_mutual_information.pyThe experiment compares two conditional tables:
- Repeated row: every context receives the same distribution (0.9, 0.1). Mean KL to uniform is about 0.531 bits, but mutual information between context and key is 0 bits: knowing the context does not change the key distribution.
- Opposite rows: the two contexts receive (0.9, 0.1) and (0.1, 0.9), respectively. Mutual information is about 0.531 bits. Its numerical equality with KL-to-uniform is incidental.
For a genuine joint distribution, the correct identity is:
[ I(X;Y)=E_{X}. ]
The KL reference is therefore the marginal (P(Y)), not an arbitrary uniform distribution. Crucially, attention weights are not automatically calibrated conditional probabilities (P()). A joint distribution must be defined and justified before this identity can be interpreted statistically.
The general mutual-information calculation is tested in src/llm_lab/foundations/information_theory.py.