Language Models, Perplexity, and Bits per Byte chain-rule factorization · n-gram MLE · Zipf’s law · perplexity · Laplace vs. Kneser–Ney smoothing · bits per byte · sliding windows
Overcoming the 10^{30} sequence explosion: Over a 1,024-token vocabulary, 1024^{10} \approx 10^{30} length-10 sequences exist, yet the chain rule reduces joint density estimation to next-token classification at each step t.
One distribution, two operations: The conditionals P(x_t \mid x_{<t}) both score candidate passages (e.g., disambiguating acoustic homophones in ASR) and generate new text via left-to-right ancestral sampling.
Markov Truncation and n-Gram Maximum Likelihood
Count-Based Language Models
Because the full prefix x_{<t} grows without bound, an n-gram language model applies an (n - 1)^\textrm{th}-order Markov approximation and estimates each conditional probability by the empirical ratio of training corpus counts N(\cdot):
P(traveller | the time) = 47/87 = 0.54
P(machine | the time) = 27/87 = 0.31
P(i | the time) = 6/87 = 0.07
word pairs followed by a single word in training: 84%
Orders n = 1, 2, 3: Unigram (n = 1, zero context), bigram (n = 2, 1 preceding token), and trigram (n = 3, 2 preceding tokens).
Local phrase capture vs. rigid determinism: After "the time"(N = 87), the word trigram assigns 0.54 to "traveller" and 0.31 to "machine", yet 84\% of all observed word pairs in training are followed by only a single unique continuation.
Building and Sampling Count-Based n-Gram Models
From-Scratch Implementation
NGramLM maps every observed (n - 1)-token context to a Counter of its successors:
class NGramLM:"""An n-gram language model estimated from counts."""def__init__(self, tokens, n, vocab_size, alpha=0.01):self.n, self.vocab_size, self.alpha = n, vocab_size, alpha cont = collections.defaultdict(collections.Counter)for gram inzip(*(tokens[i:] for i inrange(n))): cont[gram[:-1]][gram[-1]] +=1self.cont =dict(cont)self.total = {ctx: sum(c.values()) for ctx, c inself.cont.items()}def sample(self, prefix, num_tokens, rng):"""Extend prefix by sampling from the unsmoothed count model.""" out =list(prefix)for _ inrange(num_tokens): ctx =tuple(out[len(out) -self.n +1:]) counts =self.cont[ctx] out.append(rng.choices(list(counts), counts.values())[0])return outvocab_size =len(known) +1# The training words and <unk>models = {n: NGramLM(words_train, n, vocab_size) for n in (1, 2, 3)}
The Memorization Illusion in Higher-Order n-Grams
Qualitative Sampling vs. True Generalization
To test whether fluent-looking samples reflect generalization or verbatim copying, longest_copy measures the longest contiguous span of generated words copied directly from the training text:
1-gram (longest copied run: 2 words): the time me and a had i laboratory
apologize i all seemed potentialities so reached such i assured reached
little is following of head one however the
2-gram (longest copied run: 3 words): the time and when we began to trouble
myself but the under world of our friend of flowers brilliant arch of
the sun belt sandals or other
3-gram (longest copied run: 13 words): the time traveller not a mere block
but highly decorated with deep framed panels on either hand to pick
flowers to stick a fork into meat again
Why Sample Inspection Can Mislead: The unigram emits disconnected word salad; the bigram chains locally valid pairs; and the trigram sounds remarkably like H. G. Wells—because it copies 7 to 12 consecutive words verbatim whenever the sampler lands on one of the 84\% of word pairs that had only a single training continuation.
The Sparsity Wall: Exponential Context Growth
Statistical Bottleneck of Count Tables
Why do higher-order n-grams collapse into memorization on training text and fail on held-out text? The number of possiblen-grams grows exponentially as |\mathcal{V}|^n, while corpus size grows only linearly:
unseen held-out 1-grams: 8.4% (4315 distinct in training)
unseen held-out 2-grams: 51.5% (18535 distinct in training)
unseen held-out 3-grams: 87.0% (26982 distinct in training)
Catastrophic zero counts on held-out text: On the final 10\% of The Time Machine, 8.4\% of unigrams (mapped to <unk>), 51.5\% of word bigrams, and 87.0\% of word trigrams never occurred in the training split.
Storage complexity: Instead of allocating a dense |\mathcal{V}|^n array (4316^3 \approx 8 \times 10^{10} cells), a nested hash map self.cont[ctx][token] stores only the n-grams that actually occur with nonzero count in training.
Zero-probability collapse: Under maximum likelihood estimation (\hat{P} = N(\text{trigram}) / N(\text{bigram})), any unseen n-gram receives probability 0, causing a single novel word triple to assign \prod_{t=1}^T \hat{P}(x_t \mid x_{<t}) = 0 to the entire validation passage.
Zipf’s Power Law in Natural Language Frequencies
Natural Language Statistics
Count tables go sparse so rapidly because word frequencies in natural language are extremely skewed, following Zipf’s power law across ranks i = 1, 2, \ldots, |\mathcal{V}|:
Stop-word dominance: The top 10 words (the, I, and, of, a, to, was, in, that, my) are function words; rank 10 ('my',440) is already 5\times rarer than rank 1 ('the',2{,}261).
Linear log–log slope: Fitting over ranks 10\text{--}1000 gives Zipf exponent s = 1.04 \approx 1.
n_i \propto \frac{1}{i^s} \iff \log n_i = -s \log i + c
Zipf exponent s = 1.04
Heavy Singleton Tails Across Unigrams to Trigrams
Zipfian Sparsity Scaling
Plotting rank–frequency curves for word unigrams, bigrams, and trigrams on the same log–log axes reveals how power-law tails flatten and become dominated by singletons (N = 1) as n increases:
Flattening Zipf exponents: The power-law slope drops from s = 1.04 (unigrams) to s = 0.69 (bigrams) and s = 0.47 (trigrams).
Singleton explosion:52\% of distinct words, 82\% of distinct bigrams, and 95\% of distinct trigrams in The Time Machine occur only once in the entire corpus.
Implication: Estimating each context tuple independently requires exponentially larger corpora for each additional token of context.
1-grams: s = 1.04, 52% of distinct 1-grams occur once
2-grams: s = 0.69, 82% of distinct 2-grams occur once
3-grams: s = 0.47, 95% of distinct 3-grams occur once
Effective branching factor: Assigning probability 1/k to every target token yields \textrm{PPL} = k—matching the uncertainty of rolling a fair k-sided die at each step.
Calibration scale: Ranges from \textrm{PPL} = 1 (deterministic oracle) to |\mathcal{V}| (uniform guessing) and \infty whenever any test token receives probability 0.
Laplace (Add-α) Smoothing and Its Failure Modes
Classical Count Smoothing
Laplace (add-\alpha) smoothing eliminates zero probabilities by adding a pseudocount \alpha > 0 to every n-gram numerator and \alpha|\mathcal{V}| to the context denominator:
The fluency-versus-perplexity paradox: Under Laplace smoothing (\alpha = 0.01), the trigram, whose generated samples looked most like Wells, suffers the worst held-out perplexity (2{,}481.4 vs. 753.6 for the bigram).
Why Laplace smoothing fails at n = 3: Because 87\% of validation trigrams are unseen, Laplace smoothing predicts a flat uniform distribution 1/|\mathcal{V}| on 87\% of test positions, ignoring both general word frequency and the observed bigram context (x_{t-1}).
Absolute discounting (D \approx 0.93): Subtracts D = c_1 / (c_1 + 2c_2) from every nonzero count to correct singleton selection bias, freeing mass D\,S(u)/N(u).
Recursive interpolation: Allocates the freed mass to the backed-off suffix context u' = u_{2:} down to the uniform floor 1/|\mathcal{V}|.
Continuation counts at lower orders: Lower orders count how many distinct predecessors precede w (rewarding versatile "said" over context-bound "traveller").
Implementing Interpolated Kneser–Ney in Python
From-Scratch Implementation
kneser_ney derives continuation counts, estimates D_k = c_1 / (c_1 + 2c_2), and evaluates the recursion:
def kneser_ney(train, tokens, vocab_size, n=3):"""Interpolated Kneser-Ney log-probabilities (nats) of each of tokens.""" counts = {n: collections.Counter(zip(*(train[i:] for i inrange(n))))}for k inrange(n -1, 0, -1): # Lower orders: continuation counts counts[k] = collections.Counter(g[1:] for g in counts[k +1]) stats = {}for k, c in counts.items(): c1, c2 = (sum(x == r for x in c.values()) for r in (1, 2)) N, S = collections.Counter(), collections.Counter()for g, x in c.items(): N[g[:-1]] += x S[g[:-1]] +=1 stats[k] = c, N, S, c1 /max(c1 +2* c2, 1) logp = []for i inrange(len(tokens)): p =1/ vocab_size # Below the unigram: uniformfor k inrange(1, min(n, i +1) +1): c, N, S, D = stats[k] g =tuple(tokens[i - k +1:i +1])if N[g[:-1]]: # An unseen context passes p down unchanged p = (max(c[g] - D, 0) + D * S[g[:-1]] * p) / N[g[:-1]] logp.append(math.log(p))return logp
Kneser–Ney vs. Laplace on Seen and Unseen Words
Empirical Smoothing Comparison
Comparing Kneser–Ney against Laplace (\alpha = 0.01) after context "the time"(N = 87) and across the entire validation split demonstrates why Kneser–Ney dominated statistical NLP for two decades:
trigram discount D = 0.93
P(traveller | the time): Kneser-Ney 0.53, Laplace 0.36
P(was | the time): Kneser-Ney 0.00037, Laplace 7.7e-05
P(filby | the time): Kneser-Ney 2.3e-05, Laplace 7.7e-05
Preserving frequent n-grams: For seen "traveller"(N = 47), subtracting D \approx 0.93 keeps P_{\textrm{KN}} = 0.53 \approx 47/87, whereas Laplace wastes a third of the mass (\hat{P}_\alpha = 0.36) on 4{,}316 \times 0.01 = 43.16 phantom counts.
Discriminating unseen continuations: Laplace gives unseen "was" and "filby" the exact same probability (7.7 \times 10^{-5}), whereas Kneser–Ney scores versatile "was"16\times higher than context-bound "filby", cutting held-out trigram perplexity by 8\times(2{,}481.4 \to 300.1).
Why Perplexity Cannot Compare Different Tokenizers
The scale mismatch: Perplexity divides by token count T, so a character model (\textrm{PPL} \approx 6.4), BPE-1024 model (\textrm{PPL} \approx 63), and word model (\textrm{PPL} \approx 300) lie on incompatible scales.
Bits per Byte (\textrm{bpb}): Normalizing total base-2 surprisal by the invariant UTF-8 byte length B measures the exact lossless compression rate (\textrm{bpb}/8).
Comparing Characters, BPE, and Words in Bits/Byte
Cross-Granularity Benchmark
Evaluating trigram models across character, BPE-1024, and word tokenizations on the exact same held-out text (adding \log_2 27 bits/letter to spell out each <unk> token in the word model) places all three on one scale:
From 400\times PPL gap to 0.2 bpb: While Laplace perplexities span 6.4 to 2{,}481.4, Laplace bits per byte sit within 2.58\text{--}2.81 bpb.
Why BPE-1024 wins (1.90 KN bpb): Two BPE tokens span \sim 5.6 characters (vs. 2 characters for a character trigram) while incurring zero <unk> spelling penalty (which costs the word trigram \approx 0.6 bpb).
Sliding Input–Target Windows for Neural Training
Sequence Data Partitioning
To train the neural language models of §8.4–§8.6 with minibatch SGD, we slice the BPE-encoded corpus x_1, x_2, \ldots into overlapping windows of length T = \texttt{num\_steps}:
Aligned input and 1-step shifted target: A window starting at index i forms input row \mathbf{X}_{i,:} = (x_i, \ldots, x_{i+T-1}) and target row \mathbf{Y}_{i,:} = (x_{i+1}, \ldots, x_{i+T}).
Dense supervision (T targets per row): Every step t \in \{1, \ldots, T\} inside a window predicts the next token x_{i+t} from prefix (x_i, \ldots, x_{i+t-1}).
Random minibatch sampling: Shuffling window start indices into minibatches of shape (batch_size, num_steps) decorrelates gradients across SGD updates.
Preventing Train–Validation Leakage Across Windows
Data Pipeline Implementation & Leakage Guard
def__init__(self, batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024):super(d2l.TimeMachine, self).__init__()self.save_hyperparameters() raw_text =self._download()if tokenization =='bpe':self.tokenizer = d2l.BPETokenizer( vocab_size, pattern=d2l.BPETokenizer.GPT2_PATTERN)self.tokenizer.train(raw_text) corpus, self.vocab =self.tokenizer.encode(raw_text), self.tokenizerelse: # tokenization='char': characters, via TimeMachine.build corpus, self.vocab =self.build(raw_text) windows = [corpus[i:i+num_steps+1] for i inrange(len(corpus)-num_steps)]# Drop the windows that straddle the split, so that no validation token# is a training target windows = windows[:num_train] + windows[num_train+num_steps:] array = d2l.tensor(windows)self.X, self.Y = array[:,:-1], array[:,1:]
Preventing Train–Validation Leakage Across Windows (cont.)
Data Pipeline Implementation & Leakage Guard
Why drop num_steps boundary windows: Adjacent length-T windows overlap in T - 1 tokens; skipping windows[num_train : num_train + num_steps] ensures no validation token ever appeared as a training target.
Inspecting Minibatches from TimeMachine Loader
Verifying Tensor Shapes & Alignment
Each minibatch from data.train_dataloader() yields two integer ID tensors (X, Y) of shape (batch_size, num_steps) where every entry of Y is X shifted one column to the left:
data = d2l.TimeMachine(batch_size=2, num_steps=10)for X, Y in data.train_dataloader():print('X:', X, '\nY:', Y)breakprint('X[0]:', repr(data.tokenizer.decode([int(i) for i in X[0]])))print('Y[0]:', repr(data.tokenizer.decode([int(i) for i in Y[0]])))
Work through these three quantitative questions on smoothing, bits per byte, and window partitioning:
Laplace Pseudocount Dilution: In The Time Machine, "the time" occurs N(u) = 87 times and is followed by "traveller"N(u, w) = 47 times (|\mathcal{V}| = 4{,}316). Compute the Laplace-smoothed probability \hat{P}_\alpha(\textrm{traveller} \mid \textrm{the time}) at \alpha = 0.01 and at \alpha = 1.0. Why does \alpha = 1.0 collapse?
Perplexity to Bits per Byte: A neural BPE language model achieves validation perplexity \textrm{PPL} = 64.0 on text where each BPE token averages 2.80 UTF-8 bytes. What is its bits per byte (\textrm{bpb}), and to what percentage of the original UTF-8 byte size could an arithmetic coder compress the text?
Continuation Counts in Kneser–Ney: The word "Francisco" has high raw frequency in news corpora, yet appears almost exclusively after "San". Compare its unigram MLE probability against its Kneser–Ney unigram continuation probability after an unseen bigram context like "ate ___".
\textrm{bpb} = \log_2(64.0) / 2.80 = 6.00 / 2.80 \approx 2.14\text{ bits/byte}, corresponding to a lossless compression ratio of 2.14 / 8 \approx 26.8\% of the original byte size.
Unigram MLE vs. Continuation: Raw unigram MLE scores "Francisco" high based on total occurrences, whereas Kneser–Ney continuation counts how many distinct predecessors precede "Francisco"(\approx 1,"San"), assigning it near-zero probability after "ate".
Summary: Language Modeling & Evaluation Metrics
Section Takeaways
Model / Metric
Mathematical Definition
Core Strength
Fundamental Limitation
n-Gram MLE
\hat{P}(x_t \mid u) = \frac{N(u, x_t)}{N(u)} for \|u\| = n - 1
Fast single-pass counting; captures frequent local phrases
87\% of held-out word trigrams have N = 0 \implies \textrm{PPL} = \infty