Knowledge Base · Learning paths
What is Perplexity in Language Models? A Complete Guide
Perplexity is an improved version of N-gram Entropy. Starting from basic entropy and incorporating contextual priors, it evolved into the widely used Perplexity metric that measures how uncertain a language model is when predicting the next token. This article systematically explains its mathematical foundations and evolutionary history.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
Author: Xiao A, aaronxic, Zhihu Profile
Publication Date: July 8, 2023
Original Article: https://zhuanlan.zhihu.com/p/633757727
Introduction
Hello everyone, I’m aaronxic. You can call me Xiao A (Little A). Recently, due to project requirements, I started paying attention to the latest developments in transformer-related research. The sheer volume of overwhelming work in this field has caused my brain’s computation and storage to seriously overflow. The rapid pace of progress around transformers is astonishing — no wonder even Lu Qi has said he can barely keep up with the breakneck speed of the large language model era.
There is no shortage of excellent articles online that introduce various aspects of transformers. Many offer highly insightful perspectives and extremely detailed analyses. However, from a beginner’s point of view, there is still a strong desire for beginner-friendly transformer onboarding materials that meet the following needs:
-
Comprehensive coverage. The ability to connect transformer-related algorithms, training methods, and deployment techniques in one coherent narrative, helping newcomers quickly build a solid know-how in the field.
-
Balanced depth and breadth. A combination of bottom-up and top-down approaches — providing detailed, bottom-up clarification of logical chains for details that most articles tend to overlook, while also offering top-down organization of the many seemingly independent but deeply interconnected pieces of knowledge.
Drawing from my own real-world experience of “falling into the pit,” I’ve tried to summarize and organize a beginner-friendly transformer onboarding guide. On one hand, this forces me to clarify my own knowledge structure; on the other, I hope it can help future newcomers avoid detours and acquire the knowledge they need more quickly.
This series plans to introduce transformers from the following five perspectives:
- Algorithm 1: Transformer network architecture in NLP
- Algorithm 2: Transformer network architecture in CV
- Algorithm 3: Transformer network architecture in multimodal settings
- Training: Distributed training of transformers
- Deployment: TVM quantization and inference for transformers
Since I (Xiao A) have not personally implemented every detail mentioned above, most of the content is synthesized through studying code and carefully reading excellent articles. In essence, I am a knowledge porter who stands on the shoulders of giants. Therefore, this remains “talking on paper.” I sincerely welcome experts with hands-on experience to critique and correct me. Only through the collision of ideas can sparks fly, and truth becomes clearer through debate.
Each topic may consist of multiple articles. If you are interested in any part of this series, feel free to follow me (Xiao A). I will gradually update the corresponding chapters.
Next comes the first article of this series, which focuses on explaining what the most commonly used perplexity metric in NLP actually means.
This article will start from the familiar entropy metric, gradually introduce the improved N-gram Entropy tailored for natural language, and finally present the perplexity metric built upon these improvements.
Entropy (No Prior)
In natural language ( L ), a sentence can be viewed as an ordered string composed of multiple characters. Assume that the probability of each character ( x \in \mathcal{X} ) appearing is ( p(x) ), where ( p(x) ) is defined over the character set consisting of 26 lowercase English letters, i.e., ( \mathcal{X} = {a, b, \dots, z} ).
Following the familiar definition of entropy, we can calculate the entropy of natural language ( L ):
$$ H(x) = -\sum_{x \in \mathcal{X}} p(x) \log_2 p(x) $$
It is sometimes abbreviated as ( \mathbf{E}_{p(x)}[-\log_2 p(x)] ), which means the expected value of ( -\log_2 p(x) ) under the distribution ( p(x) ).
If we have no observation samples or prior knowledge, the 26 letters are assumed to be uniformly distributed. In that case, the entropy of natural language ( L ) is:
$$ H_1(x) = \log_2 26 = 4.70 \text{ bit} $$
This means that encoding each character in ( \mathcal{X} ) requires 4.7 bits.
N-gram Entropy (with Priors)
However, it is clear that in real natural language, a large number of priors can be leveraged.
- Prior 1: The probabilities of different letters appearing vary significantly. For example, the letter “e” appears with a probability of 12.70%, while “z” appears with only 0.07%. Therefore, “e” can be encoded with fewer bits, while “z” requires more bits. The table below shows the typical frequencies of lowercase English letters. When these frequencies are used as p(x), we obtain H₂(x) = 4.14 bit, which is smaller than H₁(x).
- Prior 2: Given the preceding context, the probability distribution of the next character changes dramatically. For instance, although the single character “e” appears more frequently than “h” overall, the probability of “h” following “t” is higher than that of “e”.
From the above, we can see that the entropy H(x) of a natural language L is a value closely tied to the probability distribution p(x). The original entropy definition cannot account for Prior 2. To address this, Shannon proposed N-gram Entropy specifically for natural language in his 1951 paper “Prediction and Entropy of Printed English”.
Given a sufficiently long character sequence S from natural language L, we examine all substrings of length N, denoted b_N = (w_1, w_2, ..., w_N), and define the N-gram Entropy F_N as follows:
$$ F_N = -\sum_{b_N}p(b_N)\log_2p(w_N|b_{N-1}) = -\sum_{b_N}p(b_N)\log_2p(b_N) - \left(-\sum_{b_{N-1}}p(b_{N-1})\log_2p(b_{N-1})\right) $$
Personal interpretation:
-
The key insight behind Shannon’s F_N is to incorporate context. By examining the entropy of N consecutive characters and replacing the standard expectation $\mathbf{E}{p(b_N)}[-\log_2 p(b_N)]$ with the conditional form $\mathbf{E}{p(b_N)}[-\log_2 p(w_N|b_{N-1})]$, Prior 2 is naturally incorporated into the metric.
-
Summation over b_N is valid because we can slide a window across the character sequence S to obtain a large number of b_N samples.
If we define $K_N = -\sum_{b_N}p(b_N)\log_2p(b_N)$, then:
$$ F_N = K_N - K_{N-1} $$
It is easy to see that $K_N$ is exactly the entropy of N consecutive characters, i.e., $H(b_N)$ or $\mathbf{E}_{p(b_N)}[-\log_2 p(b_N)]$ from earlier.
As N increases, F_N converges to the true entropy H of the natural language L:
$$ H = \lim_{n\rightarrow\infty}F_n $$
Moreover, F_N exhibits a monotonically decreasing property (for a full proof, see the blog post):
$$ F_0 \gt F_1 \gt \dots \gt F_N \gt F_{\infty} = H $$
When N is small, these values can be obtained through simple statistics on a corpus:
-
F₀ = 4.7 bit, which corresponds to the H₁(x) mentioned earlier. Note that N=0 is meaningless in the original F_N formula; F₀ is a special definition introduced by Shannon.
-
F₁ = 4.14 bit, which is H₂(x) from before. This corresponds to treating characters independently.
-
F₂ = 3.56 bit. This takes pairwise character co-occurrences into account.
When N becomes large, spaces between words appear. In such cases, a space character is typically added, resulting in 27 symbols in total. Because exact values are difficult to estimate, ranges are usually provided. For example:
- Estimate 1: Shannon gave 0.6–1.3 bits.
- Estimate 2: Cover and King estimated 1.25 bits.
- Estimate 3: The commonly accepted classical value is around 1.25 bits (please correct me if this is inaccurate).
It is worth noting that the above figures are all character-level N-gram entropy. There are also word-level and subword-level versions. When comparing numbers, one must be careful about the granularity. For instance, GPT-4 reports a word-level metric called BPW (bits per word). We will leave this aside for now; just keep it in mind — it will be revisited later.
BPW metrics for models of different scales
A common question is whether character-level and word-level metrics can be directly converted. According to the author (Xiao A), there is no trivial conversion formula. We can only say that the two tend to move in roughly the same direction.
Additionally, the trend reveals an interesting insight: datasets whose curves decline faster as N increases are easier to fit. For example, WikiText-2 is relatively easy, whereas SimpleBooks-92 is considerably harder.
Cross-Entropy and Perplexity
Both the prior-free Entropy and the N-gram Entropy with priors describe the intrinsic entropy of the natural language L itself. Their purpose is to measure the information content and complexity of that natural language L. So for a given Language Model (LM), such as an N-gram model or a Transformer model:
-
Question 1: How do we measure the entropy of this LM?
-
Question 2: Does the entropy of this LM have a direct relationship with the model’s final performance?
Before answering these two questions, we must first understand how an LM is typically modeled mathematically. The most common formulation is as follows:
$$ P_{(w_1, w_2, ..., w_n)} = q(w_1)q(w_2|w_1)q(w_3|w_1,w_2)...q(w_n|w_1, w_2, ..., w_{n-1}) = \prod_{i=1}^n q(w_i|w_1, ..., w_{i-1}) $$
Essentially, it predicts the next word given the previous words. The core component here is the conditional probability $q(w_i|w_1, ..., w_{i-1})$, which can be modeled using either an N-gram language model (e.g., KenLM) or a Transformer model (e.g., GPT-4).
Given the above model, a straightforward idea is to take the definition of N-gram Entropy and replace $\mathbf{E}{p(b_N)}[-\log_2p(w_N|b{N-1})]$ with $\mathbf{E}{p(b_N)}[-\log_2q(w_N|b{N-1})]$, where $q(w_N|b_{N-1})$ is exactly the core output of the LM.
At this point, we have inadvertently written out the definition of cross-entropy. Expanding it gives:
$$ \mathbf{H}(\text{LM}) = \mathbf{H}(P, Q) = \mathbf{E}{p(b_N)}[-\log_2q(w_N|b{N-1})] = -\sum_{b_N}p(b_N)\log_2q(w_N|b_{N-1}) = -\sum_{b_N}p(w_N|b_{N-1}) p(b_{N-1}) \log_2q(w_N|b_{N-1}) \approx -\sum_{b_N}1 \cdot \frac{1}{m} \log_2q(w_N|b_{N-1}) = -\frac{1}{m}\sum_{b_N}\log_2q(w_N|b_{N-1}) = -\frac{1}{m}\sum_{i=1}^m\log_2q(w_i|w_1, w_2, ..., w_{i-1}) $$
Note the key approximation step ($\approx$):
-
For $p(w_N|b_{N-1})$, we simplify by assuming that the oracle — natural language L — when seeing $b_{N-1}$, will output $w_N$ with confidence 1. Thus, $p(w_N|b_{N-1}) = 1$.
-
For $p(b_{N-1})$, we also simplify by assuming that after sliding the window, a total of $m$ different $b_N$ are generated (i.e., $|b_N| = m$). Then the probability of each specific $b_{N-1}$ is $1/m$.
And in the final step:
-
Since there are $m$ sliding windows producing $m$ different $b_N$, the number of integral terms becomes $m$.
-
First, $q(w_N|b_{N-1})$ expands to $q(w_N|w_1, w_2, ..., w_{N-1})$. Note that whether using an N-gram or a GPT-4 model, there is a context window size limit. When the preceding content $(w_1, w_2, ..., w_{i-1})$ is shorter than $N$ or exceeds $N$, it is padded or truncated to size $N$. Therefore, each term $q(w_i|w_1, w_2, ..., w_{i-1})$ in the last line can be turned into $q(w_N|w_1, w_2, ..., w_{N-1})$ through padding or truncation (this part can be a bit tricky — feel free to reread it several times).
If we further move $-\frac{1}{m}$ and $\sum_{i=1}^{m}$ inside the base-2 logarithm, we obtain:
$$ \mathbf{H}(\text{LM}) = \mathbf{H}(P, Q) \approx -\frac{1}{m}\sum_{i=1}^m\log_2q(w_i|w_1, w_2, ..., w_{i-1}) = \log_2 \left( \prod_{i=1}^m \frac{1}{q(w_i|w_1, w_2, ..., w_{i-1})} \right)^{\frac{1}{m}} = \log_2 (\text{Perplexity(LM)}) $$
Therefore, we have (strictly speaking, approximately):
$$ 2^{\mathbf{H}(\text{LM})} = 2^{\mathbf{H}(P, Q)} = \text{Perplexity(LM)} $$
This is actually quite easy to remember:
-
If an LM has an entropy of 4.7 bits, it is equivalent to rolling a 24.7 ≈ 25.99-sided die every time it generates the next token. This 25.99 is the Perplexity.
-
Conversely, if an LM has a Perplexity of 31.1, it is equivalent to rolling a 31.1-sided die each time it generates the next token. The entropy of this LM is $\log_2 31.1 \approx 4.95$ bits.
The fewer sides the die has, the more confidently the LM predicts a particular token. It has performed some compression on natural language and learned non-trivial patterns.
Note that the base can be changed from 2 to $e$, as long as it remains consistent with the definition of entropy.
Additionally, regarding the earlier concepts of Bits per Word (BPW) or Bits per Character (BPC), I understand they are essentially the same as $\mathbf{H}(P, Q)$, except BPW is computed at the word level and BPC at the character level. (Many articles mention additional averaging over sequence length — see Reference 1 and Reference 2. I’m not entirely clear on this part, so I’d appreciate insights from anyone who understands it better.)
Is Lower Perplexity Always Better?
In the previous section, we answered how to calculate the entropy of a language model (LM) in Question 1. So, does pursuing a lower Perplexity necessarily bring benefits?
- The XLNet paper states that excessively low perplexity may harm the accuracy of downstream tasks.
- The RoBERTa paper points out that for encoder-only models like RoBERTa, lower perplexity generally leads to better performance on NLU tasks.
It is therefore clear that perplexity is a good guiding metric, but the ultimate evaluation criterion must still be combined with performance on downstream tasks.
Conclusion
In summary, Perplexity, Cross-Entropy, and Bits Per Character are essentially similar concepts. They all revolve around entropy to characterize the information content and complexity of a language model.
Finally, I strongly recommend reading Evaluation Metrics for Language Modeling. It pairs perfectly with this article. Also, since the author (Xiao A) is relatively new to Transformer-related topics, errors are inevitable. I welcome corrections and feedback from experts.
If you’d like to learn more about Transformer algorithms in NLP, CV, and multimodal domains, knowledge of distributed training, or how to perform PTQ quantization and deployment on TVM, feel free to follow aaronxic~ Zhihu Profile