Module 6. Source coding: from entropy to real bits
How to read this module. The main route is §§6.1–6.8: from probabilistic models and the Kraft inequality to arithmetic coding, the AEP, entropy rate, and language-model metrics. §6.9 is a mathematical deepening on universal sequential prediction. §§6.10–6.11 return to LLM evaluation and to a reproducible compression experiment.
6.1. Engineering setup: the probabilistic model and the entropy coder
In earlier modules, appeared mainly as a loss: the less probability a model assigned to an observation, the larger the penalty. We will now read the same quantity as a description length.
Suppose two models evaluate the same data fragment and return the following probabilities for that fragment:
These are probabilities of the entire fragment, not of a single token. For an autoregressive model, each is a product of token-level conditional probabilities, so probabilities of long sequences are naturally extremely small.
Convert the probabilities into lengths:
Model therefore has a negative log-likelihood smaller by
Equivalently, model assigns the fragment an ideal information length that is 84 bits shorter. Producing a real reversible file still requires an entropy coder; its finite-precision and protocol overhead will be separated below.
The model and the coder have different roles.
A probabilistic model supplies next-symbol probabilities. An entropy coder uses those probabilities to construct a reversible bitstream.
Let a source generate from , while an autoregressive model defines
The ideal information length of a particular sequence under the model is
This is the familiar token-level negative log-likelihood, measured in bits. If a library reports NLL with natural logarithms, divide by .
For example, if the model assigns three successive observations the conditional probabilities
then the ideal bill is
The logarithm is doing the same job as in Module 1: it turns a product of conditional probabilities into an additive coding cost.
Ideal length, bitstream length, and total description length
A compression experiment has three relevant lengths.
- Ideal data length This is what bit-valued NLL measures.
- Emitted bitstream length Finite probability precision, termination, headers, and alignment live here.
- Total self-contained description length This is the relevant bill when the decoder does not already possess the model and protocol.
A validation loss measures the first ledger. A practical range coder approximates the second. A standalone archive must pay the third.
One more boundary will matter throughout the module. Entropy lower-bounds an expected length under a specified source. It does not forbid an individual regular string from being much shorter than the average. A million zeros may be exceptionally cheap; the theorem says that no lossless method can systematically push the mean length below the source entropy.
6.2. Prefix codes and the Kraft--McMillan inequality
Begin with the simplest code: assign a binary string to every symbol in a finite alphabet
A code is prefix-free if no codeword is the beginning of another. Thus
is prefix-free, whereas
is not: after reading a zero, the decoder cannot know whether a symbol ended or the word 01 began.
Prefix-freeness gives instantaneous decoding without separators. The convenience comes with a strict budget.
Kraft's theorem. Positive integers are the lengths of some binary prefix code if and only if

Why the Kraft inequality arises
Read the full binary tree as one unit of resource. A codeword of length occupies a fraction
of all sufficiently long binary continuations. Short words are expensive: length 1 immediately consumes half the tree; length 2 consumes one quarter; length 3 consumes one eighth.
For
the entire budget is used:
Making a frequent symbol shorter requires reserving a large branch and pushing other symbols deeper into the tree.
This is why an arbitrary collection of short codewords cannot exist. Kraft's inequality is not bookkeeping trivia; it is the geometry of a scarce resource.
The converse is constructive: whenever the lengths fit within the budget, leaves can be placed in the tree without overlap. The same necessary inequality holds for the larger class of uniquely decodable codes, as part of the Kraft--McMillan theorem. Prefix codes will be enough for us: they achieve the same average-length bound and are simpler to decode.
6.3. The one-symbol source-coding theorem
Let , with
and let symbol receive a codeword of length . The expected length is
How small can be?
Lower bound on average code length
Every binary prefix code satisfies
The short proof belongs in the main route because it exposes exactly where coding inefficiency comes from.
Set
Then is the distribution implicitly defined by the code lengths, and
Now read the identity in words:
The proof is a coding ledger. The gap has two causes: the lengths behave as though the source were rather than , and the code may leave some Kraft budget idle.
Equality requires both
hence
Exact one-symbol equality is possible for dyadic distributions, for which every is an integer.
Upper bound: the Shannon code
The ideal real-valued lengths
use the Kraft budget exactly because . But a binary codeword cannot be 2.37 bits long. Round up:
Then
so Kraft holds, while
Therefore some prefix code satisfies
The is not a fundamental loss on every symbol. It is the price of integer lengths in a one-symbol code. In §6.5 we postpone the rounding to the end of a long block and divide the constant across many symbols.
A code built for the wrong model
Suppose data come from , but lengths are built from a model :
with on the support of . Then
Since
we obtain
This makes the operational meaning of KL literal:
under ideal fractional coding, is the expected number of extra bits paid for using the wrong probabilistic model.
A one-symbol prefix code adds less than one further bit of integer rounding.
6.4. Huffman coding, arithmetic coding, and range coding
Two classical algorithms solve the same problem but round at different places.
Huffman coding rounds every symbol length. Arithmetic coding postpones rounding until the message is complete.
Huffman coding
Huffman's algorithm constructs an optimal binary prefix code for a known finite distribution.
- Take the two least probable nodes.
- Merge them into a node whose probability is their sum.
- Repeat until one root remains.
For
one optimal code has lengths
and therefore

The gap is small. Integer granularity is much more visible for a highly skewed binary source:
Every nonempty binary one-symbol prefix code spends one bit per symbol, even though
This is neither a failure of Huffman coding nor a violation of Shannon's theorem. Huffman is optimal in its class; the class of one-symbol integer lengths is simply too coarse.
Arithmetic coding
Arithmetic coding does not give every symbol a separate word. It represents the entire sequence by a subinterval of .
Let
and partition as
For ACB, the interval evolves as
Its final width is

This is why token perplexities from different tokenizers are usually not directly comparable. Common denominators include
and
BPB is often easier to reproduce because bytes require only a fixed input file. BPC additionally depends on whether “character” means a byte, a Unicode code point, or a grapheme cluster.
Metric comparability and the role of tokenization
BPC and BPB do not remain unchanged when both tokenizer and model are replaced. A different tokenizer changes sequence length, vocabulary, computation, and usually the distribution itself.
The narrower statement is exact: if the probability of the same byte sequence is already fixed and we only regroup its factors, total bits and BPB remain unchanged, while PPL per new unit changes.
BPC/BPB therefore make comparisons more meaningful, but they do not remove the need for a protocol. The corpus, encoding, Unicode normalization, document boundaries, available context, and long-sequence evaluation method must still be fixed.
6.7. A language model as part of a compressor
Now assemble the full construction.
Encoder and decoder share
- model parameters;
- a tokenizer or another reversible input representation;
- the procedure for computing and quantizing probabilities;
- an entropy coder;
- start, stop, and context-reset rules.
The encoder observes the next symbol, obtains , and narrows the interval. Having reconstructed the same prefix, the decoder computes the same distribution and determines which symbol the bitstream selected.
Under this protocol,
and averaging over gives
Hence lower held-out log loss on the same distribution means a shorter expected data code.
There is an important engineering detail. If tokenization normalizes text irreversibly, the compressor recovers the normalized text rather than the original bytes. A genuine lossless archive needs a reversible representation or must separately encode the information discarded by preprocessing.
The Delétang et al. experiment
In Language Modeling Is Compression (ICLR 2024), pretrained models were coupled to arithmetic coding and applied to byte streams from text, images, and audio.
In Table 1, each dataset contains 1 GB and Transformer-based models process independent 2048-byte chunks. Chinchilla 70B obtains the following raw compression rates—compressed data-code size divided by raw size, excluding model weights:
- on enwik9;
- on grayscale ImageNet patches;
- on LibriSpeech.

The result is genuinely striking: a model pretrained primarily on text assigns useful probabilities to non-text byte sequences as well.
The protocol also tells us exactly how far the claim reaches. It demonstrates byte-level predictive structure in particular 2048-byte chunks. It is not, by itself, evidence of semantic understanding of images or speech. And the raw ratio asks, “How short is the data code if both parties already possess the model for free?”
The paper's abstract reports somewhat better figures, and , for ImageNet and LibriSpeech. To avoid mixing evaluation regimes, this module and its diagram use the explicit 2048-byte Table 1 values.
6.8. Model size, scaling laws, and total description length
Validation loss asks a useful question:
How many bits do the data need if the model is already available to both sides?
A standalone archive asks a stricter one:
Who pays for the model itself?
A two-part description has length
A larger model will often shrink the second term while increasing the first. For a fixed amount of data, an intermediate model size may minimize the total.

Delétang et al. charge neural-network weights at 2 bytes per parameter. Chinchilla 70B therefore costs roughly 140 GB before any data are coded. On a 1 GB enwik9 corpus, the data code is about GB, but the two-part total is approximately
which produces the table's adjusted compression rate of about .
This does not make large models useless. When one shared model serves an enormous stream of data, its cost can be amortized. It does mean that “Is this a good predictor?” and “Is this a good standalone archive for this dataset size?” are different questions.
Scaling laws and description length
When test cross-entropy falls with scale, the data-code length under an already shared model falls as well. This is an exact and useful reading of a scaling curve.
A stronger conclusion needs additional assumptions. A smooth power law alone does not imply
or guarantee that a fitted asymptote is the “true entropy of language.”
The reasons are ordinary:
- the model family may not contain the source;
- optimization may not find the best model in the family;
- a finite context window restricts the available conditional law;
- preprocessing and tokenization define a different problem;
- a held-out corpus is not a universal distribution over language;
- the empirical curve covers a finite range of scales.
The exact identity remains powerful:
But identifying an empirical asymptote with requires a separate argument that the KL gap vanishes for the specified source and context regime.
6.9. Mathematical deepening: universal coding, sequential log loss, and ICL
Optional on a first pass. Here the “prediction = code” bridge is extended to an unknown source, where the predictor adapts along the sequence.
At time , a sequential predictor outputs
Its cumulative bit-valued log loss is
This is also an ideal sequential code length. Online prediction under log loss and sequential compression use the same ledger.
A finite mixture of models
Suppose we have models with prior weights
The Bayesian mixture is
For every ,
so
With a uniform prior, the mixture loses at most bits over the entire sequence relative to the best model in the finite class.
This is the clean idea behind universal prediction: uncertainty about which hypothesis will win is paid for by finite regret. The precise guarantee depends on the class. Lempel--Ziv, CTW, Bayesian mixtures, and other universal codes have different assumptions and redundancy rates; there is no assumption-free guarantee for every source.
The connection to in-context learning and its limits
A prompt containing demonstrations changes the model's subsequent conditional distributions without changing its weights. Operationally, this resembles an adaptive sequential code: context improves prediction, and any log-loss reduction shortens the code.
Theory provides more specific mechanisms under explicit assumptions. Xie et al. derive implicit Bayesian inference for a pretraining distribution given by a mixture of HMMs. Hahn and Goyal connect emergent ICL to structural and compositional properties of the training distribution.
These results do not turn an arbitrary LLM into an optimal universal Bayesian predictor for every prompt. A measurable question is more modest:
How quickly does sequential log loss fall as relevant context is added, and relative to which comparator class is regret measured?
6.10. Compression quality and model capabilities
The implication
is mathematical. Moving from it to “the better compressor is more intelligent” requires a definition of capability and an evaluation protocol.
The Hutter Prize uses lossless compression of the fixed 1 GB enwik9 file as a test of discovering structure in a large text corpus. Under the official rules, the scored size includes not only compressed data but also the program that reconstructs them. The benchmark is therefore closer to total description length than to NLL with a free model.
Huang et al., in Compression Represents Intelligence Linearly (COLM 2024), compare 31 public base LLMs on 12 knowledge, coding, and mathematical-reasoning benchmarks. In their protocol, average benchmark score correlates with average BPC on external corpora at a Pearson coefficient of about .
That is a strong empirical signal: good modeling of external data can be a useful unsupervised capability metric. But the same paper shows that the relationship weakens when the compression corpus is poorly aligned with the evaluated domain. A later study of code models (Xuyang et al., 2025) reports a logarithmic rather than universally linear relationship under its protocol.
A defensible conclusion is therefore:
Held-out compression efficiency is a meaningful unsupervised measure of probabilistic modeling quality and may proxy some capabilities; the shape of that relationship depends on domain, model set, and benchmark, and it is not a general definition of intelligence.
Low BPC does not by itself certify factual truth, alignment, causal reasoning, robust planning, or safe behavior. That does not weaken the compression metric; it identifies the precise question the metric answers.
6.11. A practical protocol for evaluating an LLM as a compressor
Before publishing a statement such as “the model reaches 1.1 BPB,” write down the full agreement between encoder and decoder.
- Input data. Exact file, version, license, and checksum.
- Preprocessing. Encoding, Unicode normalization, line endings, and removed regions.
- Unit. Bits/token, BPC, or BPB; for BPC, define “character.”
- Tokenizer. Version, special tokens, and reversibility to the original bytes.
- Boundaries. BOS, EOS, message length, and context resets.
- Context policy. Independent chunks, sliding window, or continuous stream; every target must be counted exactly once.
- Model. Exact revision, base or instruction-tuned variant, numerical precision, and evaluation mode.
- Coder probabilities. How logits become integer frequencies and whether encoder and decoder reproduce them identically.
- What was measured. NLL-equivalent length or an actually emitted bitstream.
- Model cost. Whether weights and tokenizer are shared in advance or included in the archive.
- Contamination. Whether the evaluation file may have appeared in pretraining.
- Comparability. Whether every method received the same byte stream and the same available context.
Sliding-window evaluation of a causal LM has a common off-by-one trap. Library losses typically compare
so the number of scored targets should be checked after this shift. Otherwise a boundary token can be skipped or counted twice.
A good report separates
- NLL-equivalent bits;
- actual compressed-stream size;
- format and coder overhead;
- model cost, when included.
Then “the LLM compresses the data” is a reproducible engineering result rather than a metaphor.
6.13. Conclusion
At the beginning of the module, was a familiar loss. It now has a physically testable meaning: it is the ideal bill, in bits, that a probabilistic model assigns to an observed sequence.
The central construction fits in one line:
Kraft's inequality explained why short codewords compete for a finite budget. Shannon's theorem decomposed coding redundancy into model mismatch and unused tree capacity. Huffman gave the best one-symbol prefix code, while arithmetic coding postponed rounding until the message ended. The AEP explained why long sequences acquire a stable per-symbol length, and entropy rate extended the picture to dependent sources.
For ML, the main consequence is particularly simple:
Lower held-out log loss means a shorter expected data code—under the same source, unit, and protocol.
Engineering honesty begins after that equality. PPL depends on the token; BPC and BPB require a common byte protocol; a real stream has coder overhead; a self-contained archive pays for the model; a strong compressor is a strong predictor but does not automatically receive a certificate of general intelligence.
The theory does not dissolve the beautiful link between prediction and compression. It strengthens it by identifying the exact equality, the exact price of mismatch, and the exact point where the rest of the system must be added to the data code.
Primary sources
- C. E. Shannon, A Mathematical Theory of Communication (1948).
- D. A. Huffman, A Method for the Construction of Minimum-Redundancy Codes (1952).
- T. Cover and J. Thomas, Elements of Information Theory, Chapter 5.
- G. Delétang et al., Language Modeling Is Compression, ICLR 2024.
- Y. Huang et al., Compression Represents Intelligence Linearly, COLM 2024.
- S. Xuyang, X. Luo et al., Is Compression Really Linear with Code Intelligence? (2025).
- S. M. Xie et al., An Explanation of In-Context Learning as Implicit Bayesian Inference, ICLR 2022.
- M. Hahn and N. Goyal, A Theory of Emergent In-Context Learning as Implicit Structure Induction (2023).
- M. Hutter, Human Knowledge Compression Contest—official enwik9 rules.