Minimum description length
Learning as compression, from uncomputable Kolmogorov complexity to Rissanen’s practical MDL principle. Study two-part and universal codes, regret, BIC, prequential coding, and applications to deep networks and probing.
After this lesson you can
- Define Kolmogorov complexity, prove invariance up to a constant, and sketch its uncomputability.
- Apply two-part MDL to model selection with explicit parameter coding.
- Derive Bayesian-mixture and NML regret for Bernoulli and the asymptotic (k/2) log n form.
- Calculate prequential description length of an online model and use it to compare models.
- Relate MDL to BIC, Bayesian marginal likelihood and adjusted language-model compression rate.
Before you start
- 07Mutual informationKraft-McMillan inequalityOptimal expected length boundsArithmetic codingSequential probability assignmentPrediction-compression equivalenceChannel capacityLocal Fisher approximation of KL
- 01Universal Turing machineHalting problem
- 14Bayesian information criterion
- 26Order selection with information criteria
- 05Prior, likelihood and posteriorMarginal likelihood (evidence)
- 15Micro framework to PyTorch correspondence
- 00Canonical training and evaluation loop
Motivation: learning is compression
Consider two strings of a million bits. The first is 0101...01, five hundred thousand repetitions of 01. The second comes from tossing a coin a million times. Both have the same probability under a fair coin, , yet nobody doubts which has “structure.” The difference is that the first has a short description (“repeat 01 five hundred thousand times,” a few dozen bits), while the second has none substantially shorter than itself. The intuition that regularity is an opportunity to abbreviate is this lesson’s starting point.
Now replace strings with datasets and descriptions with models. If you find a model that lets you write the data in far fewer bits than their raw representation, you have found a real regularity, exactly what you expect to recur in new data. The argument is counting, made precise shortly: very few short descriptions exist, so unstructured data are very unlikely to be highly compressible by chance. A model that compresses cannot be fitting noise, because noise cannot be compressed.
This is a quantitative version of Occam’s razor. It does not say “prefer simplicity” as an aesthetic preference; it says “prefer what describes the data in fewer bits, counting the bits for the model itself.” A degree-20 polynomial through 21 points compresses nothing: the 21 coefficients take as much space as the 21 data points. A line with small residuals does compress: two numbers plus cheaply encoded residuals.
You already know half the story. In the language model as compressor lesson you saw that a probabilistic model coupled to an arithmetic coder encodes data in bits, within two bits. The missing half is that the receiver must also know the model. This lesson builds it in four steps:
- The shortest possible description, Kolmogorov complexity: the ideal, which turns out to be uncomputable.
- Two-part MDL: describe the model first and then the data with it, discovering that each parameter costs bits.
- Universal codes: instead of choosing one model, encode with a mixture over the family and measure the price of not knowing the parameter (regret).
- Prequential coding: encode each observation with the model trained on previous ones. This version applies to deep networks, and its length is the area under the online loss curve.
Unless stated otherwise, is base 2 and lengths are measured in bits; is the natural logarithm.
Kolmogorov complexity
To speak of “the shortest description,” fix a description language; the most general is a programming language. Fix a universal Turing machine that reads binary programs. Also require it to be prefix-free: the set of programs on which halts contains no two strings where one is a prefix of the other. This is natural when a program must know where it ends without an end symbol, and has a useful consequence: program lengths satisfy the Kraft inequality.
Three properties follow directly:
- Trivial upper bound. A program can include literally: “print what follows.” The prefix version must say where it ends, for example by first writing with a self-delimiting code, so . A string is never much more complex than its length.
- Most strings are incompressible. There are strings of length and fewer than programs of length less than . Thus at most a fraction of length- strings admit a description bits shorter. Fewer than one string in a million can be compressed by 20 bits.
- Regular strings are highly compressible. The first bits of the binary expansion of have : a program calculating and the number suffice.
The second point is the motivation’s counting argument. If a model-selection procedure gives a description of your data bits shorter than the uniform code, the probability of this happening with unstructured data is at most . With learning assumptions instead of programs, this idea gives Occam and PAC-Bayes generalization bounds in the learning theory module.
Invariance
The definition depends on . Surprisingly, it depends very little.
The proof idea, which you will work through in the exercises, is that can simulate with a fixed-length interpreter: any program for becomes one for by prepending the interpreter. This is why we often write without a subscript: it is defined up to an additive constant.
Uncomputability
Proof
Suppose one exists. For each , consider program : “enumerate strings in length order, and lexicographically within each length; calculate for each and return the first with .” Such a string exists because incompressible strings exist at every length. But is a fixed program needing only , so its length is , and the string it prints satisfies
which is false for sufficiently large . Contradiction.
∎This is Berry’s paradox (“the smallest number not definable in fewer than twenty words”) turned into a theorem. The underlying obstacle is the halting problem: to know whether a short program prints we would have to know which short programs terminate. We can approximate from above: run all programs in parallel, interleaving steps, and whenever one prints , update the best length found. The bounds decrease to , but you never know when they have arrived. Any real compressor (gzip, bzip2, a language model with arithmetic coding) gives such an upper bound, plus a constant for the decompressor.
Randomness and entropy
We call algorithmically random if for a small constant: it has no essentially shorter description than itself. For infinite sequences, Martin-Löf defined randomness as “passing all effective statistical tests,” and the Levin–Schnorr theorem says this is equivalent to all prefixes being incompressible in that sense: for every . The connection with Shannon entropy is precise.
Proof
Lower bound: for fixed , shortest programs for strings of length form a prefix code, because is prefix-free. By the expected length bounds, no prefix code has average length below entropy, .
Upper bound: describe in two parts. First its type, the frequency vector , taking at most values; then the index of within its type class, which has at most elements (as in the method of types). This gives . Take expectations and use concavity of : .
∎Notice the upper bound’s shape: the data cost and the model (type, or multinomial parameter) costs order per free parameter. This is the first appearance of a pattern we will see three more times, with the constant refined to .
From Kolmogorov to MDL: computable codes
Kolmogorov complexity is ideal but cannot select models: it is uncomputable, depends on a constant dominating at real sizes, and searches over all programs, most absurd as statistical models. Jorma Rissanen (1978) proposed a practical compromise: restrict descriptions to a chosen family of probabilistic models, where lengths are computable.
The bridge is the code–distribution correspondence. By Kraft’s inequality, every distribution on a discrete set gives a prefix code with lengths , and every prefix code with lengths gives a (sub)distribution . Ignoring rounding, which costs at most two bits total with arithmetic coding,
From here, “encode with ” and “assign probability ” mean the same thing. For continuous data, discretize to fixed precision ; the length is per datum. The term is the same for every model and cancels in comparisons.
The two-part code
The two parts pull in opposite directions. A richer model fits better and falls: this is training loss in bits, and never increases when parameters are added. But each parameter must be written, and grows. Their sum has a minimum, and that minimum is the MDL choice.
How much does a parameter cost?
For to be finite, the parameter is written at finite precision: choose a grid of step over its range and transmit grid point nearest the maximum likelihood estimate . A tradeoff appears. With a fine grid, and data cost is minimal, but writing the parameter is expensive. With a coarse grid, the parameter is cheap but moves away from and the data cost increases.
Proof
The first term is the uniform code length over cells. For the second, expand around . The gradient vanishes at the maximum and curvature is observed information, which for large is (the same quadratic approximation as the Fisher metric as local KL):
With uniform error, , giving the third term. Differentiation yields , hence . Substitution gives and .
∎The conclusion is one of statistics’ most reusable formulas: the worthwhile precision for writing a parameter is of the order of its typical error, , costing bits per parameter, plus a constant not growing with . More precision wastes bits: the difference is below estimation noise. With parameters, rotating to the Fisher matrix’s eigenaxes gives cost and two-part length
In nats, this is half the Bayesian information criterion, . The BIC used to choose an ARMA model order is therefore two-part MDL with the constant discarded.
Occam in bits
The next figure calculates polynomial regression. The data are points with Gaussian noise of standard deviation , recorded to two decimals (). The degree- model has parameters (the coefficients and noise variance), and
where is the maximum-likelihood residual variance and encodes the degree from 0 to 12.
Three things the figure shows:
- The blue part always decreases. It is training loss, and adding a parameter never worsens it. If parameters were free, the maximum degree would always win: exactly what unpenalized maximum likelihood does, while diamonds show the cost on new data.
- The sum’s minimum falls at or near the diamonds’ minimum degree, although MDL sees no new data. With initial settings and two hundred different samples, MDL picks degree 3 four times out of five, the diamonds distribute their minimum between 3 and 5, and the median loss on new data from using the MDL degree instead of the best is less than one bit out of about three hundred. The true function is odd, so even degrees add little and the optimum is usually 3 or 5; when almost tied, MDL picks the cheaper one.
- Parameter precision is part of the model. With 32 bits per parameter (one
float32per coefficient), each coefficient costs more than it saves and MDL underfits. The programmer does not choose the right precision: it comes from the data, as in the theorem.
Two-part coding has two defects. It is inefficient: the receiver could reconstruct some of the parameter from the data themselves, and the code pays twice. It is arbitrary: length depends on discretization and the grid code, and these choices enter the constant. Refined MDL fixes both with a cleaner idea: transmit no parameter.
Universal codes and regret
Fix a family . If you knew in advance which to use, you would encode in bits. The best for particular data is the maximum-likelihood choice , but this depends on the data and is not a code: . The question is how much is lost with a single code that must work for all possible data.
Three classical constructions each illuminate an aspect.
Bayesian mixture. Fix a prior on and encode with , the marginal likelihood. For a finite family of models and a uniform prior, regret is at most (proved in the exercises): the mixture never loses more than the cost of saying which of the models to use. For the Bernoulli family, with ones in tosses and prior ,
With (uniform prior) this is Laplace’s rule; with , the Krichevsky–Trofimov (KT) estimator, the mixture with Jeffreys prior .
NML. Shtarkov (1987) asked which code has minimum worst-case regret. The answer is the normalized maximum likelihood distribution:
Proof
By definition, for every . Let be another distribution. Since both sum to 1, some sequence has , and its . Thus every other has a strictly larger maximum.
∎is the family’s parametric complexity: the exact price in bits of not knowing the parameter. Two-part coding approximated it crudely by . For Bernoulli with , sequences and have maximum likelihood 1 and and have each, so . For general , grouping by number of ones,
What the figure teaches:
- Laplace’s worst case is , on constant sequences: with , and maximum likelihood is 1. Its regret grows like , twice what is needed. The uniform prior places little mass near , exactly where the likelihood of a constant sequence concentrates.
- KT pays at the edges and slightly less than in the center. Jeffreys prior puts more mass at the boundaries, precisely enough to make regret nearly uniform. Asymptotically it exceeds NML by half a bit in the worst case.
- hugs : for , versus bits.
Asymptotic form and Fisher information
The per-parameter pattern has a geometrically meaningful constant.
The integral is the volume of in the Fisher metric, with a clear interpretation: with data points, two parameters are distinguishable if their Fisher distance exceeds roughly , so fits on the order of distinguishable distributions. Parametric complexity is the logarithm of that count: count distinguishable distributions, not parameters. For Bernoulli, and the formula gives , the figure’s reference curve.
The Bayesian mixture has the same form. By Laplace’s method applied to ,
Regret depends on through , and is constant precisely when : Jeffreys prior makes the mixture asymptotically minimax, equating it to NML in the interior of . KT is not a Bernoulli trick: it is a special case of a general rule.
Redundancy and capacity
Instead of worst case over sequences, measure expected excess when data come from some : redundancy of is , a KL divergence. The minimax problem connects this lesson with channels.
Proof
We prove the inequality, which supplies the intuition; the other needs a minimax theorem for convex–concave functions. For any prior and any ,
The middle equality follows by adding logarithms: , and the second term averaged with gives . The last equality is the definition of mutual information as average KL to the marginal. Since the supremum over exceeds the average under , for every and .
∎Read backwards: the universal code’s toll is the information data carry about the parameter. With data points, can be estimated to precision in each of directions, the channel transmits about bits about , and this is exactly what the code cannot avoid paying. Clarke and Barron (1994) gave the exact form: minimax redundancy is , differing from NML regret by because regret compares with each sequence’s and redundancy with the true .
Prequential coding
The most practical construction remains. By the chain rule, any distribution on sequences factors into predictions, , and its code length is the sum of prediction surprises. This is the sequential probability assignment already used with arithmetic coding. Dawid (1984) named evaluating a model by how it predicts each datum before seeing it prequential, from “predictive sequential.”
Three facts make this definition the backbone of modern MDL.
No parameters need transmitting. The receiver retrains the model; only data are sent, each encoded using what was learned from predecessors. Model cost does not disappear: it is paid as poor predictions while the model has not yet learned.
A Bayesian mixture is prequential. If is the posterior predictive, the product of predictives is, by the chain rule, exactly the marginal likelihood:
Laplace’s rule is the uniform mixture predictive, , with the number of ones seen. Encoding one datum at a time with it gives the same length as the mixture. Since does not depend on data order (if exchangeable under the model), Bayesian prequential length does not either, although each term changes with order.
A point estimator works too. If is the maximum-likelihood model on the past (with some regularization for initial data), Rissanen (1984) showed that for regular families and data generated by a family member, expected redundancy remains . In the worst case over sequences, or under misspecification, a point estimator may pay substantially more than the mixture. Intuition: the error of with data is order , each prediction pays excess order nats, and .
In blocks, as with networks
Retraining after every datum is infeasible for a network. Blier and Ollivier (2018) proposed a block version: choose times , usually geometrically spaced; encode the first block with a uniform code; train the model on the first observations and use it to encode to ; retrain on the first and encode the next block, and so on. Length is
where is the model trained on the first data. If you plot average block loss against the data count, length is the area under the online loss curve.
The figure reproduces in miniature the phenomenon Blier and Ollivier observed with networks:
- The small model learns quickly and plateaus. A line is estimated well from few data, but cannot capture curvature and its loss plateaus.
- The large one starts worse and ends better. Fitted on 4 or 8 points, the degree-9 polynomial overfits and oscillates between data: blocks encoded this way cost 2 or 3 bits per point more than the small model (sometimes more than twenty with other data orders). After a few hundred data points it has learned the function’s shape and each new block costs less than with the small model.
- The winner depends on available data. This is what it means for description length to measure complexity relative to available data. With 64 points the line is best: insufficient data let the large model recoup its poor start. With 1024, the large model wins. MDL has no fixed preference for simplicity; it prefers what can be learned from these data.
- Order matters with a point predictor, but not a Bayesian mixture. With block fitting, shuffling moves crossover from a few data to over two hundred, and reverses the result at in about one in four orders: a single block where the large polynomial, fitted to poorly distributed points, oscillates in a region without data can cost hundreds of bits. With the pointwise Bayesian mixture, length is marginal likelihood and order dispersion is zero (up to rounding). The Gaussian coefficient prior also prevents an expensive start for the large model: the mixture is never certain of something the data do not support.
MDL, BIC and marginal likelihood
Putting the pieces together, for a regular -parameter family the four lengths agree through the term:
| Code | Length of | term |
|---|---|---|
| Two-part | depends on discretization | |
| Bayesian mixture | depends on the prior | |
| NML | intrinsic to the family | |
| Prequential (plug-in) | , in expectation | depends on the estimator |
BIC keeps the first two terms and discards the rest. Thus it is consistent in the same sense as MDL (if the true model is among finite-dimensional candidates, it eventually selects it with probability tending to 1), and fails in the same ways as naive two-part coding: it cannot distinguish models with equal and different geometric complexity, and for small the discarded term may exceed the difference measured.
The second row merits its own sentence: marginal likelihood is a code length, that of the Bayesian mixture with the prior as parameter code. Bayesian model selection by Bayes factors and MDL with mixture codes are the same calculation. Interpretation differs, visibly when the model is false, as it always is: the Bayesian needs to believe their prior, whereas the MDL practitioner only needs a good code and can choose codes for worst-case guarantees (NML) rather than beliefs.
MDL in deep learning
A network of one hundred million parameters at 32 bits occupies 3200 million bits. ImageNet has just over a million training images, and their thousand-class labels take about bits. The naive two-part calculation says the network compresses nothing, another way of saying it should inevitably overfit. It does not, and there are three answers to how much it really compresses, from worst to best.
Variational codes and bits-back. Hinton and van Camp (1993) proposed transmitting not particular weights but a distribution over them, with a coding trick, bits-back: the sender chooses using bits of an auxiliary message, sends with prior code and data with , and the receiver, able to reconstruct , recovers the auxiliary bits. Net cost is
the negative evidence lower bound (ELBO) of variational methods: the same calculation as the VAE variational rate bound. Blier and Ollivier (2018) evaluated this code on real networks and found surprisingly poor compression bounds, although the method is designed to minimize them, proposing this as an explanation for the modest performance of variational methods in deep learning.
Prequential coding. In the same work, block coding from the preceding section, with networks retrained at every block, gave excellent compression: deep networks do compress their training data, by a lot, when the cost of describing them is counted correctly. You reproduce the observation below on a laptop scale.
MDL probing. To determine whether a pretrained model representation “encodes” a linguistic property , train a simple classifier (probe) from to and inspect accuracy. The problem is that a sufficiently capable probe learns almost anything, even random labels. Voita and Titov (2020) instead proposed measuring prequential label length given representations, with geometrically spaced blocks. A representation containing the property accessibly lets it be learned from little data, visible in the area under the curve even when final accuracies agree. With control tasks (random labels assigned by word type), probes reached similar accuracies on the linguistic and control tasks, while description length clearly separated them.
A language model is its training curve. If you train a language model for one epoch, each batch is evaluated before training on it. The sum of training losses in bits is then the corpus’s prequential length, and the receiver needs only the training code (a few kilobytes) to reproduce the process. This is the correct sense in which “an LM compresses”: not the file size compressed with the already trained model, which ignores model cost, but the area under the curve. Delétang et al. (2023) illustrate this with the adjusted compression rate, adding parameter size to compressed file size: a model with 70 000 million parameters at 16 bits takes 140 GB, 140 times a 1 GB corpus, so its adjusted rate on that corpus far exceeds 100 % however good the unadjusted rate. LLM scaling laws read naturally in this language: more data make larger models worthwhile, as in the prequential figure.
Implementation from scratch
First, Kolmogorov complexity from above. Any compressor gives an upper bound on up to a constant; see how good it is on strings with known structure.
import bz2, zlib
import numpy as np
import mpmath
n = 100_000
rng = np.random.default_rng(0)
mpmath.mp.dps = n + 10
pi_digitos = mpmath.nstr(mpmath.pi, n, strip_zeros=False).replace(".", "")[:n].encode()
cadenas = {
"«01» repetido": (b"01" * (n // 2), 0.0),
"moneda justa, '0'/'1'": (bytes(rng.integers(0, 2, n).astype(np.uint8) + 48), 1.0),
"moneda con p = 0.1": (bytes((rng.random(n) < 0.1).astype(np.uint8) + 48), None),
"dígitos de π": (pi_digitos, np.log2(10)),
"bytes uniformes": (rng.integers(0, 256, n, dtype=np.uint8).tobytes(), 8.0),
}
h01 = -(0.1 * np.log2(0.1) + 0.9 * np.log2(0.9))
print(f"{'cadena':24s} {'zlib':>8s} {'bz2':>8s} {'entropía':>9s} (bits por carácter)")
for nombre, (b, h) in cadenas.items():
h = h01 if h is None else h
z = 8 * len(zlib.compress(b, 9)) / len(b)
bz = 8 * len(bz2.compress(b, 9)) / len(b)
print(f"{nombre:24s} {z:8.3f} {bz:8.3f} {h:9.3f}")
print("\ncadenas cortas: el tamaño fijo del formato lo domina todo")
for s in [b"hola", b"0110100110", b"ab" * 20]:
print(f" {len(s):3d} bytes -> zlib {len(zlib.compress(s, 9)):3d} bytes, bz2 {len(bz2.compress(s, 9)):3d} bytes")The figures tell the Kolmogorov section’s story. The periodic string compresses to almost nothing, like its short program. A fair coin written as 0/1 characters does not go below 1 bit per character, and the biased coin approaches its -bit entropy without reaching it: the compressors are universal, but their regret versus the best family model is visible with a hundred thousand symbols. The digits of are most instructive: no compressor gets below the bits per digit of a uniform source, although of those hundred thousand digits is the size of a short program computing plus 17 bits for : a few hundred bytes in an ordinary language, compared with over forty thousand needed by bz2 and zlib. Compressors seek statistical regularities, not programs. For short strings, fixed format size dominates: hola goes from 4 bytes to 12 with zlib and 40 with bz2, and even the 40-byte periodic string only falls to 13. The additive constant in person.
Now the complete Bernoulli family: exact parametric complexity, the three codes, and verification that Laplace’s rule applied one datum at a time is the uniform mixture.
import numpy as np
from math import lgamma, log, log2, pi
def log_ml(n, k):
"""log natural de la máxima verosimilitud de una secuencia con k unos."""
f = lambda a: 0.0 if a == 0 else a * log(a / n)
return f(k) + f(n - k)
def log2_C(n):
"""log2 de la suma de Shtarkov, agrupando por número de unos (log-sum-exp)."""
t = np.array([lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1) + log_ml(n, k) for k in range(n + 1)])
m = t.max()
return (m + log(np.exp(t - m).sum())) / log(2)
def regret_mezcla(n, k, a):
"""Regret en bits de la mezcla Beta(a, a) en una secuencia con k unos."""
log_q = lgamma(k + a) + lgamma(n - k + a) - lgamma(n + 2 * a) + lgamma(2 * a) - 2 * lgamma(a)
return (log_ml(n, k) - log_q) / log(2)
print("C_2 =", 2 ** log2_C(2), " log2 C_2 =", round(log2_C(2), 4))
print(f"{'n':>6s} {'log2 Cn':>9s} {'½log2(πn/2)':>12s} {'Laplace máx':>12s} {'log2(n+1)':>10s} {'KT máx':>8s} {'KT − NML':>9s}")
for n in [2, 10, 100, 1000, 10000]:
lc = log2_C(n)
lap = max(regret_mezcla(n, k, 1.0) for k in range(n + 1))
kt = max(regret_mezcla(n, k, 0.5) for k in range(n + 1))
print(f"{n:6d} {lc:9.4f} {0.5 * log2(pi * n / 2):12.4f} {lap:12.4f} {log2(n + 1):10.4f} {kt:8.4f} {kt - lc:9.4f}")
# Laplace dato a dato = mezcla uniforme
x = (np.random.default_rng(3).random(500) < 0.3).astype(int)
bits_seq, unos = 0.0, 0
for t, xt in enumerate(x):
p1 = (unos + 1) / (t + 2)
bits_seq -= log2(p1 if xt == 1 else 1 - p1)
unos += xt
n, k = len(x), int(x.sum())
bits_mezcla = -(lgamma(k + 1) + lgamma(n - k + 1) - lgamma(n + 2)) / log(2)
print(f"\nLaplace secuencial: {bits_seq:.6f} bits mezcla uniforme: {bits_mezcla:.6f} bits")
print(f"máxima verosimilitud: {-log_ml(n, k) / log(2):.3f} bits regret: {bits_seq + log_ml(n, k) / log(2):.3f} bits")The table confirms the figure: Laplace’s worst case is exactly , KT’s differs from NML by slightly under half a bit tending to , and converges to with error already in hundredths for . The final check is the prequential identity: the sum of Laplace-rule surprises and marginal likelihood with uniform prior agree to the last decimal.
Selecting degree with four criteria
Now the first figure’s polynomial regression, with four criteria at once: two-part MDL, BIC, five-fold cross-validation and block prequential length. The reference criterion is the degree best encoding new data, calculable exactly here because we know the true function.
import numpy as np
from numpy.polynomial import legendre as L
f = lambda x: np.sin(np.pi * x) + 0.4 * x
DELTA, DMAX = 0.01, 10
xg = np.linspace(-1, 1, 2001)
def ajuste(x, y, d, lam=0.0):
V = L.legvander(x, d)
return np.linalg.solve(V.T @ V + lam * np.eye(d + 1), V.T @ y)
def dos_partes(x, y, d):
n = len(x)
s2 = np.mean((y - L.legval(x, ajuste(x, y, d))) ** 2)
return n / 2 * np.log2(2 * np.pi * np.e * s2) + n * np.log2(1 / DELTA) + np.log2(DMAX + 1) + (d + 2) / 2 * np.log2(n)
def bic(x, y, d):
n = len(x)
s2 = np.mean((y - L.legval(x, ajuste(x, y, d))) ** 2)
return n * (np.log(2 * np.pi * s2) + 1) + (d + 2) * np.log(n)
def cv(x, y, d, K=5):
idx = np.arange(len(x)) % K
return np.mean([np.mean((y[idx == j] - L.legval(x[idx == j], ajuste(x[idx != j], y[idx != j], d))) ** 2) for j in range(K)])
def precuencial(x, y, d, primero=8, lam=0.01, nu0=2.0, s0=0.5):
bits, ini = primero * np.log2(6 / DELTA), primero # primer bloque: uniforme en [-3, 3]
while ini < len(x):
fin = min(len(x), 2 * ini)
c = ajuste(x[:ini], y[:ini], d, lam)
s2 = (np.sum((y[:ini] - L.legval(x[:ini], c)) ** 2) + nu0 * s0**2) / (ini + nu0)
r = y[ini:fin] - L.legval(x[ini:fin], c)
bits += np.sum(0.5 * np.log2(2 * np.pi * s2) + r**2 / (2 * s2) / np.log(2) + np.log2(1 / DELTA))
ini = fin
return bits
def mejor_para_nuevos(x, y, sigma):
# bits esperados por dato nuevo, con la varianza ajustada y el sesgo exacto frente a f
def coste(d):
c = ajuste(x, y, d)
s2 = np.mean((y - L.legval(x, c)) ** 2)
mse = sigma**2 + np.mean((f(xg) - L.legval(xg, c)) ** 2)
return 0.5 * np.log2(2 * np.pi * s2) + mse / (2 * s2) / np.log(2)
return min(range(DMAX + 1), key=coste)
rng = np.random.default_rng(0)
n, sigma = 60, 0.3
x = rng.uniform(-1, 1, n); y = f(x) + sigma * rng.normal(size=n)
print(" d 2 partes BIC/(2 ln 2) diferencia CV (MSE) precuencial")
for d in range(DMAX + 1):
a, b = dos_partes(x, y, d), bic(x, y, d) / (2 * np.log(2))
print(f"{d:2d} {a:10.2f} {b:14.2f} {a - b:12.2f} {cv(x, y, d):10.4f} {precuencial(x, y, d):13.2f}")
criterios = {"2 partes": dos_partes, "CV": cv, "precuencial": precuencial}
cuentas = {c: np.zeros(DMAX + 1, int) for c in [*criterios, "datos nuevos"]}
for rep in range(40):
r = np.random.default_rng(100 + rep)
x = r.uniform(-1, 1, n); y = f(x) + sigma * r.normal(size=n)
for c, fn in criterios.items():
cuentas[c][min(range(DMAX + 1), key=lambda d: fn(x, y, d))] += 1
cuentas["datos nuevos"][mejor_para_nuevos(x, y, sigma)] += 1
print("\ngrado elegido en 40 conjuntos de datos (columnas: grado 0 a 10)")
for c, v in cuentas.items():
print(f"{c:13s}", " ".join(f"{k:2d}" for k in v))The “difference” column is constant: two-part code and differ by , terms independent of degree, so always choose the same. In the first dataset, the table shows four forms of the same tradeoff: training likelihood keeps improving through degree 10, cross-validation MSE flattens from degree 3, and prequential coding mercilessly penalizes high degrees (degree 9 overfits initial blocks and costs almost triple). Across forty datasets, the reference is mostly degree 3 or 5 (and 6 in a few), since with and the difference is small. Two-part MDL and prequential pick 3 in over three quarters of cases: conservative by design, accepting a parameter only if it pays its bits. Cross-validation chooses 5 more often, like the reference, but disperses more and occasionally chooses degrees 7–9: it measures prediction error with the variance of a small validation set. Repeat with more data (change n): two-part MDL moves to degree 5 and stays there (40 of 40 with ), while cross-validation chooses degrees 6–10 in a third of cases. Do not read this as cross-validation error: the true function is not a polynomial, so no true degree exists, and with the reference also chooses degrees 6–8 in 12 of the 40 sets. MDL gives a stable, cautious answer; cross-validation follows the best predictor more closely, with more variance. In miniature, this is the difference between BIC-like and AIC-like criteria in the debates section.
Gaussian mixtures: how many components?
The same analysis with a model genuinely nonlinear in its parameters. Use scikit-learn’s GaussianMixture for fitting; its bic method is with the number of free parameters, so is two-part length in bits up to constants.
import numpy as np
from sklearn.mixture import GaussianMixture
rng = np.random.default_rng(1)
medias = np.array([[0, 0], [3, 0.5], [1.2, 2.6]])
covs = [np.array([[1.0, 0.6], [0.6, 0.8]]), np.diag([0.4, 1.2]), np.diag([0.6, 0.3])]
etiq = rng.integers(0, 3, 600)
X = np.stack([rng.multivariate_normal(medias[c], covs[c]) for c in etiq])
X = X[rng.permutation(len(X))]
LN2 = np.log(2)
def gmm(K, datos):
return GaussianMixture(K, covariance_type="full", n_init=2, random_state=0).fit(datos)
def precuencial(K, X, cortes=(50, 100, 200, 400, 600)):
# primer bloque: gaussiana ancha fija (igual para todos los K); después, la mezcla ajustada al pasado
bits = -np.sum(-0.5 * np.sum((X[:cortes[0]] / 4) ** 2, 1) - np.log(2 * np.pi * 16)) / LN2
for a, b in zip(cortes[:-1], cortes[1:]):
bits -= gmm(K, X[:a]).score_samples(X[a:b]).sum() / LN2
return bits
def cv(K, X, P=3):
idx = np.arange(len(X)) % P
return -sum(gmm(K, X[idx != j]).score_samples(X[idx == j]).sum() for j in range(P)) / LN2
print(" K −log2 p(D|θ̂) (k/2) log2 n 2 partes CV (bits) precuencial")
for K in range(1, 7):
g = gmm(K, X)
k = g._n_parameters()
ll = g.score(X) * len(X) / LN2
print(f"{K:2d} {-ll:13.1f} {k / 2 * np.log2(len(X)):14.1f} {g.bic(X) / (2 * LN2):10.1f} {cv(K, X):11.1f} {precuencial(K, X):13.1f}")Training likelihood always improves with ; the parameter term, with in two dimensions, grows by about 28 bits per component. All three criteria select the three components used to generate the data. The difference is how clearly: cross-validation separates from by only 6 bits, while two-part and prequential coding charge over 70 bits to the six-component mixture. In prequential coding, this penalty comes from no formula: fitting six full-covariance Gaussians to 50 or 100 points yields poorly estimated components that predict the next block worse. This is the prequential figure’s large model in another family.
Description length of a network
The final cell follows Blier and Ollivier on a laptop scale: multilayer perceptrons of different widths on a two-spiral problem, encoded in blocks doubling from 64 to 2048 examples. Each block is encoded by a network trained from scratch with the same seed on all previous data; the first block uses the uniform code of 1 bit per label. The loop is the usual training loop, and the formula translates directly to tensors (from equations to PyTorch). It runs on CPU in seconds.
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # experimento pequeño: CPU
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.set_num_threads(2)
rng = np.random.default_rng(0)
def espirales(n):
c = rng.integers(0, 2, n)
t = np.sqrt(rng.uniform(0.02, 1, n)) * 3 * np.pi
X = np.stack([t * np.cos(t + c * np.pi), t * np.sin(t + c * np.pi)], 1) / (3 * np.pi)
X += 0.05 * rng.normal(size=X.shape)
return torch.tensor(X, dtype=torch.float32), torch.tensor(c)
X, y = espirales(2048)
Xv, yv = espirales(4000)
cortes = [64, 128, 256, 512, 1024, 2048]
def red(h):
torch.manual_seed(0)
return nn.Sequential(nn.Linear(2, h), nn.Tanh(), nn.Linear(h, h), nn.Tanh(), nn.Linear(h, 2))
def entrenar(h, X, y, pasos=300):
m = red(h)
opt = torch.optim.Adam(m.parameters(), lr=1e-2, weight_decay=1e-4)
for _ in range(pasos):
opt.zero_grad()
F.cross_entropy(m(X), y).backward()
opt.step()
return m
@torch.no_grad()
def bits(m, X, y):
return F.cross_entropy(m(X), y, reduction="sum").item() / math.log(2)
print(f"{'ancho':>5s} {'parámetros':>10s} {'precuencial':>12s} {'bits/ej.':>9s} {'val. bits/ej.':>13s} {'2 partes a 32 bits':>19s}")
for h in [2, 8, 32, 128]:
total = cortes[0] * 1.0 # primer bloque: 1 bit por etiqueta
for a, b in zip(cortes[:-1], cortes[1:]):
total += bits(entrenar(h, X[:a], y[:a]), X[a:b], y[a:b])
final = entrenar(h, X, y)
P = sum(p.numel() for p in final.parameters())
print(f"{h:5d} {P:10d} {total:12.0f} {total / len(X):9.3f} {bits(final, Xv, yv) / len(Xv):13.3f} {32 * P + bits(final, X, y):19.0f}")
print(f"código uniforme: {len(X)} bits")npm run lab and open the connection link.Output reproduces three observations from the paper. The two-part calculation at 32 bits per weight is absurd: even the width-8 network “costs” almost twice the uniform code for 2048 labels (3932 bits versus 2048), and width 128 more than 250 times as much. Prequential length is far below the uniform code once the network can learn the spirals: width 32 describes 2048 labels in about 137 bits, fifteen times less, with 1218 parameters. Networks do compress, and the ordering of prequential lengths (32, 128, 8, 2) matches final-model validation loss. Parameter count does not predict that order: width 128 has fourteen times more parameters than width 32 but almost the same length (149 bits), while width 2, with 18 parameters, compresses worst because it cannot represent the boundary. What counts is how fast each network learns structure from available data.
Limitations and debates
Choosing a code is a choice. MDL says what to do after choosing a code, but you choose the code (family, mixture prior, two-part discretization, prequential estimator). For regular families and large , NML removes arbitrariness; for families with (for example, a Gaussian with free mean on all ), one must restrict the range or condition on initial data, again your choice. Grünwald calls this luckiness: a code paying less in expected regions and more elsewhere, with explicit guarantees on the cost of being wrong.
MDL versus Bayesianism. A Bayesian mixture is a code. The philosophical difference has practical consequences: MDL does not assume a family model is true, only seeks regularities. Grünwald and van Ommen (2017) showed that under misspecification standard Bayesian inference can persistently overfit, and proposed tempering likelihood with an MDL-selected learning rate (“safe” Bayes).
MDL versus cross-validation. Prequential length is forward cross-validation with log loss, and leave-one-out cross-validation is asymptotically equivalent to AIC (Stone, 1977), not BIC. BIC- and MDL-like criteria are consistent (select the true model if among candidates); AIC-like criteria are prediction-efficient when it is not, and Yang (2005) proved no criterion can have both properties. Whether you want model identification or good prediction determines the criterion.
Common mistakes
Exercises
Step 1 of 4. Which property of lets you make a program for from ?
Step 1 of 3. What lower bound do you have for ?
preq_lineal(X, y, alpha, sigma2): the prequential length, in nats, of responses y (shape (n,)) from Bayesian linear regression with design X (shape (n, d)), prior and Gaussian noise of known variance . Traverse observations in order: encode using the posterior predictive given the preceding , , add of its density and update posterior . Tests check agreement with of marginal likelihood and independence of order. Do not use the marginal formula in your function.import numpy as np
def preq_lineal(X, y, alpha, sigma2):
"""Longitud precuencial (nats) de y con regresión lineal bayesiana actualizada dato a dato."""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
n, d = X.shape
m = np.zeros(d) # media posterior
S = np.eye(d) / alpha # covarianza posterior
total = 0.0
# tu código: para cada t, media y varianza predictivas, -log densidad y actualización de (m, S)
return totalSummary
- Kolmogorov complexity , the length of the shortest program printing , is invariant up to a constant and uncomputable. Almost all strings are incompressible, and average is entropy. Real compressors give upper bounds.
- Two-part MDL picks the model minimizing . Each parameter is written to its typical error precision, , costing bits: the length is BIC in bits.
- A universal code pays regret over the best model after the fact. Shtarkov’s NML is minimax with flat regret ; the Jeffreys-prior mixture (KT for Bernoulli) matches it asymptotically and Laplace pays twice as much in the worst case.
- Worst expected excess is capacity of the parameter data channel: a universal code pays exactly the information data carry about the parameter.
- Prequential length sums each observation’s surprise under a model trained on predecessors: it is area under the online loss curve, needs no parameters transmitted and, for a Bayesian mixture, is marginal likelihood independent of order.
- In deep learning, block prequential coding shows networks compress their data despite having far more parameters than label bits; it underlies MDL probing and reading an LM as its training curve.