Module contents
Lesson 18 of 19Advanced 115 min

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

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, 2−1062^{-10^6}, 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 −log⁡2q(xn)-\log_2 q(x^n) bits, within two bits. The missing half is that the receiver must also know the model. This lesson builds it in four steps:

  1. The shortest possible description, Kolmogorov complexity: the ideal, which turns out to be uncomputable.
  2. Two-part MDL: describe the model first and then the data with it, discovering that each parameter costs 12log⁡2n\tfrac12\log_2 n bits.
  3. Universal codes: instead of choosing one model, encode with a mixture over the family and measure the price of not knowing the parameter (regret).
  4. 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, log⁡\log is base 2 and lengths are measured in bits; ln⁡\ln 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 UU that reads binary programs. Also require it to be prefix-free: the set of programs on which UU 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 xx literally: “print what follows.” The prefix version must say where it ends, for example by first writing ℓ(x)\ell(x) with a self-delimiting code, so K(x)≤ℓ(x)+2log⁡ℓ(x)+cK(x) \le \ell(x) + 2\log \ell(x) + c. A string is never much more complex than its length.
  • Most strings are incompressible. There are 2n2^n strings of length nn and fewer than 2n−k2^{n-k} programs of length less than n−kn - k. Thus at most a fraction 2−k2^{-k} of length-nn strings admit a description kk bits shorter. Fewer than one string in a million can be compressed by 20 bits.
  • Regular strings are highly compressible. The first nn bits of the binary expansion of π\pi have K≤log⁡n+2log⁡log⁡n+cK \le \log n + 2\log\log n + c: a program calculating π\pi and the number nn suffice.

The second point is the motivation’s counting argument. If a model-selection procedure gives a description of your data kk bits shorter than the uniform code, the probability of this happening with unstructured data is at most 2−k2^{-k}. 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 UU. Surprisingly, it depends very little.

The proof idea, which you will work through in the exercises, is that UU can simulate VV with a fixed-length interpreter: any program for VV becomes one for UU by prepending the interpreter. This is why we often write K(x)K(x) without a subscript: it is defined up to an additive constant.

Uncomputability

Proof

Suppose one exists. For each nn, consider program PnP_n: “enumerate strings in length order, and lexicographically within each length; calculate KK for each and return the first xx with K(x)≥nK(x) \ge n.” Such a string exists because incompressible strings exist at every length. But PnP_n is a fixed program needing only nn, so its length is log⁡n+2log⁡log⁡n+c\log n + 2\log\log n + c, and the string xnx_n it prints satisfies

n≤K(xn)≤log⁡n+2log⁡log⁡n+c,n \le K(x_n) \le \log n + 2\log\log n + c,

which is false for sufficiently large nn. 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 xx we would have to know which short programs terminate. We can approximate KK from above: run all programs in parallel, interleaving steps, and whenever one prints xx, update the best length found. The bounds decrease to K(x)K(x), 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 xx algorithmically random if K(x)≥ℓ(x)−cK(x) \ge \ell(x) - c 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: K(x1:n)≥n−cK(x_{1:n}) \ge n - c for every nn. The connection with Shannon entropy is precise.

Proof

Lower bound: for fixed nn, shortest programs for strings of length nn form a prefix code, because UU is prefix-free. By the expected length bounds, no prefix code has average length below entropy, E[K(Xn∣n)]≥H⁡(Xn)=nH⁡(X)\E[K(X^n \given n)] \ge \Ent(X^n) = n\Ent(X).

Upper bound: describe xnx^n in two parts. First its type, the frequency vector p^\hat p, taking at most (n+1)∣X∣−1(n+1)^{\abs{\mathcal{X}}-1} values; then the index of xnx^n within its type class, which has at most 2nH⁡(p^)2^{n\Ent(\hat p)} elements (as in the method of types). This gives K(xn∣n)≤nH⁡(p^)+(∣X∣−1)log⁡(n+1)+cK(x^n \given n) \le n\Ent(\hat p) + (\abs{\mathcal{X}}-1)\log(n+1) + c. Take expectations and use concavity of H⁡\Ent: E[H⁡(p^)]≤H⁡(Ep^)=H⁡(p)\E[\Ent(\hat p)] \le \Ent(\E\hat p) = \Ent(p).

∎

Notice the upper bound’s shape: the data cost nH⁡(p^)n\Ent(\hat p) and the model (type, or multinomial parameter) costs order log⁡n\log n per free parameter. This is the first appearance of a pattern we will see three more times, with the constant refined to 12log⁡n\tfrac12\log n.

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 qq on a discrete set gives a prefix code with lengths ⌈−log⁡q(x)⌉\lceil -\log q(x) \rceil, and every prefix code with lengths ℓ(x)\ell(x) gives a (sub)distribution q(x)=2−ℓ(x)q(x) = 2^{-\ell(x)}. Ignoring rounding, which costs at most two bits total with arithmetic coding,

longitud de coˊdigo=−log⁡(probabilidad).\text{longitud de código} = -\log(\text{probabilidad}).

From here, “encode with qq” and “assign probability qq” mean the same thing. For continuous data, discretize to fixed precision δ\delta; the length is −log⁡(p(x) δ)=−log⁡p(x)+log⁡(1/δ)-\log(p(x)\,\delta) = -\log p(x) + \log(1/\delta) per datum. The term log⁡(1/δ)\log(1/\delta) 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 L(D∣M)L(D \given M) falls: this is training loss in bits, and never increases when parameters are added. But each parameter must be written, and L(M)L(M) grows. Their sum has a minimum, and that minimum is the MDL choice.

How much does a parameter cost?

For L(M)L(M) to be finite, the parameter is written at finite precision: choose a grid of step δ\delta over its range and transmit grid point θδ\theta_\delta nearest the maximum likelihood estimate θ^\hat\theta. A tradeoff appears. With a fine grid, θδ≈θ^\theta_\delta \approx \hat\theta and data cost is minimal, but writing the parameter is expensive. With a coarse grid, the parameter is cheap but θδ\theta_\delta moves away from θ^\hat\theta and the data cost increases.

Proof

The first term is the uniform code length over R/δR/\delta cells. For the second, expand −ln⁡pθ(D)-\ln p_\theta(D) around θ^\hat\theta. The gradient vanishes at the maximum and curvature is observed information, which for large nn is nI(θ^)n I(\hat\theta) (the same quadratic approximation as the Fisher metric as local KL):

−ln⁡pθδ(D)≈−ln⁡pθ^(D)+nI(θ^)2(θδ−θ^)2.-\ln p_{\theta_\delta}(D) \approx -\ln p_{\hat\theta}(D) + \frac{n I(\hat\theta)}{2}(\theta_\delta - \hat\theta)^2.

With uniform error, E[(θδ−θ^)2]=δ2/12\E[(\theta_\delta - \hat\theta)^2] = \delta^2/12, giving the third term. Differentiation yields −1/δ+nIδ/12=0-1/\delta + n I\delta/12 = 0, hence δ∗=12/(nI)\delta^* = \sqrt{12/(nI)}. Substitution gives ln⁡(R/δ∗)=12ln⁡n+12ln⁡(IR2/12)\ln(R/\delta^*) = \tfrac12\ln n + \tfrac12\ln(I R^2/12) and nIδ∗2/24=12nI\delta^{*2}/24 = \tfrac12.

∎

The conclusion is one of statistics’ most reusable formulas: the worthwhile precision for writing a parameter is of the order of its typical error, 1/n1/\sqrt n, costing 12log⁡n\tfrac12\log n bits per parameter, plus a constant not growing with nn. More precision wastes bits: the difference is below estimation noise. With kk parameters, rotating to the Fisher matrix’s eigenaxes gives cost k2log⁡n+O(1)\tfrac{k}{2}\log n + O(1) and two-part length

L2p(D)=−log⁡pθ^(D)+k2log⁡n+O(1).L_{2p}(D) = -\log p_{\hat\theta}(D) + \frac{k}{2}\log n + O(1).

In nats, this is half the Bayesian information criterion, BIC=−2ln⁡pθ^(D)+kln⁡n\mathrm{BIC} = -2\ln p_{\hat\theta}(D) + k\ln n. 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 nn points yi=sin⁡(πxi)+0.4 xi+εiy_i = \sin(\pi x_i) + 0.4\,x_i + \eps_i with Gaussian noise of standard deviation σ\sigma, recorded to two decimals (δ=0.01\delta = 0.01). The degree-dd model has k=d+2k = d + 2 parameters (the d+1d + 1 coefficients and noise variance), and

L(D∣d)=n2log⁡(2πe σ^d2)+nlog⁡1δ,L(d)=log⁡13+k2log⁡n,L(D \given d) = \frac{n}{2}\log\big(2\pi e\,\hat\sigma_d^2\big) + n\log\frac1\delta, \qquad L(d) = \log 13 + \frac{k}{2}\log n,

where σ^d2\hat\sigma_d^2 is the maximum-likelihood residual variance and log⁡13\log 13 encodes the degree from 0 to 12.

InteractiveOccam in bits
−2−1012−101degree 9Description length by degree (bits)2502753003253500123456789101112mindegree d · truncated axis: starts at 240 bits
  • data
  • truth
  • fit of chosen degree
  • L(D∣M)L(D \mid M)
  • L(M)L(M)
  • nn new data with the fit
9
0.30
40
Cost per parameter
L(M)L(M), bits33.0
L(D∣M)L(D \mid M), bits274.5
Total, bits307.5
Degree chosen by MDL3
Optimum on new data3
Training σ^\hat\sigma0.282
Degree 9 saves 5.1 data bits but pays 16.0 model bits: 10.8 bits more than degree 3.
Above: data (blue), true function (dashed), and polynomial of the selected degree (red). Below: for each degree, data length given the model (blue), with model length stacked on top (orange); the axis starts well above zero so the relevant differences are visible. Magenta diamonds show the bits needed to encode nn new observations with each fit. Start at degree 9: the fit wiggles and the total bar exceeds the minimum. Click the minimum bar. Raise noise to 0.8 and lower nn to 20: the minimum becomes a line. With n=200n = 200 and noise 0.3, MDL stays at degree 3 while the diamonds already favor 5. Then try Free (maximum likelihood) and 32 bits.

Three things the figure shows:

  1. 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.
  2. 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.
  3. Parameter precision is part of the model. With 32 bits per parameter (one float32 per 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 O(1)O(1) constant. Refined MDL fixes both with a cleaner idea: transmit no parameter.

Universal codes and regret

Fix a family M={pθ:θ∈Θ}\mathcal{M} = \{p_\theta : \theta \in \Theta\}. If you knew in advance which θ\theta to use, you would encode xnx^n in −log⁡pθ(xn)-\log p_\theta(x^n) bits. The best θ\theta for particular data is the maximum-likelihood choice θ^(xn)\hat\theta(x^n), but this depends on the data and is not a code: ∑xnpθ^(xn)(xn)>1\sum_{x^n} p_{\hat\theta(x^n)}(x^n) > 1. The question is how much is lost with a single code qq that must work for all possible data.

Three classical constructions each illuminate an aspect.

Bayesian mixture. Fix a prior ww on Θ\Theta and encode with qw(xn)=∫pθ(xn) w(θ) ⁣dθq_w(x^n) = \int p_\theta(x^n)\,w(\theta)\dd\theta, the marginal likelihood. For a finite family of MM models and a uniform prior, regret is at most log⁡M\log M (proved in the exercises): the mixture never loses more than the cost of saying which of the MM models to use. For the Bernoulli family, with kk ones in nn tosses and prior Beta(a,a)\mathrm{Beta}(a, a),

qa(xn)=B(k+a,  n−k+a)B(a,a).q_a(x^n) = \frac{B(k + a,\; n - k + a)}{B(a, a)}.

With a=1a = 1 (uniform prior) this is Laplace’s rule; with a=12a = \tfrac12, the Krichevsky–Trofimov (KT) estimator, the mixture with Jeffreys prior w(θ)∝I(θ)=1/θ(1−θ)w(\theta) \propto \sqrt{I(\theta)} = 1/\sqrt{\theta(1-\theta)}.

NML. Shtarkov (1987) asked which code has minimum worst-case regret. The answer is the normalized maximum likelihood distribution:

pNML(xn)=pθ^(xn)(xn)Cn,Cn=∑yn∈Xnpθ^(yn)(yn).p_{\mathrm{NML}}(x^n) = \frac{p_{\hat\theta(x^n)}(x^n)}{C_n}, \qquad C_n = \sum_{y^n \in \mathcal{X}^n} p_{\hat\theta(y^n)}(y^n).
Proof

By definition, REG(pNML,xn)=log⁡(pθ^(xn)(xn)/pNML(xn))=log⁡Cn\mathrm{REG}(p_{\mathrm{NML}}, x^n) = \log\big(p_{\hat\theta(x^n)}(x^n)/p_{\mathrm{NML}}(x^n)\big) = \log C_n for every xnx^n. Let q≠pNMLq \neq p_{\mathrm{NML}} be another distribution. Since both sum to 1, some sequence xnx^n has q(xn)<pNML(xn)q(x^n) < p_{\mathrm{NML}}(x^n), and its REG(q,xn)>log⁡Cn\mathrm{REG}(q, x^n) > \log C_n. Thus every other qq has a strictly larger maximum.

∎

COMPn(M)=log⁡Cn\mathrm{COMP}_n(\mathcal{M}) = \log C_n is the family’s parametric complexity: the exact price in bits of not knowing the parameter. Two-part coding approximated it crudely by k2log⁡n\tfrac{k}{2}\log n. For Bernoulli with n=2n = 2, sequences 0000 and 1111 have maximum likelihood 1 and 0101 and 1010 have 14\tfrac14 each, so C2=2.5C_2 = 2.5. For general nn, grouping by number of ones,

Cn=∑k=0n(nk)(kn)k(n−kn)n−k.C_n = \sum_{k=0}^{n}\binom{n}{k}\Big(\frac{k}{n}\Big)^k\Big(\frac{n-k}{n}\Big)^{n-k}.
InteractiveUniversal code regret
024010203040number of ones k in sequence (n = 40)regret (bits)Worst case versus length051014166425610244096n (logarithmic scale)slope 1slope ½
  • Laplace, Beta(1, 1)
  • KT, Beta(½, ½)
  • NML: log⁡2Cn\log_2 C_n
  • 12log⁡2(πn/2)\tfrac12\log_2(\pi n/2)
40
10 of 40
Laplace at this kk2.565
KT at this kk2.998
NML, log⁡2Cn\log_2 C_n3.106
Laplace worst case5.358
KT worst case3.491
12log⁡2(πn/2)\tfrac12\log_2(\pi n/2)2.987
Above: regret of each code versus the number of ones kk in a sequence of length nn. NML (purple) is flat: it pays log⁡2Cn\log_2 C_n everywhere. KT (aqua) is nearly flat and Laplace (orange) shoots up at the edges. Below: each worst case against nn on a logarithmic scale: Laplace grows with slope 1, the others with slope ½, close to the asymptotic reference. Move kk to 0 and compare all three. Increase nn and watch the gap between KT and NML at the edges stabilize at half a bit.

What the figure teaches:

  • Laplace’s worst case is log⁡(n+1)\log(n+1), on constant sequences: with k=0k = 0, q1(0n)=1/(n+1)q_1(0^n) = 1/(n+1) and maximum likelihood is 1. Its regret grows like log⁡n\log n, twice what is needed. The uniform prior places little mass near θ=0\theta = 0, exactly where the likelihood of a constant sequence concentrates.
  • KT pays 12log⁡(πn)\tfrac12\log(\pi n) at the edges and slightly less than log⁡Cn\log C_n 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.
  • log⁡Cn\log C_n hugs 12log⁡(πn/2)\tfrac12\log(\pi n/2): for n=1000n = 1000, 5.3335.333 versus 5.3095.309 bits.

Asymptotic form and Fisher information

The 12log⁡n\tfrac12\log n per-parameter pattern has a geometrically meaningful constant.

The integral ∫det⁡I\int\sqrt{\det I} is the volume of Θ\Theta in the Fisher metric, with a clear interpretation: with nn data points, two parameters are distinguishable if their Fisher distance exceeds roughly 1/n1/\sqrt n, so Θ\Theta fits on the order of (n/2π)k/2∫det⁡I(n/2\pi)^{k/2}\int\sqrt{\det I} distinguishable distributions. Parametric complexity is the logarithm of that count: count distinguishable distributions, not parameters. For Bernoulli, ∫01 ⁣dθ/θ(1−θ)=π\int_0^1 \dd\theta/\sqrt{\theta(1-\theta)} = \pi and the formula gives 12log⁡(n/2π)+log⁡π=12log⁡(πn/2)\tfrac12\log(n/2\pi) + \log\pi = \tfrac12\log(\pi n/2), the figure’s reference curve.

The Bayesian mixture has the same form. By Laplace’s method applied to ∫pθ(xn)w(θ) ⁣dθ\int p_\theta(x^n)w(\theta)\dd\theta,

−log⁡qw(xn)=−log⁡pθ^(xn)+k2log⁡n2π+12log⁡det⁡I(θ^)−log⁡w(θ^)+o(1).-\log q_w(x^n) = -\log p_{\hat\theta}(x^n) + \frac{k}{2}\log\frac{n}{2\pi} + \frac12\log\det I(\hat\theta) - \log w(\hat\theta) + o(1).

Regret depends on θ^\hat\theta through 12log⁡det⁡I(θ^)−log⁡w(θ^)\tfrac12\log\det I(\hat\theta) - \log w(\hat\theta), and is constant precisely when w∝det⁡Iw \propto \sqrt{\det I}: Jeffreys prior makes the mixture asymptotically minimax, equating it to NML in the interior of Θ\Theta. 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 pθp_\theta: redundancy of qq is D(pθ ∥ q)=Eθ[−log⁡q(Xn)]−H⁡θ(Xn)D(p_\theta \,\|\, q) = \E_\theta[-\log q(X^n)] - \Ent_\theta(X^n), a KL divergence. The minimax problem connects this lesson with channels.

Proof

We prove the ≥\ge inequality, which supplies the intuition; the other needs a minimax theorem for convex–concave functions. For any prior ww and any qq,

∫w(θ)D(pθ ∥ q) ⁣dθ=∫w(θ)D(pθ ∥ qw) ⁣dθ+D(qw ∥ q)≥∫w(θ)D(pθ ∥ qw) ⁣dθ=I(Θ;Xn).\int w(\theta) D(p_\theta \,\|\, q)\dd\theta = \int w(\theta) D(p_\theta \,\|\, q_w)\dd\theta + D(q_w \,\|\, q) \ge \int w(\theta) D(p_\theta \,\|\, q_w)\dd\theta = I(\Theta; X^n).

The middle equality follows by adding logarithms: log⁡pθq=log⁡pθqw+log⁡qwq\log\frac{p_\theta}{q} = \log\frac{p_\theta}{q_w} + \log\frac{q_w}{q}, and the second term averaged with w(θ)pθ(x)w(\theta)p_\theta(x) gives D(qw ∥ q)D(q_w \,\|\, q). The last equality is the definition of mutual information as average KL to the marginal. Since the supremum over θ\theta exceeds the average under ww, sup⁡θD(pθ ∥ q)≥Iw(Θ;Xn)\sup_\theta D(p_\theta \,\|\, q) \ge I_w(\Theta; X^n) for every qq and ww.

∎

Read backwards: the universal code’s toll is the information data carry about the parameter. With nn data points, θ\theta can be estimated to precision 1/n1/\sqrt n in each of kk directions, the channel transmits about k2log⁡n\tfrac{k}{2}\log n bits about θ\theta, and this is exactly what the code cannot avoid paying. Clarke and Barron (1994) gave the exact form: minimax redundancy is k2log⁡n2πe+log⁡∫det⁡I+o(1)\tfrac{k}{2}\log\frac{n}{2\pi e} + \log\int\sqrt{\det I} + o(1), differing from NML regret by k2log⁡e\tfrac{k}{2}\log e because regret compares with each sequence’s θ^\hat\theta and redundancy with the true θ\theta.

Prequential coding

The most practical construction remains. By the chain rule, any distribution on sequences factors into predictions, q(xn)=∏tq(xt∣xt−1)q(x^n) = \prod_t q(x_t \given x^{t-1}), 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 q(xt∣xt−1)=∫pθ(xt∣xt−1) w(θ∣xt−1) ⁣dθq(x_t \given x^{t-1}) = \int p_\theta(x_t \given x^{t-1})\,w(\theta \given x^{t-1})\dd\theta is the posterior predictive, the product of predictives is, by the chain rule, exactly the marginal likelihood:

∏t=1nqw(xt∣xt−1)=∏t=1nqw(xt)qw(xt−1)=qw(xn).\prod_{t=1}^n q_w(x_t \given x^{t-1}) = \prod_{t=1}^n\frac{q_w(x^t)}{q_w(x^{t-1})} = q_w(x^n).

Laplace’s rule is the uniform mixture predictive, q(1∣xt−1)=(kt−1+1)/(t+1)q(1 \given x^{t-1}) = (k_{t-1} + 1)/(t + 1), with kt−1k_{t-1} the number of ones seen. Encoding one datum at a time with it gives the same length as the mixture. Since qw(xn)q_w(x^n) 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 q(⋅∣xt−1)=pθ^(xt−1)q(\cdot \given x^{t-1}) = p_{\hat\theta(x^{t-1})} 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 k2log⁡n+O(1)\tfrac{k}{2}\log n + O(1). In the worst case over sequences, or under misspecification, a point estimator may pay substantially more than the mixture. Intuition: the error of θ^\hat\theta with tt data is order 1/t1/\sqrt t, each prediction pays excess order k/(2t)k/(2t) nats, and ∑tk/(2t)≈k2ln⁡n\sum_t k/(2t) \approx \tfrac{k}{2}\ln n.

In blocks, as with networks

Retraining after every datum is infeasible for a network. Blier and Ollivier (2018) proposed a block version: choose times t1<t2<⋯<tS=nt_1 < t_2 < \cdots < t_S = n, usually geometrically spaced; encode the first block with a uniform code; train the model on the first t1t_1 observations and use it to encode t1+1t_1 + 1 to t2t_2; retrain on the first t2t_2 and encode the next block, and so on. Length is

Lpreq=t1log⁡∣Y∣+∑s=1S−1  ∑t=ts+1ts+1−log⁡pθ^s(yt∣xt),L_{\mathrm{preq}} = t_1\log\abs{\mathcal{Y}} + \sum_{s=1}^{S-1}\;\sum_{t = t_s + 1}^{t_{s+1}} -\log p_{\hat\theta_s}(y_t \given x_t),

where θ^s\hat\theta_s is the model trained on the first tst_s data. If you plot average block loss against the data count, length is the area under the online loss curve.

InteractivePrequential length
fits with 128 points481216uniform code050100150200250bits per point · area is lengthCumulative L(large) − L(small), bitsabove 0 the small model leads; below, the large model−50050050100150200250encoded data
  • small, degree 1
  • large, degree 9
  • block being encoded
  • cumulative difference
block 7 of 7
256
0.30
Predictor
Small (degree 1), bits2015
Large (degree 9), bits1953
Uniform code, bits2363
Large model wins from n≈n \approx150
Small across 20 orders…
Large across 20 orders…
With 256 data points the large model has recovered its startup cost and wins by 62 bits: each new block costs less because it captures curvature the small model cannot see.
Two polynomial regressions, degree 1 (orange) and degree 9 (purple), over NN data generated by the first figure's function. Each block (blue in the left diagram) is encoded using the fit to all previous blocks; block sizes double: 4, 8, 16... In the bits-per-point panel, the shaded area under each curve is its description length. Below is their cumulative difference: above zero, the small model is winning. Play through blocks: the large model starts worse (fitted on 4 or 8 points, it overfits) and ends below. Reduce NN to 64: the small model wins. Increase noise to 0.5 and NN to 1024: crossover is delayed by hundreds of observations. Shuffle the order several times and watch how much crossover moves. Finally switch to the Bayesian mixture.

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 N=256N = 256 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 kk-parameter family the four lengths agree through the k2log⁡n\tfrac{k}{2}\log n term:

CodeLength of xnx^nO(1)O(1) term
Two-part−log⁡pθ^(xn)+k2log⁡n+O(1)-\log p_{\hat\theta}(x^n) + \tfrac{k}{2}\log n + O(1)depends on discretization
Bayesian mixture−log⁡pθ^(xn)+k2log⁡n2π+12log⁡det⁡I(θ^)−log⁡w(θ^)-\log p_{\hat\theta}(x^n) + \tfrac{k}{2}\log\frac{n}{2\pi} + \tfrac12\log\det I(\hat\theta) - \log w(\hat\theta)depends on the prior
NML−log⁡pθ^(xn)+k2log⁡n2π+log⁡∫det⁡I-\log p_{\hat\theta}(x^n) + \tfrac{k}{2}\log\frac{n}{2\pi} + \log\int\sqrt{\det I}intrinsic to the family
Prequential (plug-in)−log⁡pθ^(xn)+k2log⁡n+O(1)-\log p_{\hat\theta}(x^n) + \tfrac{k}{2}\log n + O(1), in expectationdepends 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 kk and different geometric complexity, and for small nn the discarded term may exceed the difference measured.

The second row merits its own sentence: −log⁡-\log 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 1.28×106×log⁡1000≈1.3×1071.28\times 10^6 \times \log 1000 \approx 1.3\times 10^7 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 q(w)q(\vb{w}) over them, with a coding trick, bits-back: the sender chooses w∼q\vb{w} \sim q using bits of an auxiliary message, sends w\vb{w} with prior code p(w)p(\vb{w}) and data with p(D∣w)p(D \given \vb{w}), and the receiver, able to reconstruct qq, recovers the auxiliary bits. Net cost is

L=Eq[−log⁡p(D∣w)]+KL⁡(q ∥ p),L = \E_{q}\big[-\log p(D \given \vb{w})\big] + \KL(q \,\|\, p),

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 h(x)h(x) “encodes” a linguistic property yy, train a simple classifier (probe) from h(x)h(x) to yy 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 K(x)K(x) up to a constant; see how good it is on strings with known structure.

[ ]Upper bounds on K using real compressorsBrowser
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 0.4690.469-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 π\pi are most instructive: no compressor gets below the log⁡210=3.32\log_2 10 = 3.32 bits per digit of a uniform source, although KK of those hundred thousand digits is the size of a short program computing π\pi plus 17 bits for nn: 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.

[ ]Exact NML, Laplace and KT for BernoulliBrowser
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 log⁡2(n+1)\log_2(n+1), KT’s differs from NML by slightly under half a bit tending to 0.50.5, and log⁡2Cn\log_2 C_n converges to 12log⁡2(πn/2)\tfrac12\log_2(\pi n/2) with error already in hundredths for n=1000n = 1000. 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.

[ ]Two-part MDL, BIC, cross-validation and prequential codingBrowser
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 BIC/(2ln⁡2)\mathrm{BIC}/(2\ln 2) differ by nlog⁡2(1/δ)+log⁡211n\log_2(1/\delta) + \log_2 11, 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 n=60n = 60 and σ=0.3\sigma = 0.3 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 12log⁡n\tfrac12\log n 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 n=2000n = 2000), 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 n=2000n = 2000 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 −2ln⁡pθ^(D)+kln⁡n-2\ln p_{\hat\theta}(D) + k\ln n with kk the number of free parameters, so BIC/(2ln⁡2)\mathrm{BIC}/(2\ln 2) is two-part length in bits up to constants.

[ ]Number of Gaussian mixture componentsBrowser
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 KK; the parameter term, (k/2)log⁡2n(k/2)\log_2 n with k=6K−1k = 6K - 1 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 K=3K = 3 from K=4K = 4 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.

[ ]Prequential length of perceptrons (CPU)Local GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 nn, NML removes arbitrariness; for families with Cn=∞C_n = \infty (for example, a Gaussian with free mean on all R\R), 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

QuizKolmogorov for model selection
Why is Kolmogorov complexity K(D)K(D) not used directly to choose between models, and what replaces it in practice?
NumericParametric complexity with two tosses
Compute in bits the NML parametric complexity log⁡2C2\log_2 C_2 of the Bernoulli family for sequences of length n=2n = 2.
NumericThe price of ten parameters
A model with k=10k = 10 parameters is fitted to n=106n = 10^6 data. How many bits does the term k2log⁡2n\tfrac{k}{2}\log_2 n add to two-part length?
NumericEncoding with Laplace's rule
Encode binary sequence 11011101 one datum at a time with Laplace's rule, q(1∣xt−1)=(kt−1+1)/(t+1)q(1 \given x^{t-1}) = (k_{t-1} + 1)/(t + 1), where kt−1k_{t-1} is the number of ones in the first t−1t - 1 observations. How many bits in total (without rounding)?
NumericPrecision of a parameter
Estimate a coin's probability θ\theta with n=104n = 10^4 tosses and obtain θ^≈0.5\hat\theta \approx 0.5. According to the optimal precision theorem, which grid step δ∗\delta^* should be used to transmit θ\theta in a two-part code?
QuizData order
You calculate a dataset's prequential length with two methods in two different data orders. Which statement is correct?
QuizThe cost of not knowing the parameter
By the redundancy–capacity theorem, the worst expected excess of a universal code for family {pθn}\{p_\theta^n\} is capacity of channel θ↦Xn\theta \mapsto X^n. Which statement is a correct consequence?
ProofThe invariance theorem
Prove: If UU and VV are universal prefix Turing machines, there is a constant cc such that ∣KU(x)−KV(x)∣≤c\abs{K_U(x) - K_V(x)} \le c for every string xx.
0
Fix xx and let pp be a shortest program for VV, so V(p)=xV(p) = x with ℓ(p)=KV(x)\ell(p) = K_V(x).

Step 1 of 4. Which property of UU lets you make a program for UU from pp?

ProofRegret of a finite mixture
Prove: Let M={p1,…,pM}\mathcal{M} = \{p_1, \dots, p_M\} be a finite family of distributions on Xn\mathcal{X}^n and q=1M∑j=1Mpjq = \frac1M\sum_{j=1}^M p_j its uniform mixture. For every sequence xnx^n, REG(q,xn)≤log⁡M\mathrm{REG}(q, x^n) \le \log M.
0
Fix xnx^n and let ȷ^\hat\jmath index the model best explaining xnx^n: pȷ^(xn)=max⁡jpj(xn)p_{\hat\jmath}(x^n) = \max_j p_j(x^n).

Step 1 of 3. What lower bound do you have for q(xn)q(x^n)?

CodeBayesian prequential coding and marginal likelihood
Implement 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 w∼N(0,α−1I)\vb{w} \sim \Normal(\vb{0}, \alpha^{-1}\mat{I}) and Gaussian noise of known variance σ2\sigma^2. Traverse observations in order: encode yty_t using the posterior predictive given the preceding t−1t - 1, N(xt⊤mt−1, σ2+xt⊤St−1xt)\Normal(\vb{x}_t\T\vb{m}_{t-1},\ \sigma^2 + \vb{x}_t\T\mat{S}_{t-1}\vb{x}_t), add −ln⁡-\ln of its density and update posterior (mt,St)(\vb{m}_t, \mat{S}_t). Tests check agreement with −ln⁡-\ln of marginal likelihood N(y; 0, σ2I+α−1XX⊤)\Normal(\vb{y};\ \vb{0},\ \sigma^2\mat{I} + \alpha^{-1}\mat{X}\mat{X}\T) 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 total
Shift+Enter to run

Summary

Key idea
Learning is compression: the best model describes data in the fewest bits counting model description cost, and this accounting, using universal codes or one datum at a time, penalizes each parameter by about 12log⁡n\tfrac12\log n bits and measures complexity by what the model can learn from available data.
  • Kolmogorov complexity K(x)K(x), the length of the shortest program printing xx, is invariant up to a constant and uncomputable. Almost all strings are incompressible, and average KK is entropy. Real compressors give upper bounds.
  • Two-part MDL picks the model minimizing L(M)+L(D∣M)L(M) + L(D \given M). Each parameter is written to its typical error precision, δ∗=12/(nI)\delta^* = \sqrt{12/(nI)}, costing 12log⁡n\tfrac12\log n 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 log⁡Cn=k2log⁡n2π+log⁡∫det⁡I+o(1)\log C_n = \tfrac{k}{2}\log\frac{n}{2\pi} + \log\int\sqrt{\det I} + o(1); 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 →\to 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.