Language Trees via Compression
Cross-Entropy, Compression, and Language Models
Compression as a Tool for Discovering Language Structure
A striking result from the early 2000s showed that general-purpose file compression can reveal meaningful relationships between languages without using pre-built linguistic knowledge.
Suppose a collection of documents is written in several different languages. A system could be asked to:
Cluster documents according to their language.
Determine which languages are most closely related.
Reconstruct a tree representing shared linguistic ancestry.
Identify the likely author of an unknown document.
The surprising part is that these tasks can be approached using ordinary compression software such as gzip, rather than a specialized language model or linguistic database.
The co-compression idea
Given two documents, A and B:
Compress document A by itself.
Append a short portion of B to A.
Compress the combined document.
Compare the compressed sizes.
A compressor trained primarily on A becomes optimized for the repeated patterns, symbols, and structures found in A. If the appended text from B has similar patterns, it should compress relatively efficiently. If B is written in a very different language, its patterns will be less familiar to the compressor and the combined file will be larger.
Thus, the difference in compressed size acts as an approximate measure of how different the two documents are.
Core idea: A compression scheme optimized for one source performs better on another source when the two sources share statistical patterns.
By applying this comparison to many pairs of documents, it becomes possible to construct a distance measure between languages. The resulting distances can be used to produce a language-family tree.
Why this connects to machine learning
Compression and language modeling appear to be different areas:
Compression focuses on representing data with as few bits as possible.
Machine learning focuses on learning patterns and making predictions.
However, both depend on estimating probabilities. A good compressor assigns short descriptions to likely events and longer descriptions to unlikely events. A good language model assigns high probabilities to likely next tokens and low probabilities to unlikely ones.
The common mathematical concept linking these tasks is cross-entropy.
Information Content and Optimal Compression
Symbols as probabilistic events
A message can be treated as a sequence of symbols. Symbols might be:
Characters in a text.
Words or pieces of words.
Robot movement instructions.
Any other discrete events.
If each symbol is sampled from a probability distribution, the probabilities determine how efficiently the message can theoretically be compressed.
A toy robot example
Consider a robot that receives one of four instructions:
Up
Down
Left
Right
Suppose the instructions are sampled according to the following distribution:
Up: probability 21
Down: probability 41
Left: probability 81
Right: probability 81
A sensible encoding assigns shorter bit strings to more probable symbols:
Up: 1 bit
Down: 2 bits
Left: 3 bits
Right: 3 bits
The common pattern is:
where qi is the probability of symbol i.
For the robot instructions:
Information content
The quantity
is the information content of an event with probability qi.
It measures how surprising the event is:
Very probable events carry little information.
Rare events carry more information.
An event with probability 1 carries zero information.
An event with probability 21 carries one bit of information.
The negative logarithm is useful because it converts multiplication of probabilities into addition:
This means that the information content of a sequence can be obtained by adding the information content of its individual symbols.
Fractional information
Probabilities do not usually produce whole-number values of −log2(qi). For example, if an event has probability 31, its information content is:
which is approximately 1.585 bits.
Although an individual symbol cannot normally be assigned a fractional-length ordinary bit string, fractional information has a real meaning when averaged over many messages. Advanced compression methods can approach these average limits using techniques such as arithmetic coding.
Entropy: The Best Possible Average Compression
For a probability distribution Q with symbol probabilities qi, the information content of symbol i is:
The average information per symbol is the probability-weighted sum:
This quantity is the entropy of Q.
Entropy represents the minimum possible average number of bits per symbol for an ideal compression scheme when the true distribution is Q.
Visual interpretation of entropy
Entropy can be visualized as a collection of bars:
The width of bar i is qi.
The height of bar i is −log2(qi).
The area of bar i is qi[−log2(qi)].
The sum of all bar areas is the entropy.
Thus, entropy is the average information content of events generated by the distribution.
Entropy and uncertainty
Entropy is larger when probability is spread more evenly among possible outcomes.
For example:
A distribution in which one event is nearly certain has low entropy.
A distribution in which many events are similarly likely has higher entropy.
For a two-event distribution with equal probabilities, the entropy is:
The distribution has one bit of entropy per symbol.
Cross-Entropy
Using the wrong compression model
Suppose the true distribution of symbols is P, but the compression code was designed for a different distribution Q.
The code optimized for Q assigns symbol i approximately:
bits.
However, symbols actually occur according to P, so the average number of bits used is:
This is the cross-entropy of P relative to Q.
The terminology can vary in different sources, but the essential roles are:
P: the distribution that generates the data or represents reality.
Q: the distribution used by the model or compression code.
Cross-entropy measures how well a code optimized for Q performs when data is actually generated according to P.
The weights in the average come from P, because P determines how often each symbol appears. The bit lengths come from Q, because Q determines the code being used.
Visual interpretation of cross-entropy
Cross-entropy uses bars similar to the entropy diagram:
The width of bar i is pi.
The height of bar i is −log2(qi).
The total area is H(P,Q).
The difference from entropy is that the distribution determining how often a symbol occurs and the distribution determining its code length may be different.
Robot example with a changed distribution
Initially, the robot instructions had distribution Q:
Up: 21
Down: 41
Left: 81
Right: 81
The code optimized for this distribution uses:
Up: 1 bit
Down: 2 bits
Left: 3 bits
Right: 3 bits
Now suppose the actual distribution changes to P:
Up: 81
Down: 81
Left: 41
Right: 21
The old code is still used. The average number of bits becomes:
The value 2.625 bits per symbol is the cross-entropy: the average cost of using a code optimized for the old distribution when the new distribution is the one actually occurring.
Cross-Entropy Is Not Symmetric
Cross-entropy depends on the order of its arguments:
This is natural because the two distributions have different roles:
The first distribution determines the frequencies of events.
The second distribution determines the code lengths or predicted probabilities.
Two-outcome example
Consider two possible events.
Case 1: Q is uniform and P is skewed
Let:
Q=(0.5,0.5)
P=(0.9,0.1)
Because Q assigns probability 0.5 to each event, both events receive one bit of information:
Therefore:
Even though P is skewed, the code remains one bit per symbol because the code optimized for Q gives both outcomes the same code length.
The entropy of Q is also:
Case 2: Q is skewed and P is uniform
Now reverse the roles:
Q=(0.9,0.1)
P=(0.5,0.5)
The code optimized for Q assigns:
The common event a short code.
The rare event a much longer code.
The entropy of Q is less than one bit because Q is skewed. However, under the actual distribution P, both events occur equally often. The rare event under Q is encountered much more frequently than expected, making the average code length about:
Thus, swapping P and Q changes the result substantially.
The Minimum of Cross-Entropy
For a fixed actual distribution P, consider cross-entropy as a function of the proposed distribution Q:
The cross-entropy reaches its minimum when:
At that point:
Therefore:
The best possible code for data generated according to P is the code optimized for P, and its minimum average cost is the entropy of P.
If Q differs from P, the code is less efficient and cross-entropy becomes larger.
Geometric intuition
In a two-outcome distribution:
P can be described by one parameter, such as p1, because the other probability is 1−p1.
Q can similarly be described by q1.
If P is fixed and cross-entropy is plotted against Q, the curve has a minimum at:
If the value of P is moved, the locations of these minima trace out the entropy curve:
This demonstrates that entropy is the lowest cross-entropy achievable for a given true distribution.
Compression and Language Similarity
The language-tree experiment can be understood as an approximate application of cross-entropy.
Document compression as model transfer
A compressor trained on document A is optimized for the patterns present in A. When a snippet from document B is appended, the compressor must encode B using a model shaped by A.
The resulting additional compressed length asks:
How efficiently can patterns from B be encoded using a compression scheme optimized for A?
That is essentially the same question as cross-entropy.
Why the method works
If A and B are written in closely related languages:
They may share vocabulary patterns.
They may use similar character sequences.
They may share grammatical regularities.
They may have similar spelling and punctuation patterns.
They may contain recurring structures that a compressor can reuse.
The snippet from B will then tend to compress well after A.
If the languages are unrelated, fewer patterns transfer from A to B, so the appended text will require more bits.
Why gzip is only an approximation
The compression distance is not exactly cross-entropy because:
A text document is treated as a sample from an underlying language distribution rather than as an explicit probability distribution.
Gzip is not an ideal compressor and does not generally achieve the theoretical Shannon limit.
Gzip primarily detects repetitions and replaces later repetitions with references to earlier sequences.
The specific distance measure may include additional normalization or comparison details.
Nevertheless, the approximation can still be useful. Even an imperfect compressor may preserve enough information about statistical similarity to distinguish languages and authors.
Language Models as Predictive Distributions
A modern language model can be viewed as a function with a large collection of adjustable parameters.
Tokens
Language models do not necessarily process complete words. They divide text into tokens, which may be:
Whole words.
Pieces of words.
Individual characters.
Punctuation marks.
Other frequently occurring text fragments.
A text is represented as a sequence of tokens.
Model input and output
Given an input sequence of tokens, a language model produces a probability distribution over all possible next tokens.
For example, after receiving:
“The robot moved”
the model might assign probabilities to possible continuations such as:
“up”
“quickly”
“through”
“because”
The model’s output is not merely one guess. It is a complete probability distribution describing its uncertainty about what comes next.
Training objective
To train the model, a loss function measures the quality of its predictions. Training then adjusts the model’s parameters to reduce this loss.
The model is optimized using standard deep-learning machinery, especially:
Gradient descent, which changes parameters in directions that reduce the loss.
Backpropagation, which computes how each parameter contributed to the loss.
Optimization algorithms that make this process practical at large scale.
The loss landscape technically has one dimension for every model parameter, potentially billions of dimensions. Two-dimensional hill diagrams are only simplified visual analogies.
Pre-Training and Per-Token Information
The next-token training procedure
For a training sequence:
Provide the model with an initial sequence of tokens.
Ask the model for a probability distribution over the next token.
Identify the actual next token in the training data.
Record the probability assigned to that true token.
Convert that probability into a loss using its negative logarithm.
Repeat for every position in the sequence and across the entire training corpus.
Average the losses.
For a true next token with model-assigned probability q, the per-token loss is:
In machine learning, the natural logarithm is usually used:
Using ln instead of log2 changes the values only by a constant factor:
That constant factor can be absorbed into the learning rate during optimization.
Why the negative logarithm is appropriate
The negative logarithm has the desired behavior:
If the model assigns high probability to the true token, the loss is small.
If the model assigns low probability to the true token, the loss is large.
If the model assigns an extremely small probability, the penalty grows sharply.
If the model assigns probability 1, the loss is zero.
Thus, the loss strongly punishes confident but incorrect predictions.
A poorly trained or random model gives low probability to the actual next token and therefore receives a high average loss. A knowledgeable model assigns higher probabilities to tokens that actually occur and receives a lower loss.
Pre-training as average information
The total pre-training loss is the average negative log-probability of the true next token:
where:
N is the number of prediction events.
qj is the model’s probability for the true token at event j.
This can be interpreted as:
The average information, or surprise, of the observed text from the model’s perspective.
At a high level, pre-training attempts to make the model’s predictions approach the statistical structure of the language represented by the training data.
Why the loss is called cross-entropy
For an individual training example, the target distribution is often represented as a one-hot distribution:
Probability 1 for the actual next token.
Probability 0 for every other token.
If the model’s predicted distribution is Q, and the target distribution is P, then cross-entropy is:
Because every pi is zero except for the true token, the expression reduces to:
This explains the standard implementation of next-token loss, but it does not fully explain why logarithms and cross-entropy are the right choices. A deeper explanation comes from requiring the loss to reward matching the true data distribution.
Why the Logarithm Is Mathematically Natural
Suppose the per-example loss is represented by a general decreasing function F of the model’s assigned probability:
The loss should decrease as q increases because assigning higher probability to the correct outcome should be rewarded.
Consider a repeated pattern such as:
“My name is ___”
Suppose different names occur in the training data with proportions pi. The model assigns probabilities qi to those names.
The average loss over all examples of this pattern is:
The desired property is that this average loss should be minimized exactly when the model distribution matches the data distribution:
subject to the requirement that the model’s probabilities sum to one:
A constrained optimization argument using a Lagrange multiplier shows that the derivative of F must have the form:
for some constant C.
The only functions whose derivatives have this reciprocal form are logarithmic functions:
Because the loss must decrease as q increases, the relevant choice is the negative logarithm:
Therefore, the logarithmic loss is not merely one convenient decreasing function among many. It is forced by the requirement that the average loss be minimized when the model’s output distribution matches the empirical distribution in the data.
When the negative logarithm is averaged over all possible outcomes, the result is exactly cross-entropy:
Distillation: Learning from a Larger Model
Motivation
Pre-training a small model directly from raw text provides only one explicit target at each position: the token that actually occurred.
A larger model, however, can provide a complete probability distribution over possible next tokens. A smaller model can be trained to imitate this richer distribution.
This process is called knowledge distillation or simply distillation.
The goals are usually to:
Preserve much of a large model’s performance.
Reduce the number of parameters.
Lower memory and computation requirements.
Make inference faster and cheaper.
Distillation procedure
At each prediction position:
The small model produces a probability distribution Q.
The large model produces a probability distribution P.
The loss is the cross-entropy between these distributions:
The small model’s parameters are adjusted to make Q resemble P.
The large model is often called the teacher, while the smaller model is the student.
Why distillation contains more information than ordinary pre-training
Ordinary pre-training treats the observed next token as the only target with positive weight. It does not directly communicate how plausible the other possible tokens were.
For example, if the correct next token is “Alice,” ordinary training says:
“Alice” is the observed answer.
Every other token is treated as incorrect for this particular example.
The teacher model might instead assign a distribution such as:
“Alice”: high probability
“Bob”: moderate probability
“Charlie”: low but nonzero probability
Other names: very small probabilities
This distribution provides information about the teacher’s uncertainty and the relationships among possible answers.
Analogy
Learning from ordinary pre-training is like watching a chess game and seeing only which move was played.
Distillation is like having a stronger player explain:
Which moves were considered.
Which moves were good.
Which moves were nearly as good.
How strongly each move was preferred.
For a pattern such as “My name is ___,” a student model might need many examples before it learns a useful distribution over names through ordinary pre-training. Distillation can provide a similar distributional signal from a single example by comparing the student’s output with the teacher’s full prediction.
Cross-Entropy as a General Comparison Tool
Cross-entropy is useful whenever one wants to compare statistical patterns in one setting with a model or code optimized for another.
Examples include:
Comparing the patterns of two languages.
Measuring how well a model predicts a language.
Evaluating a compression code on new data.
Training a student model to imitate a teacher model.
Measuring the difference between an empirical distribution and a predicted distribution.
Its central interpretation remains the same:
Cross-entropy is the average cost of using distribution Q to represent data generated according to distribution P.
This explains why it appears both in compression theory and in machine learning.
From Predictors to Compressors
A language model predicts a probability distribution for each next token. In principle, those predictions can be used to compress text.
If the model assigns probability qi to a token, that token has model-based information content:
A compression algorithm can use these probabilities to allocate approximately that many bits to the token. Across an entire text, the total number of bits approaches the sum of the information contents:
where qt is the model’s probability for the observed token at position t.
Therefore, a model with a lower average cross-entropy assigns shorter descriptions to the observed text. Training the model to minimize cross-entropy can be interpreted as training it to compress text more efficiently.
This gives a powerful reinterpretation of language-model training:
The usual description is next-token prediction.
The compression description is learning an efficient representation of text.
Both descriptions use the same negative log-probability objective.
An ideal model would approach the entropy of the language, representing text close to its theoretical minimum description length.
Kullback–Leibler Divergence
Definition
Cross-entropy is always at least as large as entropy:
The difference between them is called Kullback–Leibler divergence, or KL divergence:
Expanding the definitions gives:
Thus, the compact expression and the entropy-difference expression are equivalent.
Compression interpretation
In compression, KL divergence measures the excess cost of using a code optimized for Q when the true distribution is P.
H(P): the ideal average number of bits per symbol when the code is optimized for P.
H(P,Q): the average number of bits when the code is optimized for Q.
DKL(P∥Q): the number of extra bits wasted by using the mismatched code.
For the robot example:
Properties of KL divergence
KL divergence has several important properties:
It is always nonnegative:
It equals zero when the distributions are identical:
It grows as the distributions become more different.
It is asymmetric:
Therefore, KL divergence is often described as a divergence or discrepancy rather than a true mathematical distance. A true distance generally needs symmetry, while KL divergence does not have that property.
KL divergence in machine learning
In machine learning, KL divergence can compare:
A data distribution and a model distribution.
A teacher model and a student model.
An original model and an approximating model.
A prior distribution and a learned posterior distribution.
For distillation, minimizing the teacher-to-student KL divergence is closely related to minimizing cross-entropy because the teacher’s entropy does not depend on the student’s parameters:
When P is fixed, minimizing DKL(P∥Q) and minimizing H(P,Q) produce the same optimal student distribution. The two losses differ only by the constant H(P) from the student’s point of view.
Central Relationships
The main concepts can be organized as follows:
Information content: The surprise of one event, −log2(p).
Entropy: The average information content under one distribution, H(P).
Cross-entropy: The average cost of using Q to encode data generated by P, H(P,Q).
KL divergence: The excess cost caused by using Q instead of the optimal distribution P, DKL(P∥Q).
Language-model loss: The average negative log-probability assigned to observed next tokens.
Compression: A way to turn probabilities into approximate bit lengths.
Distillation: Training one model to match the full predictive distribution of another.
The shared mathematical principle is that probability distributions encode both predictions and compression costs. A model that assigns high probability to what actually occurs is simultaneously a better predictor and a more efficient compressor.

Ask anything
We've read this whole study set, so questions about it get the best answers.