Lecture 3 · Autoregressive Language Modeling: From Counting to Neural Networks

Advanced Natural Language Processing · Lecture 03。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 3 (01/20), slides anlp-s2026-03-lm.pdf; course demo code 03_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 from code/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:

  1. Place language modeling among prediction problems (binary, multi-class, structured) and say what a language model is: a probability distribution over all sequences.
  2. 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.
  3. Write the autoregressive factorization P(X)=∏tP(xt∣x<t)P(X) = \prod_t P(x_t \mid x_{<t}) and explain why it turns an impossible problem into many small ones.
  4. 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.
  5. Work in log space, generate by sampling, and evaluate with negative log-likelihood and perplexity, including what perplexity means and what its floor is.
  6. Explain smoothing, and the three problems of n-gram models: similar words, intervening words, long-distance dependencies.
  7. 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.
  8. 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

SectionIdeaDemo in code/lecture03/
§2, §4scoring sequences; bigrams by counting = MLE; log space; sampling; NLL and perplexity01_bigram_lm.py
§5a language with known probabilitieslm_world.py (run it for the language’s statistics)
§6n-grams: order, smoothing, zero counts, data size, the three problems02_ngrams.py (+ ngram.py)
§7the feed-forward neural LM: vs n-grams, the window horizon, shared strength, generation03_neural_lm.py (+ neural_lm.py, lmkit.py)
§8overfitting, initialization, schedules, batching, masking04_practical.py

0.4 Notation

SymbolMeaning
X=(x1,…,xT)X = (x_1, \dots, x_T)a sequence of tokens; x<t=(x1,…,xt−1)x_{<t} = (x_1, \dots, x_{t-1}) its prefix
V\mathcal{V}, ∣V∣\lvert\mathcal{V}\rvertthe token vocabulary and its size
V∗\mathcal{V}^*the set of all finite sequences over V\mathcal{V}
<s>, </s>start and end markers; every sentence ends with </s>
p∗p_* or pdatap_\text{data}the true data distribution; pθp_\theta the model
D={x(i)}i=1N\mathcal{D} = \{x^{(i)}\}_{i=1}^Na dataset of NN sequences (samples from p∗p_*)
NLL, PPLnegative log-likelihood; perplexity =exp⁡(average NLL per token)= \exp(\text{average NLL per token})

All logarithms are natural (results in nats); divide by ln⁡2\ln 2 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: 45445^4 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 50,00020≈109450{,}000^{20} \approx 10^{94} 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 P(X)P(X) over all sequences X∈V∗X \in \mathcal{V}^*.

The simplest distribution, for comparison, is a biased coin: P(X=0)=0.4P(X = 0) = 0.4, P(X=1)=0.6P(X = 1) = 0.6. Two outcomes, two numbers. A language model is the same object with one outcome for every possible sequence: P("a.")=0.000013P(\text{"a."}) = 0.000013, P("aa.")=0.000001P(\text{"aa."}) = 0.000001, …, P("a cat sat.")=0.0191P(\text{"a cat sat."}) = 0.0191, …. 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: P(Jane went to the store .)P(\text{Jane went to the store .}) high, P(store to Jane went the .)P(\text{store to Jane went the .}) 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 x^∼P(X)\hat x \sim P(X): a new text that looks like the training data.

Generate conditionally. Condition on a context and generate the continuation, x^t+1:T∼P(Xt+1:T∣x1:t)\hat x_{t+1:T} \sim P(X_{t+1:T} \mid x_{1:t}). 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

P(X)=∏t=1TP(xt∣x1,…,xt−1),P(X) = \prod_{t=1}^{T} P(x_t \mid x_1, \dots, x_{t-1}),

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. P(X)P(X) is defined over V∗\mathcal{V}^*, the space of all sequences, which is enormous. Each factor P(xt∣x<t)P(x_t \mid x_{<t}) is defined over V\mathcal{V}, 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 ∣V∣\lvert\mathcal{V}\rvert classes, the tool of Lectures 1–2, applied once per position.

The factorization itself is exact. The key modeling question is how to represent P(xt∣x1,…,xt−1)P(x_t \mid x_1, \dots, x_{t-1}), 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:

P(X)≈∏t=1Tpθ(xt∣xt−1).P(X) \approx \prod_{t=1}^{T} p_\theta(x_t \mid x_{t-1}).

The parameters are a table: θi,j=p(xt=j∣xt−1=i)\theta_{i,j} = p(x_t = j \mid x_{t-1} = i), one probability distribution over next tokens for every possible previous token.

4.2 Training: the problem set-up

Goal: model a data distribution, pθ≈pdatap_\theta \approx p_\text{data}. We only have samples: a dataset D={x(n)}n=1N\mathcal{D} = \{x^{(n)}\}_{n=1}^N drawn from pdatap_\text{data}, split into training, dev and test sets.

Training a bigram model sets each probability from counts in the training data:

p(xt∣xt−1)=count(xt−1,xt)∑x′count(xt−1,x′).p(x_t \mid x_{t-1}) = \frac{\text{count}(x_{t-1}, x_t)}{\sum_{x'} \text{count}(x_{t-1}, x')}.

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:

max⁡θ∑x∈Dtrainlog⁡pθ(x).\max_\theta \sum_{x \in \mathcal{D}_\text{train}} \log p_\theta(x).

Derivation (the slide’s exercise). For a fixed previous token ii, the log-likelihood contains ∑jcijlog⁡θij\sum_j c_{ij} \log \theta_{ij}, where cijc_{ij} counts the pair (i,j)(i, j), subject to ∑jθij=1\sum_j \theta_{ij} = 1. With a Lagrange multiplier λ\lambda: ∂/∂θij[∑jcijlog⁡θij−λ(∑jθij−1)]=cij/θij−λ=0\partial/\partial\theta_{ij}\big[\sum_j c_{ij}\log\theta_{ij} - \lambda(\sum_j \theta_{ij} - 1)\big] = c_{ij}/\theta_{ij} - \lambda = 0. So θij=cij/λ\theta_{ij} = c_{ij}/\lambda, and the constraint gives λ=∑jcij\lambda = \sum_j c_{ij}. 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 pθp_\theta match the data distribution. With p∗p_* the data distribution:

min⁡θDKL(p∗ ∥ pθ)=min⁡θ∑xp∗(x)log⁡p∗(x)pθ(x)=min⁡θ[−∑xp∗(x)log⁡pθ(x)+∑xp∗(x)log⁡p∗(x)⏟does not depend on θ]≡min⁡θ−Ex∼p∗[log⁡pθ(x)]  ≈  min⁡θ−1∣D∣∑x∈Dlog⁡pθ(x)  ≡  max⁡θ∑x∈Dlog⁡pθ(x).\begin{aligned} \min_\theta D_\text{KL}(p_* \,\|\, p_\theta) &= \min_\theta \sum_x p_*(x) \log \frac{p_*(x)}{p_\theta(x)} = \min_\theta \Big[ -\sum_x p_*(x) \log p_\theta(x) + \underbrace{\sum_x p_*(x) \log p_*(x)}_{\text{does not depend on } \theta} \Big] \\ &\equiv \min_\theta -\mathbb{E}_{x \sim p_*}\big[\log p_\theta(x)\big] \;\approx\; \min_\theta -\frac{1}{\lvert\mathcal{D}\rvert} \sum_{x \in \mathcal{D}} \log p_\theta(x) \;\equiv\; \max_\theta \sum_{x \in \mathcal{D}} \log p_\theta(x). \end{aligned}

The expectation over the unknown p∗p_* 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 10−10,05610^{-10{,}056}, far below the smallest positive float64 (≈10−308\approx 10^{-308}, or 4.9×10−3244.9 \times 10^{-324} with denormals). The fix is to work with log probabilities and add instead of multiply:

P(X)=∏iP(xi)⟺log⁡P(X)=∑ilog⁡P(xi).P(X) = \prod_i P(x_i) \quad\Longleftrightarrow\quad \log P(X) = \sum_i \log P(x_i).

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):

NLL=−∑i=1N∑t=1Tilog⁡p(xt(i)∣x<t(i))∈[0,∞),NLLavg=NLLTtotal,PPL=exp⁡(NLLavg)∈[1,∞).\text{NLL} = -\sum_{i=1}^{N} \sum_{t=1}^{T_i} \log p\big(x_t^{(i)} \mid x_{<t}^{(i)}\big) \in [0, \infty), \qquad \text{NLL}_\text{avg} = \frac{\text{NLL}}{T_\text{total}}, \qquad \text{PPL} = \exp\big(\text{NLL}_\text{avg}\big) \in [1, \infty).

TtotalT_\text{total} counts every predicted token, including </s>. Perplexity (困惑度) has a concrete meaning. A model that spreads its probability uniformly over kk tokens at every step has NLL log⁡k\log k per token and perplexity exactly kk. 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 e−log⁡p=1/p=28.4e^{-\log p} = 1/p = 28.4.

Measured (demo 01 Part E):

modeltest NLL per tokentest perplexity
uniform guess over 129 tokens4.860129
unigram (add-0.01)4.05657.76
bigram (add-0.01)1.0772.94
the true language (its entropy)0.7542.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:

typeexamplewhat 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 cross-entropy−entropy=DKL\text{cross-entropy} - \text{entropy} = D_\text{KL}, 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 n−1n - 1 tokens:

P(X)≈∏tpθ(xt∣xt−1,xt−2,…,xt−n+1),p(xt∣xt−n+1:t−1)=count(xt−n+1:t−1,xt)∑x′count(xt−n+1:t−1,x′).P(X) \approx \prod_t p_\theta(x_t \mid x_{t-1}, x_{t-2}, \dots, x_{t-n+1}), \qquad p(x_t \mid x_{t-n+1:t-1}) = \frac{\text{count}(x_{t-n+1:t-1}, x_t)}{\sum_{x'} \text{count}(x_{t-n+1:t-1}, x')}.

Contexts at the start of a sentence are padded with n−1n - 1 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:

p(xt∣xt−n+1:t−1)=k+count(xt−n+1:t−1,xt)k∣V∣+∑x′count(xt−n+1:t−1,x′).p(x_t \mid x_{t-n+1:t-1}) = \frac{k + \text{count}(x_{t-n+1:t-1}, x_t)}{k\lvert\mathcal{V}\rvert + \sum_{x'} \text{count}(x_{t-n+1:t-1}, x')}.

k=1k = 1 is add-one (Laplace) smoothing. kk is a hyperparameter, tuned on dev (demo 02 Part A, test NLL per token):

nk=1k = 1k=0.1k = 0.1k=0.01k = 0.01k=0.001k = 0.001train (best kk)
14.0564.0564.0564.0564.040
21.4481.1221.0771.0831.024
31.7221.1180.9940.9980.890
42.0771.2941.0871.0830.844
52.4441.5191.1891.1590.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 (λ3p3+λ2p2+λ1p1\lambda_3 p_3 + \lambda_2 p_2 + \lambda_1 p_1, 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 sentencesbigramtrigram4-gram5-grambestbest − entropy
5001.1371.1421.4071.734n = 20.383
2,0001.0700.9851.0781.164n = 30.231
20,0001.0410.9060.8990.871n = 50.117
100,0001.0410.8980.8850.850n = 50.096

(demo 02 Part C; kk 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):

modellong-distance, 8 back14 back20 backdr ‹rare name› ___agreement
3-gram, 2,000 sentences0.1420.1420.1420.4720.199
5-gram, 2,000 sentences0.1400.1400.1400.7460.598
3-gram, 100,000 sentences0.1390.1390.1390.9980.200
5-gram, 100,000 sentences0.1380.1380.1380.9980.600
true language1.0001.0001.0001.0001.000
  1. 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).
  2. 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.
  3. 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 n−1n - 1 tokens, but replaced the count table with a neural network:

P(X)≈∏tpθ(xt∣xt−1,…,xt−n+1),c=[ ext−n+1;… ;ext−1 ](look up and concatenate embeddings)h=tanh⁡(W1c+b1)(hidden vector)s=Wh+b∈R∣V∣(logits)pθ(xt∣⋅)=softmax⁡(s).P(X) \approx \prod_t p_\theta(x_t \mid x_{t-1}, \dots, x_{t-n+1}), \qquad \begin{aligned} c &= [\, e_{x_{t-n+1}}; \dots; e_{x_{t-1}} \,] && \text{(look up and concatenate embeddings)}\\ h &= \tanh(W_1 c + b_1) && \text{(hidden vector)}\\ s &= W h + b \in \mathbb{R}^{\lvert\mathcal{V}\rvert} && \text{(logits)}\\ p_\theta(x_t \mid \cdot) &= \operatorname{softmax}(s). \end{aligned}

Training is again maximum likelihood, max⁡θ∑x∈D∑tlog⁡pθ(xt∣x<t)\max_\theta \sum_{x \in \mathcal{D}} \sum_t \log p_\theta(x_t \mid x_{<t}), so the loss at each position is Lt=−log⁡pθ(xt∣x<t)L_t = -\log p_\theta(x_t \mid x_{<t}). That is exactly Lecture 2’s cross-entropy loss, with the one-hot “label” yy 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 sentencestrigram (tuned kk)neural, context 2trigram − floorneural − floor
5001.1390.9720.3850.218
2,0000.9940.9280.2400.174
20,0000.9070.9140.1530.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 tanh⁡(wk⊤c+bk)\tanh(w_k^\top c + b_k) over the concatenated context embeddings. Because each context position has its own slice of wkw_k, 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 hjh_j and hkh_k, the probability of the same next word ww (with output vector ww) under each is p(w∣hj)=exp⁡(w⊤hj)/Zjp(w \mid h_j) = \exp(w^\top h_j) / Z_j and p(w∣hk)=exp⁡(w⊤hk)/Zkp(w \mid h_k) = \exp(w^\top h_k)/Z_k, so

p(w∣hj)p(w∣hk)=ZkZjexp⁡(w⊤(hj−hk)).\frac{p(w \mid h_j)}{p(w \mid h_k)} = \frac{Z_k}{Z_j} \exp\big(w^\top (h_j - h_k)\big).

If hj≈hkh_j \approx h_k (e.g. “it’s a great” and “it is a wonderful”), every word gets almost the same probability in both contexts, and Zj≈ZkZ_j \approx Z_k 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 WW).

Measured (demo 03 Part C, window-4 model, 2,000 sentences):

wordnearest input embeddingsnearest output embeddings (rows of WW)
boughtgertrude, keyboard, smith, calledgot, rented, sold, purchased
purchasedpurchase, got, ball, hisgot, bought, rented, sold
gertrude (rare)bought, racquet, towel, smithwanda, yuki, pedro, hugo
drcar, omar, prof, jonasfor, ms, prof, mr
tenniswednesday, felix, my, tripodphotography, cooking, programming, painting
carbrown, ines, week, drmotorcycle, 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 W1W_1, 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 sentencestrigramneural, context 2
5000.1740.862
2,0000.4700.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?

problemn-gramfeed-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):

windowparameterstest NLLlong 8long 14long 20dr ‹name›agreement
229,4110.9280.130.130.130.980.20
437,6030.8910.140.140.140.990.60
853,9870.8640.960.140.140.991.00
1270,3710.8620.970.140.130.991.00
1686,7550.8470.980.970.130.991.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 (d×d \times 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):

modelvalid sentencesof which not in trainingmean true log P (valid ones)
trigram, 2,000 sentences41137−7.14
5-gram, 100,000 sentences633212−7.49
neural, window 4, 2,000 sentences54591−7.45
neural, window 16, 2,000 sentences906216−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 p∗p_*:

  • training data: samples from p∗p_*, used to fit pθp_\theta;
  • validation data: held-out samples from p∗p_* to check generalization. We try configurations (hyperparameters, ablations, model selection) and choose the one that generalizes best;
  • test data: held-out samples from p∗p_*, 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:

epoch124610204060
train loss2.5091.1280.8310.7970.7150.6720.6270.603
dev NLL1.4041.0660.9751.0081.0361.1241.2721.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):

W∼U ⁣(−6nin+nout,  6nin+nout),W \sim \mathcal{U}\!\left(-\sqrt{\frac{6}{n_\text{in} + n_\text{out}}},\; \sqrt{\frac{6}{n_\text{in} + n_\text{out}}}\right),

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):

initsaturated tanh units at initdistinct hidden valuesdev NLL at initafter 1 epochafter 10 epochs
PyTorch default0.0%1284.9581.1670.880
Xavier0.8%1285.0151.1390.883
N(0,1)\mathcal{N}(0, 1)82.9%5229.67913.5071.318
all zeros0.0%14.8754.7914.301
  • Too large (N(0,1)\mathcal{N}(0, 1) with 128 inputs): pre-activations have standard deviation ~11, so 83% of tanh units sit at ±1 where their gradient 1−tanh⁡2≈01 - \tanh^2 \approx 0. 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):

scheduleep 1ep 2ep 4ep 6ep 8ep 10
constant0.9830.9980.9610.9440.9540.945
cosine0.9810.9870.9340.8970.8840.879
warmup (32 steps) + cosine0.9920.9920.9430.9010.8830.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 BB examples instead of BB small ones) and averages out some of the noise in individual gradients. Five epochs over 2,000 sentences (demo 04 Part D):

batch sizeupdateswall time (varies)dev NLL
110,0001.9 s0.947
166250.4 s0.896
256400.3 s0.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

  1. 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.
  2. Autoregressive factorization: P(X)=∏tP(xt∣x<t)P(X) = \prod_t P(x_t \mid x_{<t}) is exact and turns sequence modeling into next-token classification over the vocabulary. The modeling question is how to represent P(xt∣x<t)P(x_t \mid x_{<t}).
  3. 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.
  4. 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.
  5. 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.
  6. 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).
  7. 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 kk 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); N(0,1)\mathcal{N}(0,1) 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

  1. MLE by hand. A training set contains the bigrams (a, b) ×3, (a, c) ×1, (b, a) ×2. Give the MLE bigram probabilities p(⋅∣a)p(\cdot \mid a) and p(⋅∣b)p(\cdot \mid b), then the add-1 smoothed ones with vocabulary {a, b, c} (ignore </s>).

    AnswerMLE: $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.
  2. Derive the MLE. Show with a Lagrange multiplier that maximizing ∑jcjlog⁡θj\sum_j c_j \log \theta_j subject to ∑jθj=1\sum_j \theta_j = 1 gives θj=cj/∑kck\theta_j = c_j / \sum_k c_k.

    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.
  3. 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?

    AnswerNLL $= -(\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$.
  4. 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?

    AnswerKL = 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.)
  5. 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, d=512d = 512, hidden width 2,048 have (ignore biases)?

    Answer5-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.
  6. 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?

    AnswerThe 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).
  7. Similar contexts. Using p(w∣hj)/p(w∣hk)=(Zk/Zj)exp⁡(w⊤(hj−hk))p(w \mid h_j)/p(w \mid h_k) = (Z_k/Z_j)\exp(w^\top(h_j - h_k)), show that if hj=hkh_j = h_k 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?

    AnswerIf $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.
  8. Initialization arithmetic. A hidden layer has nin=128n_\text{in} = 128 inputs with values of variance ~1. With weights from N(0,1)\mathcal{N}(0, 1), what is the standard deviation of a pre-activation? With Xavier uniform (nout=128n_\text{out} = 128)? Why does the first saturate tanh?

    AnswerVariance 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.
  • 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 tt 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-entropyKL 散度 / 熵 / 交叉熵
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填充 / 填充词元 / 掩码
← 返回课程目录