Maps to: CMU 11-711 Spring 2026, Lecture 3 (01/20), slides
anlp-s2026-03-lm.pdf; course demo code03_lm_fundamentals/(lm_basics_bigrams.ipynb, character-level bigrams on a dataset of names, after Karpathy’s makemore;lm_basics_neural.ipynb). Readings: K. Cho, Natural Language Understanding with Distributed Representation (2015), ch. 5 up to §5.4.2; additional: Y. Bengio, R. Ducharme, P. Vincent, C. Jauvin, A Neural Probabilistic Language Model (JMLR 2003); X. Glorot, Y. Bengio, Understanding the difficulty of training deep feedforward neural networks (AISTATS 2010). Sources: the public slides (some adapted from Graham Neubig’s Fall 2024 course), the readings, and the papers cited in each section. Instead of the course’s character-level names dataset, the demos use a word-level toy language whose true probabilities are known exactly (§5). Every number labelled “measured” comes fromcode/lecture03/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, CPU). Code:code/lecture03/— every demo runs in under 30 seconds. Reading time: ~110 minutes for the prose; ~30 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Place language modeling among prediction problems (binary, multi-class, structured) and say what a language model is: a probability distribution over all sequences.
- List what a language model can do — score, generate, generate conditionally — and how tasks such as translation, question answering and classification become language-modeling problems.
- Write the autoregressive factorization and explain why it turns an impossible problem into many small ones.
- Train a bigram/n-gram model by counting, prove that counting is maximum-likelihood estimation, and explain why maximum likelihood minimizes the KL divergence to the data distribution.
- Work in log space, generate by sampling, and evaluate with negative log-likelihood and perplexity, including what perplexity means and what its floor is.
- Explain smoothing, and the three problems of n-gram models: similar words, intervening words, long-distance dependencies.
- Build the feed-forward neural language model (Bengio et al., 2003), and say precisely which n-gram problems it solves and which it does not.
- Apply the practical tools of every training run: data splits, early stopping against overfitting, initialization, learning-rate schedules and warmup, batching, padding and masking.
0.2 Prerequisites and scope
- Prerequisites: Lecture 2 (embeddings, neural networks, cross-entropy, KL divergence, backpropagation, the PyTorch training loop).
- Scope: language models with a fixed-length context: bigrams, n-grams, and the feed-forward neural LM, plus the training practice that all later models share.
- Not in scope: models with unbounded context (recurrent networks, Lecture 4; Transformers, Lecture 5), and decoding strategies beyond plain sampling (Lecture 9).
0.3 Section → code map
| Section | Idea | Demo in code/lecture03/ |
|---|---|---|
| §2, §4 | scoring sequences; bigrams by counting = MLE; log space; sampling; NLL and perplexity | 01_bigram_lm.py |
| §5 | a language with known probabilities | lm_world.py (run it for the language’s statistics) |
| §6 | n-grams: order, smoothing, zero counts, data size, the three problems | 02_ngrams.py (+ ngram.py) |
| §7 | the feed-forward neural LM: vs n-grams, the window horizon, shared strength, generation | 03_neural_lm.py (+ neural_lm.py, lmkit.py) |
| §8 | overfitting, initialization, schedules, batching, masking | 04_practical.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| a sequence of tokens; its prefix | |
| , | the token vocabulary and its size |
| the set of all finite sequences over | |
<s>, </s> | start and end markers; every sentence ends with </s> |
| or | the true data distribution; the model |
| a dataset of sequences (samples from ) | |
| NLL, PPL | negative log-likelihood; perplexity |
All logarithms are natural (results in nats); divide by for bits.
1. Types of prediction
Lectures 1–2 predicted one label from a small set:
- binary classification: “I hate this movie” → positive / negative;
- multi-class classification: → very good / good / neutral / bad / very bad.
Many NLP outputs are not one label from a small set but a whole structure drawn from an exponential, or infinite, set:
- structured prediction: “I hate this movie” →
PRP VBP DT NN(a part-of-speech tag per word: possible outputs for four words with 45 tags), or → “kono eiga ga kirai” (a Japanese sentence: any sequence of Japanese tokens).
Lecture 1 showed what happens if we treat a sentence as one giant label: a softmax over candidates. The way out is to model sequences directly, one piece at a time. That is language modeling, and it is the backbone of every model in the rest of the course.
2. What is a language model?
2.1 A distribution over sequences
A language model (语言模型) is a probability distribution over all sequences .
The simplest distribution, for comparison, is a biased coin: , . Two outcomes, two numbers. A language model is the same object with one outcome for every possible sequence: , , …, , …. There are a lot of sequences (infinitely many), each with its own probability, and all of them sum to 1.
2.2 What can we do with one?
Score sequences. A good model assigns high probability to fluent, plausible text and low probability to garbage: high, low. Measured on our toy language (demo 01 Part A): the true distribution gives “for tennis class he wanted to buy his own racquet .” a log-probability of −6.86 and its scramble probability 0 (log = −∞). A bigram model gives −11.34 and −87.01.
Generate sequences. Draw : a new text that looks like the training data.
Generate conditionally. Condition on a context and generate the continuation, . Almost every task fits this form:
- machine translation: context = a sentence in English, continuation = its Japanese translation;
- in general: context = instructions, examples, the start of an output; continuation = the output.
Do tasks by scoring or by generating.
- Answer questions: score each multiple-choice answer as a continuation, or generate the answer.
- Classify text: score the text under each label (“This review is positive: …”), or generate the label after a classification prompt.
- Correct grammar: score each word and replace low-scoring ones, or generate a corrected version.
This versatility is why language models became the foundation of modern NLP (Lectures 6–8).
3. Autoregressive language models
3.1 The factorization
By the chain rule of probability, any distribution over sequences can be written exactly as
a product of next-token distributions, each conditioned on its context (the prefix). Including a final </s> token makes the length part of the prediction: a sentence ends when the model predicts </s>.
This changes the problem’s size completely. is defined over , the space of all sequences, which is enormous. Each factor is defined over , the vocabulary, which is much smaller (128 words in our toy language, tens of thousands of tokens in a real LLM). Sequence modeling has become next-token prediction: a classification problem with classes, the tool of Lectures 1–2, applied once per position.
The factorization itself is exact. The key modeling question is how to represent , a function of a context that keeps getting longer. The rest of this lecture and the next two answer it with increasingly powerful models: bigram → n-gram → feed-forward neural (today) → recurrent (Lecture 4) → Transformer (Lecture 5).
4. Bigram models: the four core ideas
4.1 The model
A bigram model (二元语言模型) keeps only the previous token:
The parameters are a table: , one probability distribution over next tokens for every possible previous token.
4.2 Training: the problem set-up
Goal: model a data distribution, . We only have samples: a dataset drawn from , split into training, dev and test sets.
Training a bigram model sets each probability from counts in the training data:
Measured (demo 01 Part B, 2,000 training sentences): the word “a” occurs 828 times as a context. The counted probabilities of what follows (car 0.217, talk 0.140, book 0.127, bicycle 0.138, …) are within 0.018 of the true distribution of the next token after “a” (car 0.214, talk 0.143, …). That true distribution can be computed exactly in our toy language. (Note that “a” precedes both vehicles and the “a talk / a book” of other sentence types; a bigram model cannot tell which kind of sentence it is in.)
4.3 Why counting? Maximum likelihood
The counting rule is not arbitrary: it is the maximum-likelihood estimate (最大似然估计, MLE), the parameters that make the training data most probable:
Derivation (the slide’s exercise). For a fixed previous token , the log-likelihood contains , where counts the pair , subject to . With a Lagrange multiplier : . So , and the constraint gives . That is the counting formula.
Demo 01 checks it numerically: moving 0.02 of probability mass between any two next tokens after “a” (in either direction) lowered the training log-likelihood in 6 of 6 trials, by 2.0–3.3 nats. The counted table sits at the top of the hill.
Why maximum likelihood? Because it makes match the data distribution. With the data distribution:
The expectation over the unknown is replaced by an average over samples from it, our dataset. Maximum likelihood is “minimize KL to the data distribution, estimated from samples”. It is the same argument as Lecture 2’s cross-entropy loss, now for whole sequences.
4.4 Log space
Probabilities of sequences are products of many numbers below 1; they become astronomically small. Multiplying the probabilities of the 2,000 training sentences (demo 01 Part C), the running product underflows to exactly 0.0 after 67 sentences. The true value is about , far below the smallest positive float64 (, or with denormals). The fix is to work with log probabilities and add instead of multiply:
The sum, −23,155.2, is perfectly representable. Log space also turns products into sums, which are easier to differentiate (gradients of a sum are sums of gradients). Every likelihood in this course is computed in log space.
4.5 Generation
Generate from an autoregressive model by repeatedly sampling a next token and appending it to the context:
until </s> is generated: x̂_t ~ p_θ(x_t | x̂_{<t})
This is equivalent to sampling from the model’s joint distribution over full sequences (the chain rule again; more in Lecture 9). How good are a bigram’s samples? Demo 01 Part D draws 1,000. Because our toy language has known rules, we can check each one: only 149 of 1,000 are sentences of the language. With one token of memory, the bigram forgets the subject and the topic mid-sentence, e.g. for swimming class , we wanted to order her own racquet . (wrong possessive, wrong item).
4.6 Evaluation: log-likelihood and perplexity
We evaluate a model by the probability it assigns to held-out data (dev or test sets):
counts every predicted token, including </s>. Perplexity (困惑度) has a concrete meaning. A model that spreads its probability uniformly over tokens at every step has NLL per token and perplexity exactly . So perplexity is the “effective number of equally likely choices” per token. The slide’s example: if a model gives ” bark” probability 0.0352 after “When a dog sees a squirrel it will usually”, that token’s contribution is .
Measured (demo 01 Part E):
| model | test NLL per token | test perplexity |
|---|---|---|
| uniform guess over 129 tokens | 4.860 | 129 |
| unigram (add-0.01) | 4.056 | 57.76 |
| bigram (add-0.01) | 1.077 | 2.94 |
| the true language (its entropy) | 0.754 | 2.13 |
The last row is something real text never gives us: the floor. No model can beat the true distribution’s entropy on data drawn from it, so the gap between a model and the floor is exactly how much it has left to learn (§5).
5. A language with known probabilities
On real text, we compare models only with each other (“perplexity 30 is better than 40”); nobody knows how far either is from the truth. The demos therefore use Errand World (lm_world.py), a small artificial language whose sentence probabilities are known exactly. It has three sentence types, chosen to contain the three problems the slides list for n-gram models:
| type | example | what makes it hard |
|---|---|---|
| purchases (40%) | for tennis class , which met on monday and on friday , she really wanted to get her own racquet . | the item depends on the activity, 8–21 tokens earlier (the relative clause is optional and variable); the possessive agrees with the subject 4–5 tokens earlier |
| people (30%) | dr gertrude smith gave a talk . | the last name depends on the title (dr → smith/jones, prof → chen/garcia, …) with a first name in between; first names are Zipf-distributed, so many are rare |
| vehicles (30%) | she purchased a motorcycle yesterday . | similar words: bought / purchased / got / sold / rented behave identically |
Statistics (run python3 lm_world.py): 34,320 possible sentences, 128 word types, 11.02 tokens per sentence including </s>, and an entropy of 0.7540 nats per token: no model can reach a perplexity below 2.125. A 2,000-sentence training set contains 1,357 distinct sentences covering only 52% of the probability mass, so a good model must generalize to sentences it never saw.
Because , every test NLL minus 0.754 is the model’s KL divergence from the true language, per token.
Probes. Besides overall NLL, demos measure each problem directly. A probe is a prefix whose correct continuations are known: “for tennis class he wanted to buy his own ___” (correct: racquet, ball, net), the same with a 1-day or 3-day clause (14 or 20 tokens between activity and item), “dr ___” (smith, jones), “for cooking class she really wanted to buy ___” (her). The probe score is the probability mass the model puts on the correct tokens. The true language scores 1.000 on all of them.
6. N-gram models
6.1 Longer contexts, same counting
An n-gram model conditions on the previous tokens:
Contexts at the start of a sentence are padded with copies of <s>.
6.2 The zero-count problem and smoothing
A longer context is more informative but rarer. Many perfectly possible n-grams never occur in training, and counting gives them probability 0. One zero in a test sentence makes its probability 0, and the perplexity infinite. Measured without smoothing (demo 02 Part B, 2,000 training sentences): 13.2% of test sentences get probability 0 under a trigram, 22.7% under a 5-gram.
Smoothing (平滑) reserves some probability for unseen events. The simplest is to add a fake count to every possible n-gram:
is add-one (Laplace) smoothing. is a hyperparameter, tuned on dev (demo 02 Part A, test NLL per token):
| n | train (best ) | ||||
|---|---|---|---|---|---|
| 1 | 4.056 | 4.056 | 4.056 | 4.056 | 4.040 |
| 2 | 1.448 | 1.122 | 1.077 | 1.083 | 1.024 |
| 3 | 1.722 | 1.118 | 0.994 | 0.998 | 0.890 |
| 4 | 2.077 | 1.294 | 1.087 | 1.083 | 0.844 |
| 5 | 2.444 | 1.519 | 1.189 | 1.159 | 0.808 |
Two lessons. First, add-one is far too strong here (trigram 1.722 vs 0.994): one fake count for each of 129 possible next tokens swamps contexts seen only a few times. Second, with 2,000 sentences the trigram is best. The 5-gram fits training data better (0.808) but generalizes worse (1.159), because most of its long contexts were never seen.
Better smoothing methods exist and were the core of statistical NLP for two decades. Interpolation mixes estimates of different orders (, Jelinek & Mercer, 1980). Backoff uses a shorter context when the long one is unseen. Kneser–Ney smoothing (1995; Chen & Goodman, 1999) estimates the lower orders by how many different contexts a word follows. That is the method of the KenLM toolkit the slides mention.
6.3 More data supports longer contexts
| training sentences | bigram | trigram | 4-gram | 5-gram | best | best − entropy |
|---|---|---|---|---|---|---|
| 500 | 1.137 | 1.142 | 1.407 | 1.734 | n = 2 | 0.383 |
| 2,000 | 1.070 | 0.985 | 1.078 | 1.164 | n = 3 | 0.231 |
| 20,000 | 1.041 | 0.906 | 0.899 | 0.871 | n = 5 | 0.117 |
| 100,000 | 1.041 | 0.898 | 0.885 | 0.850 | n = 5 | 0.096 |
(demo 02 Part C; tuned on dev in each cell.) The best order grows with the data: with enough counts, longer contexts become usable. But even 100,000 sentences leave a gap of 0.096 nats to the floor.
6.4 Three problems counting cannot fix
The slides list three problems. All three are measured by the probes (demo 02 Part D):
| model | long-distance, 8 back | 14 back | 20 back | dr ‹rare name› ___ | agreement |
|---|---|---|---|---|---|
| 3-gram, 2,000 sentences | 0.142 | 0.142 | 0.142 | 0.472 | 0.199 |
| 5-gram, 2,000 sentences | 0.140 | 0.140 | 0.140 | 0.746 | 0.598 |
| 3-gram, 100,000 sentences | 0.139 | 0.139 | 0.139 | 0.998 | 0.200 |
| 5-gram, 100,000 sentences | 0.138 | 0.138 | 0.138 | 0.998 | 0.600 |
| true language | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 |
- Cannot share strength among similar words. “she bought a car”, “she purchased a bicycle”: an n-gram model learns about “bought a” and “purchased a” separately, even though they behave identically. → solution: neural networks (§7).
- Cannot condition on context with intervening words. “Dr. Jane Smith”, “Dr. Gertrude Smith”: the last name depends on the title, but a trigram’s context is (dr, gertrude), seen only if this exact pair was in training. The probe for the 10 rarest first names reaches 0.47 with 2,000 sentences and needs 100,000 to approach 1.0. → solution: neural networks.
- Cannot handle long-distance dependencies. “for tennis class he wanted to buy his own racquet” / “for programming class he wanted to buy his own computer”: the activity is 8 or more tokens back, outside any n-gram’s window. The long-distance probes sit at chance (~0.14: spread over all eight activities’ items) whatever the amount of data. Agreement needs the subject 4–5 tokens back; only the 5-gram sometimes sees it (0.60, when no adverb intervenes). → solution: neural networks with unbounded context (Lectures 4–5).
6.5 When to use n-gram models
Neural LMs achieve better performance, but n-gram models remain useful. They are extremely fast to estimate and apply: no training loop, a hash-table lookup per token. And their perfect memorization can be the point. Examples: checking whether a text (or a benchmark question) appears verbatim in a training corpus, or giving an exact estimate of how frequent an expression is. KenLM is the standard toolkit. For web-scale corpora, suffix-array methods such as infini-gram extend the idea to n of any length.
7. The feed-forward neural language model
7.1 The model
Bengio et al. (2003) kept the n-gram’s assumption, a fixed context of tokens, but replaced the count table with a neural network:
Training is again maximum likelihood, , so the loss at each position is . That is exactly Lecture 2’s cross-entropy loss, with the one-hot “label” being the next token and the classes being the whole vocabulary.
In code (neural_lm.FFNNLM), all positions of a batch are computed at once. unfold builds every position’s window of previous token ids (with <s> before the sentence start). The training loop is lmkit.train_lm: teacher forcing feeds the true prefix at every position, and the loss is the average cross-entropy over all positions.
7.2 Results: same context, better model
The cleanest comparison is a trigram against a neural LM that also sees exactly 2 previous tokens (demo 03 Part A; test NLL per token, floor 0.754):
| training sentences | trigram (tuned ) | neural, context 2 | trigram − floor | neural − floor |
|---|---|---|---|---|
| 500 | 1.139 | 0.972 | 0.385 | 0.218 |
| 2,000 | 0.994 | 0.928 | 0.240 | 0.174 |
| 20,000 | 0.907 | 0.914 | 0.153 | 0.160 |
With scarce data the neural model is much closer to the truth (at 500 sentences it halves the KL). With plenty of data the trigram catches up, and is even slightly ahead here (the neural model got only 6 epochs at that size). Sharing strength matters most when counts are sparse.
7.3 Combination features
A hidden unit computes over the concatenated context embeddings. Because each context position has its own slice of , a unit can detect a combination such as “the previous word is a determiner AND the word before is a verb”. It gives a large positive value only when both slices match (the slide’s example of row 34 of the weight matrix). These are the learned combination features of Lecture 2, now over positions in the context.
7.4 Where is strength shared?
Similar contexts get similar hidden states, and similar hidden states give similar predictions. For two contexts with hidden states and , the probability of the same next word (with output vector ) under each is and , so
If (e.g. “it’s a great” and “it is a wonderful”), every word gets almost the same probability in both contexts, and too. So whatever the model learned in one context transfers to the other. The slide lists three places where strength is shared:
- similar words get similar embeddings (input side);
- similar contexts get similar hidden states;
- similar output words get similar output weights (rows of ).
Measured (demo 03 Part C, window-4 model, 2,000 sentences):
| word | nearest input embeddings | nearest output embeddings (rows of ) |
|---|---|---|
| bought | gertrude, keyboard, smith, called | got, rented, sold, purchased |
| purchased | purchase, got, ball, his | got, bought, rented, sold |
| gertrude (rare) | bought, racquet, towel, smith | wanda, yuki, pedro, hugo |
| dr | car, omar, prof, jonas | for, ms, prof, mr |
| tennis | wednesday, felix, my, tripod | photography, cooking, programming, painting |
| car | brown, ines, week, dr | motorcycle, bicycle, scooter, truck |
The output table is beautifully organised: synonyms, names, titles, activities and vehicles each form a cluster. The input table is not. A likely reason: in a concatenation model each input vector is read by four different position-specific slices of , so its raw coordinates need not reflect similarity. Each output row, by contrast, is trained directly on “which hidden states predict me”. The hidden states are organised too: cos(h(“she bought a”), h(“she purchased a”)) = 0.84 and cos(h(“she bought a”), h(“he rented a”)) = 0.75, but cos(h(“she bought a”), h(“dr jane”)) = −0.04.
The payoff is generalization to contexts rarely or never seen. For “dr/prof/mr/ms ‹one of the 10 rarest first names› ___” (these names occur 13 times in total in 500 training sentences):
| training sentences | trigram | neural, context 2 |
|---|---|---|
| 500 | 0.174 | 0.862 |
| 2,000 | 0.470 | 0.985 |
The neural model has learned “after a title and any first name comes that title’s surname”, because all first names share an embedding region. The trigram needs to have seen each (title, name) pair.
7.5 What problems are handled?
| problem | n-gram | feed-forward neural LM |
|---|---|---|
| sharing strength among similar words (bought / purchased) | ✗ | ✓ (and similar contexts, too) |
| conditioning on context with intervening words (Dr. X Smith) | ✗ (only if seen) | ✓ |
| long-distance dependencies (tennis … racquet) | ✗ | ✗ — not solved yet |
The third row deserves a precise look, because the feed-forward model does see further when its window is widened (demo 03 Part B, 2,000 sentences):
| window | parameters | test NLL | long 8 | long 14 | long 20 | dr ‹name› | agreement |
|---|---|---|---|---|---|---|---|
| 2 | 29,411 | 0.928 | 0.13 | 0.13 | 0.13 | 0.98 | 0.20 |
| 4 | 37,603 | 0.891 | 0.14 | 0.14 | 0.14 | 0.99 | 0.60 |
| 8 | 53,987 | 0.864 | 0.96 | 0.14 | 0.14 | 0.99 | 1.00 |
| 12 | 70,371 | 0.862 | 0.97 | 0.14 | 0.13 | 0.99 | 1.00 |
| 16 | 86,755 | 0.847 | 0.98 | 0.97 | 0.13 | 0.99 | 1.00 |
The window is a hard horizon. A dependency is solved exactly when it fits inside the window (8 back from window 8, 14 back from window 16) and is at chance when it does not (20 back: 0.13 for every window). Widening the window helps but never ends the problem. Every extra position adds its own block of weights ( hidden parameters), and some dependency is always longer: in real text, a pronoun may refer to a name three paragraphs earlier. We need models whose context is unbounded: recurrent networks (Lecture 4) and attention (Lecture 5).
7.6 Generation quality, checked exactly
Because the true language is known, generated text can be graded exactly (demo 03 Part D, 1,000 samples per model):
| model | valid sentences | of which not in training | mean true log P (valid ones) |
|---|---|---|---|
| trigram, 2,000 sentences | 411 | 37 | −7.14 |
| 5-gram, 100,000 sentences | 633 | 212 | −7.49 |
| neural, window 4, 2,000 sentences | 545 | 91 | −7.45 |
| neural, window 16, 2,000 sentences | 906 | 216 | −8.21 |
The window-16 neural model, trained on 2,000 sentences, writes valid sentences 91% of the time, more often than a 5-gram trained on 50 times more data. About a quarter of its valid sentences are new (not copies of training sentences). Generating new valid sentences is generalization; repeating training sentences is memorization. A good model does both, in proportion to how likely the sentences are.
8. Important practical concepts
A deep-learning system has many moving parts: the architecture, the optimizer, the weights, the hyperparameters, the data. We want experiments that give reliable conclusions. The following ideas are implicit in almost every experiment in this course.
8.1 Train, validation (dev) and test splits
The goal is to fit a target distribution :
- training data: samples from , used to fit ;
- validation data: held-out samples from to check generalization. We try configurations (hyperparameters, ablations, model selection) and choose the one that generalizes best;
- test data: held-out samples from , used once at the end as an unbiased check of the final configuration. Do not look at it during development.
8.2 Overfitting
A model may fit the training sample but not generalize. The symptom: training loss decreasing while validation loss increases. Demo 04 Part A trains a large model (window 8, 512 hidden units) on only 300 sentences:
| epoch | 1 | 2 | 4 | 6 | 10 | 20 | 40 | 60 |
|---|---|---|---|---|---|---|---|---|
| train loss | 2.509 | 1.128 | 0.831 | 0.797 | 0.715 | 0.672 | 0.627 | 0.603 |
| dev NLL | 1.404 | 1.066 | 0.975 | 1.008 | 1.036 | 1.124 | 1.272 | 1.307 |
Dev NLL is best at epoch 4, then climbs steadily while training loss keeps falling: the model memorises the 300 sentences. Remedies: choose different hyperparameters (a smaller model, fewer epochs), add regularization (weight decay, dropout), or choose the model with minimum validation loss (early stopping (早停)). Keeping the epoch-4 weights gives test NLL 0.973 instead of 1.312.
8.3 Initialization
Weight initialization affects the optimization trajectory. The standard choice for tanh networks is Xavier (Glorot) initialization (Glorot & Bengio, 2010):
weights drawn uniformly around zero, scaled so that the variance of activations (forward) and of gradients (backward) stays roughly constant from layer to layer. What goes wrong otherwise (demo 04 Part B; window 4, 128 tanh units):
| init | saturated tanh units at init | distinct hidden values | dev NLL at init | after 1 epoch | after 10 epochs |
|---|---|---|---|---|---|
| PyTorch default | 0.0% | 128 | 4.958 | 1.167 | 0.880 |
| Xavier | 0.8% | 128 | 5.015 | 1.139 | 0.883 |
| 82.9% | 52 | 29.679 | 13.507 | 1.318 | |
| all zeros | 0.0% | 1 | 4.875 | 4.791 | 4.301 |
- Too large ( with 128 inputs): pre-activations have standard deviation ~11, so 83% of tanh units sit at ±1 where their gradient . The initial predictions are wildly overconfident (dev NLL 29.7), and after 10 epochs the model is still far behind (1.318).
- All zeros: every hidden unit computes the same function (one distinct value), and since the output weights are zero, no gradient reaches the hidden layer at all. Only the output bias learns, which is at best a unigram model (4.301 after 10 epochs). Random initialization is needed to break symmetry.
- PyTorch’s default (a scaled uniform) and Xavier behave alike here.
8.4 Learning-rate schedules and warmup
A schedule varies the learning rate during training. A cosine schedule starts high and decays smoothly to zero: large updates early (exploration), small updates late (convergence). Warmup ramps the rate up from near zero over the first steps. It stabilizes the early updates, when gradients and optimizer statistics are still unreliable. At an aggressive base rate of 0.02 (demo 04 Part C, dev NLL after each of 10 epochs):
| schedule | ep 1 | ep 2 | ep 4 | ep 6 | ep 8 | ep 10 |
|---|---|---|---|---|---|---|
| constant | 0.983 | 0.998 | 0.961 | 0.944 | 0.954 | 0.945 |
| cosine | 0.981 | 0.987 | 0.934 | 0.897 | 0.884 | 0.879 |
| warmup (32 steps) + cosine | 0.992 | 0.992 | 0.943 | 0.901 | 0.883 | 0.878 |
The constant rate keeps bouncing; decaying it lets the model settle (0.945 → 0.879). Warmup adds nothing measurable for this shallow model. It matters for deep networks, Transformers especially (Lecture 5).
8.5 Batching
We process several examples at once, a batch. This takes advantage of parallel hardware (one matrix multiplication for examples instead of small ones) and averages out some of the noise in individual gradients. Five epochs over 2,000 sentences (demo 04 Part D):
| batch size | updates | wall time (varies) | dev NLL |
|---|---|---|---|
| 1 | 10,000 | 1.9 s | 0.947 |
| 16 | 625 | 0.4 s | 0.896 |
| 256 | 40 | 0.3 s | 0.969 |
Batch size trades the number of updates against their quality and speed. Batch 1 updates often but noisily and slowly; batch 256 computes fast but makes only 40 updates in 5 epochs. In practice the batch size and learning rate are tuned together.
8.6 Padding and masking
Inputs of variable length are padded to a common length with a pad token, and operations involving pad tokens must be masked out. In particular, the loss must ignore padded target positions: PyTorch’s cross_entropy(..., ignore_index=-100) with padded targets set to −100. In a random batch of Errand World sentences, 57% of target positions are padding (demo 04 Part E). Train without the mask, and the reported training loss drops to 0.390 (vs 0.851 masked), because over half of it is now the trivial task “predict <pad> after <pad>”. The model’s real dev NLL, measured correctly, is unchanged (0.876 vs 0.880): here the bug corrupts the measurement, not the learning. With other architectures, e.g. models that attend to padding (Lecture 5), unmasked padding can also change what is learned. Lecture 4 shows a concrete batching example for sequence-to-sequence models.
(The Adam optimizer, used in all these demos, is derived in Lecture 5.)
9. Summary
- Language modeling = a probability distribution over all sequences. It can score, generate, and generate conditionally, and most tasks (translation, QA, classification, grammar correction) can be cast as one of these.
- Autoregressive factorization: is exact and turns sequence modeling into next-token classification over the vocabulary. The modeling question is how to represent .
- Bigram/n-gram models estimate it by counting, which is maximum likelihood, which is minimizing KL to the data distribution estimated from samples. Work in log space (the product of 2,000 sentence probabilities underflows after 67). Generate by sampling token by token. Evaluate by held-out NLL and perplexity = exp(NLL per token) = effective number of choices.
- A language with known probabilities gives the floor: 0.754 nats/token (perplexity 2.125). Model NLL minus the floor is the KL to the truth.
- N-grams need smoothing (13.2% of test sentences get probability 0 under an unsmoothed trigram; add-one is far too strong). The best order grows with data (trigram at 2,000 sentences, 5-gram at 100,000). They cannot share strength among similar words or across intervening words unless every pattern was seen, and cannot reach beyond their window at all.
- The feed-forward neural LM shares strength through embeddings, hidden states and output weights. It is much better with scarce data (0.972 vs 0.994 trigram at 500 sentences; rare-name probe 0.86 vs 0.17) and generates valid sentences far more often (906/1000 vs 411). But its window is a hard horizon (the 20-back dependency stays at chance for every window up to 16).
- Practice: dev for choices, test once; watch for dev loss rising (early stopping turned 1.312 into 0.973); initialize to avoid saturation and symmetry (Xavier); decay the learning rate (0.945 → 0.879); tune batch size with the learning rate; mask padding (or your loss numbers lie).
Common pitfalls
- Comparing perplexities across vocabularies or tokenizers. Perplexity is per token: a tokenizer that makes more, easier tokens lowers it without improving the model. Compare per word or per character, or with the same tokenizer.
- Forgetting
</s>in the NLL. The model must also predict where sentences end; leaving it out flatters every model. - Smoothing by habit (add-one). With a large vocabulary it destroys the estimates (1.722 vs 0.994); tune on dev.
- Believing a bigger n-gram is always better. Without enough data the 5-gram is worse than the trigram on test, while better on train.
- Reading input embeddings as word similarity in every model. In the concatenated feed-forward LM, the clean similarity structure was in the output weights.
- Evaluating on the training set. Train NLL keeps improving while the model overfits (0.603 train vs 1.307 dev at epoch 60).
- Zero or huge initial weights. Zeros never break symmetry (only the bias learns); saturates 83% of tanh units.
- Not masking padding. The reported loss (0.390) can be off by a factor of two from the real one.
Exercises
-
MLE by hand. A training set contains the bigrams (a, b) ×3, (a, c) ×1, (b, a) ×2. Give the MLE bigram probabilities and , then the add-1 smoothed ones with vocabulary {a, b, c} (ignore
</s>).Answer
MLE: $p(b \mid a) = 3/4$, $p(c \mid a) = 1/4$, $p(a \mid a) = 0$; $p(a \mid b) = 1$. Add-1 with $\lvert V\rvert = 3$: $p(b \mid a) = 4/7$, $p(c \mid a) = 2/7$, $p(a \mid a) = 1/7$; $p(a \mid b) = 3/5$, $p(b \mid b) = p(c \mid b) = 1/5$. Smoothing moved a lot of mass to unseen events: with tiny counts, add-1 is a strong prior. -
Derive the MLE. Show with a Lagrange multiplier that maximizing subject to gives .
Answer
$\mathcal{L} = \sum_j c_j \log\theta_j - \lambda(\sum_j \theta_j - 1)$. $\partial\mathcal{L}/\partial\theta_j = c_j/\theta_j - \lambda = 0 \Rightarrow \theta_j = c_j/\lambda$. Summing over $j$: $1 = \sum_j c_j / \lambda \Rightarrow \lambda = \sum_k c_k$. The objective is concave in $\theta$ (sum of logs), so this stationary point is the maximum. -
Perplexity. A model assigns probabilities 0.5, 0.25, 0.25 and 0.125 to the four tokens (including
</s>) of a test sentence. Compute its NLL per token and perplexity. What perplexity would a model have that always spreads probability uniformly over 8 tokens?Answer
NLL $= -(\ln 0.5 + 2 \ln 0.25 + \ln 0.125)/4 = (0.693 + 2.773 + 2.079)/4 = 1.386$ nats per token; PPL $= e^{1.386} = 4.0$ (the geometric mean of 2, 4, 4, 8 is 4). Uniform over 8: NLL $= \ln 8$, PPL $= 8$. -
The floor. Errand World’s entropy is 0.754 nats per token. A model has test NLL 0.864. What is its KL divergence from the true language per token, and per sentence (11.02 tokens on average)? Can any model reach 0.70 on a large test set drawn from the language?
Answer
KL = 0.864 − 0.754 = 0.110 nats per token ≈ 1.21 nats per sentence. No: cross-entropy ≥ entropy (Gibbs' inequality), so on a large test set from the true distribution, no model can go below 0.754 in expectation. (A small test set could, by chance, be easier than average.) -
Counting n-gram parameters. With a vocabulary of 50,000 tokens, how many free parameters does a full 5-gram table have? How many does a feed-forward LM with window 4, , hidden width 2,048 have (ignore biases)?
Answer
5-gram: $50{,}000^4$ contexts × 49,999 free probabilities ≈ $3 \times 10^{23}$ (almost all of which would be zero counts). Neural: embeddings $50{,}000 \times 512 = 25.6$M; $W_1$: $(4 \cdot 512) \times 2{,}048 = 4.2$M; output $2{,}048 \times 50{,}000 = 102.4$M; total ≈ 132M — large, but independent of how many contexts exist, and every parameter is shared across all contexts. -
Why the window is a horizon. In Errand World, the 20-back probe stays at 0.13 for every window up to 16. Using the factorization, explain why no fixed-window model, however large, can exceed chance on a dependency longer than its window. What is the chance level here?
Answer
The model's prediction at that position is a function only of the last $w$ tokens; if the activity lies further back, two prefixes that differ only in the activity produce identical inputs and therefore identical predictions. The best such a model can do is predict the item distribution *averaged* over activities. The probe mass on the correct activity's items is then the average over activities of their share of that mixture, ≈ 0.13 here (the 8 activities' items overlap slightly: goggles appears twice). -
Similar contexts. Using , show that if the two contexts give identical next-token distributions. What does the measured cosine 0.84 between h(“she bought a”) and h(“she purchased a”) imply for what the model learned about “purchased a ___” from “bought a ___” examples?
Answer
If $h_j = h_k$ then $Z_j = Z_k$ and the ratio is 1 for every $w$: identical distributions. A high cosine means the two hidden states are close, so the predictions after "purchased a" are close to those after "bought a": training examples with either verb improve both, which is how the model generalizes to rare verb–vehicle combinations an n-gram must see individually. -
Initialization arithmetic. A hidden layer has inputs with values of variance ~1. With weights from , what is the standard deviation of a pre-activation? With Xavier uniform ()? Why does the first saturate tanh?
Answer
Variance of $\sum_{i=1}^{128} w_i x_i$ = $128 \cdot \text{Var}(w)\text{Var}(x)$. $\mathcal{N}(0,1)$: variance 128, std ≈ 11.3 — tanh(±11) = ±1, gradient ≈ 0. Xavier: $\text{Var}(w) = (6/256)/3 = 1/128$, so variance ≈ 1, std ≈ 1 — tanh's useful range.
Related assignment (concepts only)
- Assignment 1 — Build your own LLaMa. The training objective you will implement is exactly §4.3/§7.1 (next-token cross-entropy = maximum likelihood), evaluated by NLL and perplexity (§4.6), with batching, padding masks, initialization and schedules (§8). These notes do not provide assignment code.
Further reading
- K. Cho, Natural Language Understanding with Distributed Representation, arXiv:1511.07916, ch. 5 up to §5.4.2 (course reading).
- Y. Bengio, R. Ducharme, P. Vincent, C. Jauvin, “A Neural Probabilistic Language Model”, JMLR 3, 2003.
- X. Glorot, Y. Bengio, “Understanding the difficulty of training deep feedforward neural networks”, AISTATS 2010 — Xavier initialization.
- C. E. Shannon, “Prediction and Entropy of Printed English”, Bell System Technical Journal, 1951 — entropy of a language, measured by human next-letter prediction.
- S. F. Chen, J. Goodman, “An Empirical Study of Smoothing Techniques for Language Modeling”, Computer Speech & Language, 1999 — interpolation, backoff, Kneser–Ney.
- K. Heafield, “KenLM: Faster and Smaller Language Model Queries”, WMT 2011.
- J. Liu et al., “Infini-gram: Scaling Unbounded n-gram Language Models to a Trillion Tokens”, 2024.
- D. Jurafsky, J. H. Martin, Speech and Language Processing (3rd ed. draft), chapter “N-gram Language Models”.
- A. Karpathy, “The spelled-out intro to language modeling: building makemore” (video) — the source of the course’s bigram notebook.
Preview of Lecture 4 — Recurrent neural networks
The feed-forward LM’s window is a hard horizon: the 20-token dependency stayed at chance. A recurrent neural network removes the window. It reads the sequence one token at a time and carries a hidden state, a “memory”, from step to step, so in principle the prediction at step can depend on everything before it. We will train RNN language models on Errand World and see whether the long-distance probes finally move. Then we meet the practical obstacle, vanishing gradients, and its cure, gated architectures (GRU, LSTM). Finally we use RNNs for conditional generation: an encoder–decoder that translates English into Zorbian, and attention, which lets the decoder look back at every input word instead of a single summary vector.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| language model (LM) | 语言模型 |
| binary / multi-class / structured prediction | 二分类 / 多分类 / 结构化预测 |
| part-of-speech tag | 词性标签 |
| sequence / prefix / context | 序列 / 前缀 / 上下文 |
| scoring / generation / conditional generation | 打分 / 生成 / 条件生成 |
| autoregressive / chain rule / factorization | 自回归 / 链式法则 / 分解 |
| next-token prediction | 下一个词元预测 |
| bigram / n-gram | 二元语法 / n 元语法 |
| count / maximum likelihood estimation (MLE) | 计数 / 最大似然估计 |
| Lagrange multiplier | 拉格朗日乘子 |
| data distribution | 数据分布 |
| KL divergence / entropy / cross-entropy | KL 散度 / 熵 / 交叉熵 |
| log space / underflow | 对数空间 / 下溢 |
| sampling | 采样 |
| negative log-likelihood (NLL) / perplexity (PPL) | 负对数似然 / 困惑度 |
| nat / bit | 奈特 / 比特 |
| zero-count problem / smoothing | 零计数问题 / 平滑 |
| add-one (Laplace) / add-k smoothing | 加一(拉普拉斯)/ 加 k 平滑 |
| interpolation / backoff / Kneser–Ney | 插值 / 回退 / Kneser–Ney 平滑 |
| similar words / intervening words | 相似词 / 中间词 |
| long-distance dependency / agreement | 长距离依赖 / 一致性(呼应) |
| feed-forward neural language model | 前馈神经语言模型 |
| concatenation / hidden vector / logits | 拼接 / 隐藏向量 / 未归一化得分 |
| combination feature | 组合特征 |
| output embedding / weight tying | 输出嵌入 / 权重绑定 |
| teacher forcing | 教师强制 |
| horizon (of a fixed window) | (固定窗口的)视野上限 |
| generalization / memorization | 泛化 / 记忆 |
| training / validation (dev) / test split | 训练 / 验证(开发)/ 测试集划分 |
| hyperparameter / ablation | 超参数 / 消融实验 |
| overfitting / regularization / early stopping | 过拟合 / 正则化 / 早停 |
| initialization / Xavier (Glorot) initialization | 初始化 / Xavier(Glorot)初始化 |
| saturation / symmetry breaking | 饱和 / 打破对称性 |
| learning-rate schedule / cosine schedule / warmup | 学习率调度 / 余弦调度 / 预热 |
| batch / batch size | 批 / 批大小 |
| padding / pad token / mask | 填充 / 填充词元 / 掩码 |