Maps to: CMU 11-711 Spring 2026, Lecture 2 (01/15), slides
anlp-s2026-02-representations.pdf; course demo code02_wordrep_classification/(BoW, CBoW and Deep CBoW sentiment classifiers). Readings: K. Cho, Natural Language Understanding with Distributed Representation (2015), ch. 2–3; additional: A. Karpathy, Let’s build the GPT Tokenizer (video, 2024). Sources: the public slides (adapted from Graham Neubig’s Fall 2024 course), the readings, and the papers cited in each section. §3.4 (word vectors pretrained on unlabeled text) goes slightly beyond the slides: it closes the loop on Lecture 1’s unseen-word problem and prepares Lecture 6. Every number labelled “measured” comes fromcode/lecture02/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, CPU, single thread). Code:code/lecture02/— every demo runs in under 20 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:
- Explain why a model needs a tokenizer, what makes a good vocabulary (expressive, efficient, neither too large nor too small), and run byte pair encoding (BPE) by hand.
- Predict two side effects of BPE — languages that are rare in the tokenizer’s training data get longer sequences, and numbers get split inconsistently — and the usual fixes.
- Describe an embedding layer (a lookup table equal to a one-hot × matrix product) and the continuous bag of words (CBoW) classifier, and say honestly what learned vectors do and do not represent.
- Explain why a neural network needs nonlinear activations, and what a hidden layer can express that a linear model cannot (combination features such as “not” AND “dull”).
- Distinguish what a model can represent from what it actually learns from data, using the negation measurements of this lecture.
- Derive binary and multi-class cross-entropy, relate cross-entropy to the KL divergence, and compute a gradient with the chain rule.
- Describe a neural network as a computation graph, run forward propagation and backpropagation on it, and say what a framework such as PyTorch automates.
- Explain the idea of pretraining word vectors on unlabeled text (skip-gram with negative sampling), when it helps a classifier with few labels, and when freezing or fine-tuning the vectors is the better choice.
0.2 Prerequisites and scope
- Prerequisites: Lecture 1 (the scoring-function recipe, bag of words, the perceptron, cross-entropy, the Cinema World dataset and its failure cases). Calculus at the level of the chain rule. A first look at PyTorch helps but is not required; every PyTorch idiom used in the code is explained in a comment.
- Scope: we still do classification, . The new ingredients are continuous representations of subwords, parameterization by neural networks, and learning by gradient descent with backpropagation. Every state-of-the-art NLP system is built from these.
- Not in scope: word order. Every model today still sums its token vectors, so word order is lost. Models that read sequences are Lectures 3–5.
0.3 Section → code map
| Section | Idea | Demo in code/lecture02/ |
|---|---|---|
| §2 | UTF-8 bytes; BPE; vocabulary size; languages and numbers | 01_tokenization.py (+ bpe.py) |
| §3.1–3.3 | embedding lookup; BoW vs CBoW; what vectors encode; subword units | 02_embeddings.py (+ nn_text.py) |
| §3.4 | vectors from unlabeled text; freeze vs fine-tune | 05_pretrained_vectors.py (+ word2vec.py) |
| §4 | linear collapse; the negation XOR; Deep CBoW; representable vs learned | 03_deep_cbow.py |
| §5–6 | losses, chain rule, gradient descent; computation graphs and backprop | 04_backprop.py (+ minigrad.py) |
0.4 Notation
| Symbol | Meaning |
|---|---|
| the tokens of an input, each an id in a vocabulary of size | |
| or | embedding dimension |
| embedding table; row is token ‘s vector | |
| a hidden representation (a feature vector computed by the network) | |
| weights and biases of a layer; for layer | |
| the sigmoid function | |
| model probability; a loss; the learning rate |
1. Where we are: four symptoms, four cures
Lecture 1 ended with a bag-of-words (BoW) classifier — “features: sum of one-hot vectors; weights: learned” — and a list of measured failures on Cinema World. The slides organise those failures into four symptoms, each paired with the part of the course that cures it:
| Symptom of bag of words | Example | Cure | Where |
|---|---|---|---|
| conjugated or compound words | I love this movie → I loved this movie | subword models | §2 |
| word similarity | I love this movie → I adore this movie | word embeddings | §3 |
| combination features | I love this movie → I don’t love this movie | neural networks | §4 |
| sentence structure | It has an interesting story, but is boring overall | sequence models | Lectures 3–5 |
Lecture 1 measured each symptom. Rare decisive words: 44% accuracy when the word was unseen in 200 training reviews. Negation: 9.9%, worse than chance. Contrast: the adjective-swapped twins got both right in 0 of 125 pairs. This lecture applies the first three cures and re-measures, and each section reports which numbers moved and which did not.
2. Tokenization and subword models
2.1 The core problem
Every model in this course reads a sequence of tokens (词元) , each an element of a fixed vocabulary (词表) . Tokenization (分词 / 词元化) is the map from raw text to that sequence. The same sentence can be tokenized at different granularities:
| Units | “the companies are expanding” |
|---|---|
| words | the · companies · are · expanding |
| subwords | the · compan · _ies · are · expand · _ing |
| characters | t · h · e · c · o · m · p · a · n · … |
What do we want from a vocabulary?
- Expressive: it should be able to represent any text — English, Japanese, code, LaTeX, emoji, typos.
- Efficient: neither too large nor too small. A larger vocabulary means more parameters to learn and store (an embedding row per token, and in a language model an output row per token). A smaller vocabulary means longer inputs, and every later model pays per token (attention even pays per pair of tokens, Lecture 5).
Words fail the first requirement: any word not in the vocabulary (a name, a typo, “stultifying”) becomes an out-of-vocabulary (未登录词) <unk>, and languages written without spaces (Chinese, Japanese) do not even have obvious words. Characters pass it, but make sequences long, and a single character carries little meaning. Subwords sit in between: common words stay whole, and less common words are split into a few frequent pieces. Then the pieces share parameters (the “-ing” of expanding is the “-ing” of exhilarating), and the vocabulary stays small.
2.2 Idea 1: UTF-8 bytes
Every string, in every script, is stored on a computer as a sequence of UTF-8 bytes (字节): integers from 0 to 255. So the 256 byte values form a vocabulary that can write anything: never an unknown token. How long are the sequences? (demo 01, Part A):
| text | characters | UTF-8 bytes | bytes per character |
|---|---|---|---|
| English “Hello! I loved this movie.” | 26 | 26 | 1.00 |
| French “un café très agréable” | 21 | 24 | 1.14 |
| Japanese 今日は良い天気ですね | 10 | 30 | 3.00 |
| Chinese 这部电影很好看 | 7 | 21 | 3.00 |
| emoji 🎬🍿👍 | 3 | 12 | 4.00 |
| Python code | 23 | 23 | 1.00 |
ASCII characters take one byte, accented Latin letters two, CJK characters three (“今” is bytes 228, 187, 138), emoji four. Bytes are expressive but inefficient: a byte-level model reads an English review as ~52 tokens instead of ~12 words (Part C below), and a Japanese text pays three tokens per character.
2.3 Idea 2: byte pair encoding (BPE)
Key idea: start from a base vocabulary (the 256 bytes) and a training corpus, and repeatedly merge the most frequent pair of adjacent tokens into a new token:
- Count every pair of adjacent tokens in the corpus.
- Take the most frequent pair , add a new token to the vocabulary, and replace every occurrence of by .
- Repeat until the vocabulary reaches the desired size.
Gage (1994) introduced BPE as a compression algorithm. Sennrich, Haddow & Birch (2016) applied it to words for machine translation, and GPT-2 (Radford et al., 2019) made it byte-level, as here.
A tiny example by hand. Corpus: low ×5, lower ×2, newest ×6, widest ×3 (counts of each word). Start from characters. The most frequent pair is e s (in newest and widest: 6 + 3 = 9 times), so merge it into es. The next most frequent pair is es t (9 again), giving est. Then l o (5 + 2 = 7) gives lo, then lo w gives low, and so on. After a few merges, newest is n e w est and lowest, a word never seen in training, splits into low est: two meaningful pieces, not unknown.
Encoding new text applies the learned merges in the order they were learned: in each chunk, repeatedly find the adjacent pair whose merge was learned earliest and merge it, until no learned pair remains. Decoding just concatenates the tokens’ bytes.
Why pre-tokenize? Practical tokenizers first cut text into chunks — a word with its leading space, a run of digits, a run of punctuation — and never merge across chunk boundaries. Otherwise frequent accidents of adjacency (“e” at the end of one word next to “t” at the start of the next) would waste vocabulary slots on tokens like “e t”. The leading space is kept inside the token: " movie" and "movie" are different tokens, which is how the model knows where words begin.
Measured (demo 01, Part B). Trained on the 2,000 Cinema World training reviews with a vocabulary of 512, the first merges are _ i, _ ., t h, th e, _ a, _i s, i n, _ s, _ f, _ the (_ marks a space). Space-attached function words come first, because they are the most frequent pairs in any English text. Then words:
| word | tokens | split |
|---|---|---|
| ” movie”, ” the” | 1 | _movie, _the |
| ” love” / ” loved” / ” loving” | 2 | _lo · ve, _lo · ved, _lo · ving |
| ” beautiful” | 5 | _b · ea · ut · i · ful |
| ” luminous” (rare) | 5 | _ · l · um · in · ous |
| ” stultifying” (rare) | 8 | _st · u · l · t · i · f · y · ing |
| ” zebra” (never seen) | 5 | _ · z · e · b · ra |
Frequent words are one token. The three forms of love share the piece _lo, which is exactly the parameter sharing that should help with conjugation. Rare and unseen words are spelled out in small pieces, never unknown. On dev text: 1.51 tokens per word, 2.89 bytes per token.
2.4 Choosing the vocabulary size
The vocabulary size trades sequence length against parameters (demo 01, Part C; embedding dimension 64):
| requested | learned | tokens per review | tokens per word | bytes per token | embedding parameters |
|---|---|---|---|---|---|
| 256 (bytes) | 256 | 51.9 | 4.35 | 1.00 | 16,384 |
| 300 | 300 | 32.0 | 2.68 | 1.62 | 19,200 |
| 400 | 400 | 22.2 | 1.86 | 2.34 | 25,600 |
| 600 | 600 | 16.0 | 1.34 | 3.25 | 38,400 |
| 1,000 | 1,000 | 12.7 | 1.06 | 4.09 | 64,000 |
| 2,000 | 1,272 | 12.3 | 1.03 | 4.22 | 81,408 |
The first few hundred merges shorten sequences dramatically (51.9 → 16.0 tokens per review with 344 merges). After that, returns diminish: Cinema World has only ~800 word types, and once every frequent chunk is a single token, BPE runs out of pairs that occur twice (it stops at 1,272). Real tokenizers face real text with millions of word types, which is why their vocabularies are tens of thousands of tokens: 50,257 for GPT-2, about 100,000 for GPT-4’s cl100k_base, 32,000 for LLaMA and LLaMA 2, 128,000 for LLaMA 3. For a model with , a 128k-token embedding table alone is over half a billion parameters.
2.5 Practical tools
- tiktoken (OpenAI): loads pre-existing vocabularies (GPT-2, GPT-4, …) and tokenizes and decodes fast. It does not train new vocabularies. The web demo https://tiktokenizer.vercel.app/ shows the tokens of any text.
- SentencePiece (Kudo & Richardson, 2018): trains tokenizers (BPE or the unigram LM method) directly on raw text, treating the space as an ordinary symbol (
▁). Its base vocabulary is Unicode characters, not bytes. Withbyte_fallback=True, a character missing from the vocabulary is spelled as its UTF-8 bytes instead of<unk>. LLaMA’s tokenizer is built this way.
2.6 Two side effects of BPE
Under-represented languages are merged less. Merges are chosen by frequency in the tokenizer’s training data, so a language that is rare in that data gets few merges and is cut into many short pieces. Demo 01 Part D trains a 600-token BPE on 2,000 English reviews plus Zorbian translations of the same kind of reviews. Zorbian is word-for-word, so tokens per word is a fair comparison:
| tokenizer training mix | English tokens/word | Zorbian tokens/word | Zorbian / English |
|---|---|---|---|
| Zorbian = 5% | 1.37 | 3.40 | 2.5× |
| Zorbian = 50% | 1.74 | 1.97 | 1.13× |
The same content costs 2.5 times as many tokens in the minority language. That means 2.5 times the compute, a shorter effective context window, and, for paid APIs, a higher price. Petrov et al. (2023) measured such disparities across real languages, up to an order of magnitude. The usual work-around, upsampling the under-represented language when training the tokenizer, works here (1.13×), but notice what it costs: English now needs 1.74 tokens per word instead of 1.37. A fixed vocabulary budget is shared between languages, and giving one more costs another.
Numbers are split inconsistently. With merging allowed, frequent digit strings become tokens: a year like 1958 becomes _195 · 8, but 125 becomes _12 · 5 and 923 stays _ · 9 · 2 · 3. Over all numbers 100–999 (demo 01 Part E), the split “shapes” are 1+1+1 for 871 of them, 2+1 for 15, 1+2 for 8, and 3 (a single token) for 6. The model therefore sees “the same” digit positions in different tokens depending on how common the number happened to be, which makes arithmetic needlessly hard. The common fix is a hand-defined pre-tokenization rule: never group digits, so every number is spelled digit by digit (LLaMA’s tokenizer does this). GPT-4’s tokenizer groups digits into chunks of at most three.
2.7 Do subwords help the classifier?
Demo 02 Part D trains the same CBoW classifier (§3.2) on whitespace words and on BPE-600 tokens:
| labelled reviews | units | dev accuracy | morphology reviews |
|---|---|---|---|
| 200 | words | 61.4% | 67.1% |
| 200 | BPE subwords | 62.4% | 73.5% |
| 2,000 | words | 76.8% | 92.9% |
| 2,000 | BPE subwords | 77.3% | 95.5% |
The gain is where the slide said it would be — word forms (+6.4 points at 200 labels) — and small overall. Shared pieces like _lo let “loving” borrow what “loved” learned. They do nothing for rare words: “luminous” splits into pieces (l · um · in · ous) that carry no sentiment. That needs a different cure.
3. Continuous word embeddings
3.1 From one-hot to dense vectors
In a bag of words, token is a one-hot vector : all zeros except a 1 at the token’s id. Two different words are always orthogonal, so “great” and “brilliant” are exactly as unrelated as “great” and “dull”. The alternative is to represent each token by a dense vector (稠密向量) with, say, or 512, whose numbers are learned: an embedding (嵌入).
The embedding layer is a matrix with a row per vocabulary token. “Looking up” token means reading row , and that is mathematically identical to multiplying a one-hot vector by the matrix:
Demo 02 Part A checks this exactly (for “great”, id 66, in a vocabulary of 641): the product and the lookup give the same four numbers. The lookup simply reads numbers instead of performing multiplications. In PyTorch this is nn.Embedding.
3.2 The continuous bag of words (CBoW)
The CBoW classifier sums the token embeddings and applies a linear layer:
with parameters , , . Compare Lecture 1’s BoW: there each word had weights of its own (one per class), and the score was their sum. CBoW gives each word numbers that are shared features, and a single matrix reads class scores off the summed features. BoW is the special case , .
Why sum? It keeps the bag-of-words property (order is ignored), so any difference from Lecture 1 is due to the representation, not to order. (Averaging is the other common choice; it makes long and short texts comparable.)
Measured (demo 02 Part B; 2,000 training reviews, 15 epochs of Adam):
| model | parameters | dev | negation | contrast |
|---|---|---|---|---|
| BoW (Lecture 1’s model, in PyTorch) | 1,926 | 78.4% | 13 | 58 |
| CBoW, | 1,291 | 75.6% | 22 | 54 |
| CBoW, | 5,155 | 78.6% | 15 | 56 |
| CBoW, | 41,219 | 78.3% | 16 | 61 |
Linear CBoW does not beat the bag of words, and for 3 classes it does not even save parameters ( vs ). That is expected once you see the algebra: , so a linear CBoW is still a sum of per-word class scores, just factored. Its value appears elsewhere: (1) when the output space is large — a language model must score all next tokens, and dense vectors are what make that tractable (Lecture 3); (2) when nonlinear layers are stacked on top (§4); (3) when the vectors come pretrained on far more text than the labelled set (§3.4).
3.3 What do our vectors represent?
The slide’s honest answer: no guarantees, but we hope that similar words are close in vector space and that each dimension behaves like a feature. What did the CBoW () actually learn? (demo 02 Part C)
The output layer tells positive from negative along the direction . Project each sentiment adjective’s vector on it (“polarity score” ):
| adjective tier | mean training count | positive words: mean score | negative words: mean score | correct sign |
|---|---|---|---|---|
| common | 38.5 | +1.29 | −1.16 | 20/20 |
| mid | 15.5 | +1.73 | −1.47 | 27/28 |
| rare | 2.6 | −0.13 | −1.30 | 20/36 |
Frequent words are perfectly organised by polarity; rare words, seen about 2.6 times, are barely better than a coin. A supervised embedding is only as good as the labels that touched it. Nearest neighbours by cosine similarity (among frequent words) tell the same story. “great” → charming, what, penny, new, town, funny; “dull” → friday, awkward, of, shallow, lena, beautiful. Some neighbours are polarity-consistent, many are noise (function words, names, even the opposite polarity). With 2,000 labelled reviews as the only signal, “similar words are close” is a hope, not a fact.
3.4 Where do good vectors come from? Learning from unlabeled text
Labels are expensive; raw text is nearly free. The distributional hypothesis (分布假说) — “you shall know a word by the company it keeps” (Firth, 1957) — suggests learning vectors from raw text alone: give two words similar vectors if they appear in similar contexts.
Skip-gram with negative sampling (SGNS) (Mikolov et al., 2013, “word2vec”) turns this into a prediction game. For each center word and each word within a window of positions, the model should say “real pair”; for random “noise” words (drawn from the unigram distribution raised to the 0.75 power) it should say “fake pair”:
are the “input” vectors (the embeddings we keep) and the “output” vectors. The yes/no formulation avoids a softmax over the whole vocabulary for every pair. Words that predict the same neighbours end up with similar .
The catch: vectors capture only what the contexts reveal. In Cinema World’s templates, “the plot is dull .” and “the plot is great .” share every context word, so skip-gram makes dull and great near-identical. This is the well-known antonym problem of distributional vectors. Real reviews contain an extra signal: people stack adjectives of the same polarity (“dull and lifeless”, “witty and moving”). Hatzivassiloglou & McKeown (1997) used exactly such “X and Y” conjunctions to infer adjective polarity. Demo 05 trains SGNS on 20,000 unlabeled reviews, once with such “the X is A and B .” sentences added to half of the opinionated reviews and once without:
| measured (demo 05) | with “A and B” | without |
|---|---|---|
| neighbours of rare “luminous” | lyrical, engaging, powerful, charming, heartfelt | mawkish, awful, engaging, sharp, predictable |
| neighbours of rare “turgid” | plodding, grating, interminable, pretentious, witless | virtuosic, fun, buoyant, weak, sloppy |
| cos(great, dull) | 0.71 | 0.98 |
| polarity from 3 + 3 seed words (good, great, fun / bad, boring, dull), all 78 adjectives | 78/78 (rare: 36/36) | 43/78 (coin flip) |
| cos(loved, hated) | 0.99 | 1.00 |
With informative contexts, every adjective — including the 36 rare ones a supervised model barely saw — lands on the correct side; without them, polarity is invisible. The last row is the same lesson in miniature: verbs never appear in “A and B” sentences, so loved and hated stay at cosine 0.99 even in the good corpus. (Nouns cluster as nouns — “film” → acting, direction, editing — and genres as genres in both corpora: those contexts are distinctive.)
Do pretrained vectors help a classifier with few labels? Demo 05 Part C trains a Deep CBoW (§4) on 200 labelled reviews, with the embedding table initialised randomly or from the SGNS vectors. Each setting is run with 3 seeds; the “unseen” column counts the plain and morphology reviews whose decisive word does not occur in the 200 labelled ones:
| labelled | embeddings | dev accuracy | decisive word unseen (111 reviews) |
|---|---|---|---|
| 200 | random init, trained | 59.9% | 44.7% |
| 200 | pretrained (with “A and B”), frozen | 66.2% | 60.7% |
| 200 | pretrained (with), fine-tuned | 63.3% | 42.6% |
| 200 | pretrained (without), frozen | 55.7% | 46.8% |
| 2,000 | random init, trained | 84.6% | — |
| 2,000 | pretrained (with), frozen | 76.4% | — |
| 2,000 | pretrained (with), fine-tuned | 87.8% | — |
Four lessons, each of which reappears with large language models (Lectures 6–8):
- Pretraining transfers knowledge to words the labels never touched: with 200 labels, frozen pretrained vectors raise accuracy on unseen-word reviews from 44.7% to 60.7%.
- Only if the pretraining data contains the signal: vectors trained without informative contexts do not help (55.7% / 46.8%).
- Fine-tuning can undo the transfer. Updating the vectors on 200 labels moves the seen words to fit the labels, while the unseen words stay where pretraining put them, so the two no longer line up (42.6%). Kumar et al. (2022) analyse this “feature distortion” for fine-tuning in general.
- With enough labels the trade-off flips: at 2,000 labels frozen vectors are clearly worse (76.4%, they cannot adapt to the task) and fine-tuned pretrained vectors are best (87.8%). Freeze when labels are scarce; fine-tune when they are plentiful.
(One practical detail mattered. Raw SGNS vectors share a large common component, and a review is a sum of ~12 of them, so the polarity direction drowned. In a first attempt, a linear classifier on raw frozen vectors could not even fit its own 200 training reviews. Centering the vectors and fixing their length (prepared() in demo 05) fixed it. Representations need to be usable by the model on top, not just informative.)
4. Neural network features
4.1 Motivation: combination features
The slide’s examples: “I don’t love this movie” (negative) and “There’s nothing I don’t love about this movie” (very positive). The meaning comes from combinations: “don’t” AND “love”, “nothing” AND “don’t” AND “love”. Lecture 1 proved that a linear bag of words cannot represent the simplest such combination. For great (+), dull (−), not great (−), not dull (+), the four conditions on the weights contradict each other. Lecture 1 fixed it by hand with a feature for the pair not|dull. Can a model learn combination features?
4.2 Deep CBoW and the role of nonlinearity
Deep CBoW passes the summed embedding through hidden layers before the output layer:
Why the tanh? Without an activation function, stacking layers buys nothing: , a single linear map . Demo 03 Part A checks it: a “deep” CBoW with three linear layers produces the same scores as its collapsed matrix to within (floating-point rounding), and scores 77.1%, no better than plain CBoW. A nonlinearity between the layers is what lets the network represent functions that are not linear in its input.
Common activation functions (激活函数). sigmoid (range 0 to 1), tanh (range −1 to 1, zero-centred), ReLU (cheap, does not saturate for ), and smooth relatives such as GELU and SiLU (Lecture 5). The slides use tanh; demo 03 also tries ReLU.
What a hidden unit can compute. A unit computes , a soft threshold on a weighted sum of its inputs. With a suitable bias it can fire only when two inputs are both present (AND), or when one is present and another absent: exactly a combination feature. Theory goes much further: a single hidden layer with enough units can approximate any continuous function on a bounded domain (the universal approximation theorem; Cybenko, 1989; Hornik, 1991). The theorem says nothing about how many units are needed, or whether gradient descent will find them.
4.3 Measured: the negation XOR and Cinema World
The four sentences (demo 03 Part B), trained for 300 epochs from 5 random initializations:
| model | seed 0 | seed 1 | seed 2 | seed 3 | seed 4 |
|---|---|---|---|---|---|
| CBoW (linear), | 2/4 | 2/4 | 2/4 | 3/4 | 2/4 |
| Deep CBoW, one tanh layer of 8 units | 4/4 | 4/4 | 4/4 | 4/4 | 4/4 |
The linear model never exceeds 3 of 4, as Lecture 1 proved it cannot. One tanh layer solves the XOR every time.
Cinema World (demo 03 Part C; 2,000 training reviews):
| model | dev | plain | morph | negation | contrast | twins both right |
|---|---|---|---|---|---|---|
| BoW | 78.4% | 82 | 96 | 13 | 58 | 0/125 |
| CBoW | 78.3% | 80 | 97 | 16 | 61 | 0/125 |
| Deep CBoW, 1 tanh layer | 85.1% | 90 | 94 | 58 | 54 | 0/125 |
| Deep CBoW, 2 tanh layers | 82.0% | 82 | 90 | 67 | 49 | 0/125 |
| Deep CBoW, 1 ReLU layer | 82.5% | 85 | 92 | 64 | 49 | 0/125 |
Negation jumps from 16% to 58–67%, and overall accuracy rises to 85.1%: combination features are being learned. But the last column does not move. For the adjective-swapped twins of Lecture 1 (“the acting is great, but the plot is dull” vs “…dull, but … great”), every model gives both twins the same label, because summing the embeddings destroys word order before any layer can see it. No amount of depth on top of a sum can recover order. That is the fourth symptom, and its cure is sequence models (Lectures 3–5).
4.4 Representable is not the same as learned
Part B showed that one hidden layer can represent negation. Did it learn the rule “negation flips polarity”, or did it memorise particular combinations? Demo 03 Part D splits the dev negation reviews by whether their exact (negator, word) pair — (“not”, “dull”), (“n’t”, “charming”), … — ever occurred in a training review:
| model | pair seen in training (68 reviews) | pair never seen (23 reviews) |
|---|---|---|
| CBoW | 16.2% | 17.4% |
| Deep CBoW, 1 tanh layer | 66.2% | 34.8% |
| Deep CBoW, 2 tanh layers | 75.0% | 43.5% |
The gain is concentrated on combinations the model has seen; on new combinations it is far weaker. The probe “the plot is not great .” (“not great” occurs in 0 training reviews) is labelled positive. Looking inside, the hidden units with the strongest “interaction” scores are AND-type units: unit 50 fires (+0.99) for “great” and is off (−0.99/−1.00) for “dull”, “not great” and “not dull”, i.e. “great AND NOT not”. That is a useful combination feature, but it is tied to one adjective. It is not a general negation operator.
This distinction — between what an architecture can represent and what training on finite data actually learns — runs through the whole course. It is the root of questions about compositional generalization (组合泛化), data coverage, and why scale and data diversity matter so much (Lectures 6–7).
5. Training neural network models
The recipe for every model in the course: (1) write down a loss function; (2) compute the gradient of the loss with respect to every parameter; (3) move the parameters a small step in the direction that reduces the loss.
5.1 Binary cross-entropy
Example task: classify a tweet as positive () or negative (). The model outputs a probability for the positive class through a sigmoid layer, , and the loss is binary cross-entropy (BCE):
If , only the first term remains, . As the loss → 0, and as the loss → ∞: being confidently wrong is punished without bound.
5.2 Multi-class cross-entropy
For classes (positive / neutral / negative), the model outputs scores , turned into probabilities by the softmax, . The true label is written as a one-hot vector (e.g. ):
High probability on the correct class gives a small loss; low probability, a large one. BCE is the case. Demo 04 Part C checks that for , both give 1.2040.
5.3 Where does cross-entropy come from?
Suppose we want the model distribution to match a target distribution . A natural measure of mismatch is the Kullback–Leibler divergence (KL 散度):
The entropy does not depend on the model, so minimizing cross-entropy over is the same as minimizing KL. For a one-hot target, and the two are equal. Measured with (demo 04 Part C): for target , . For a soft target , , , : they differ by exactly the constant. Lecture 3 makes the same argument for language models, where the target is the data distribution itself.
5.4 Calculating gradients: the chain rule
For logistic regression, , , , the chain rule splits the derivative into three local pieces:
The messy terms cancel, leaving “prediction minus truth, times the input”: the same form as Lecture 1’s softmax gradient . With , , , (demo 04 Part B): , and the three factors multiply to . A finite-difference check, with , agrees to . Finite differences are the standard way to test a hand-written gradient.
5.5 Optimizing parameters: gradient descent
Stochastic gradient descent (SGD): at step , compute the gradient on a mini-batch, , and update . The learning rate matters enormously (demo 04 Part E, a 2-8-1 tanh network, 300 full-batch steps):
| learning rate | step 1 | step 10 | step 50 | step 150 | step 300 |
|---|---|---|---|---|---|
| 0.01 | 0.713 | 0.711 | 0.703 | 0.690 | 0.675 |
| 0.5 | 0.713 | 0.663 | 0.578 | 0.426 | 0.219 |
| 5 | 0.713 | 0.550 | 0.218 | 0.150 | 0.010 |
| 50 | 0.713 | 70.856 | 70.521 | 59.181 | 45.952 |
Too small: almost no progress. Too large: the first step overshoots so far that the loss explodes to 70.9. There are many other optimizers that adapt the step per parameter (momentum, RMSProp, Adam). The demos use Adam, and Lecture 5 derives it.
5.6 In code
PyTorch packages the loss (nn.CrossEntropyLoss, which takes raw scores and applies log-softmax internally), the optimizer, and automatic gradients. Every training loop in this course has the same five lines (from nn_text.train):
logits = model(ids) # forward: compute scores
loss = loss_fn(logits, y) # compute loss
opt.zero_grad() # clear gradients from the previous step
loss.backward() # compute gradients (backpropagation, §6)
opt.step() # update parameters
6. What is a neural net? Computation graphs
6.1 “Neural” nets
The name comes from a loose analogy with neurons in the brain (a unit sums weighted inputs and “fires”). The modern, more useful view is less romantic: a neural network is a computation graph (计算图), a composition of simple differentiable functions.
6.2 Computation graphs
Take the slide’s expression . As a graph:
- a node is a value: a scalar, vector, matrix or tensor (, , , , and every intermediate result such as , , , );
- an edge points from a function’s argument to the node computed from it;
- each node computed by a function knows how to compute its value from its inputs and its local gradient with respect to each input;
- functions can take any number of arguments (most are unary or binary), and the graph is directed and acyclic (DAG). Variable names are just labels on nodes.
6.3 Forward propagation
Forward propagation (前向传播): visit nodes in topological order (every node after all of its inputs) and compute each value from its inputs. With , , , (demo 04 Part A): , , . Built from scalar operations, as in our engine, the graph has 23 nodes: 9 inputs/parameters and 14 intermediate results.
6.4 Backpropagation
Backpropagation (反向传播): visit nodes in reverse topological order, starting from the output with . Each node multiplies the gradient arriving from above (the “incoming gradient”) by its own local gradient and passes the result to each of its inputs:
When a value feeds several nodes ( appears three times in ), the gradients arriving along the different paths add up. Reverse order guarantees that a node’s gradient is complete before it is passed on. Finally, the parameter update moves each parameter against its gradient: W -= lr * dL/dW.
Demo 04 Part A runs this with minigrad.py, a 200-line engine in which every scalar is a Value that records its inputs and a small _backward function. Its gradients match the calculus — , , , — and PyTorch’s to .
Why does this work so well? Backpropagation computes the gradient with respect to all parameters at roughly the cost of one extra forward pass, whatever their number. That is what makes training a billion-parameter model feasible: computing each partial derivative separately would cost one forward pass per parameter.
6.5 Neural network frameworks
The basic process in every framework: create a model; for each example (or batch), build a graph that represents the computation, compute its result, and, if training, run backpropagation and update.
- PyTorch (Meta): the most widely used in NLP; favours dynamic execution: the graph is built anew as the Python code runs (“define by run”). Very flexible: ordinary Python
ifandforcan change the graph per example. - JAX / TensorFlow (Google): favour definition then compilation: trace the computation once, compile it, run it many times. Conceptually simple parallelization across devices.
Is a framework doing anything more than our 200-line engine? Demo 04 Part D trains the same 2-8-1 tanh network on 40 points, from identical initial weights, with minigrad and with PyTorch (float64). The losses agree at every one of 200 steps, to (the two compute the logistic loss with algebraically equal but numerically different formulas). The difference is speed: minigrad creates one Python object per scalar and takes about 2.4 s, while PyTorch operates on whole tensors in optimized C++ and takes about 0.015 s. Same mathematics, ~150× faster on this tiny network (the exact ratio varies run to run), and the gap grows with model size.
7. Summary
- Four symptoms, four cures: subwords for word forms, embeddings for similarity, neural networks for combinations, sequence models for structure. This lecture applied the first three.
- Tokenization maps text to ids from a vocabulary that should be expressive and efficient. UTF-8 bytes can write anything but give long sequences. BPE repeatedly merges the most frequent adjacent pair, making frequent words single tokens and spelling rare ones in pieces (Cinema World: 1.51 tokens per word). Vocabulary size trades sequence length against parameters.
- BPE side effects: languages rare in the tokenizer’s data pay more tokens for the same content (2.5× at 5% share; upsampling helps but costs other languages), and numbers split inconsistently (fix: one token per digit).
- An embedding layer is a lookup equal to one-hot × matrix. A linear CBoW is still a sum of per-word scores (78.3% vs BoW 78.4%). Supervised vectors organise frequent words well and rare words barely (20/36).
- Pretrained vectors from unlabeled text (skip-gram) capture whatever the contexts reveal (78/78 adjective polarities with informative contexts, 43/78 without). With few labels, frozen pretrained vectors help unseen words (44.7% → 60.7%). With many labels, fine-tuning them is best (87.8%).
- Nonlinearity is what makes depth useful (linear layers collapse to one matrix). One tanh layer solves the negation XOR (4/4 in 5/5 seeds) and lifts Cinema World negation from 16% to 58–67%, but the gains concentrate on seen combinations (66–75% vs 35–43%): representable ≠ learned. Summing embeddings still destroys order (twins: 0/125).
- Training = loss (BCE / cross-entropy, i.e. KL to the data up to a constant) + gradients (chain rule; logistic: ) + updates (SGD; the learning rate matters: 50 explodes, 0.01 crawls).
- A neural network is a computation graph. Forward propagation computes values in topological order; backpropagation computes all gradients in one reverse pass. Frameworks automate exactly this, over tensors.
Common pitfalls
- Assuming learned vectors mean what you hope. Supervised embeddings put “dull” next to “friday”; distributional ones put “loved” next to “hated” (0.99). Check what your training signal actually rewards.
- Comparing tokenizers by bytes per token across languages. Use tokens per word (or per character of the same content); Zorbian’s longer words made it look better than English by bytes per token.
- Stacking linear layers and calling it deep. Without activations it is one matrix (77.1%, no better than one layer).
- Reading a high average as a learned rule. 58% on negation hid 66% on seen pairs vs 35% on unseen ones. Split your evaluation by what the model could have memorised.
- Forgetting
optimizer.zero_grad(). Gradients accumulate (+=) in PyTorch, exactly as inminigrad.backward. Without zeroing, each step uses the sum of all previous gradients. - Fine-tuning pretrained vectors on tiny data by default. With 200 labels it erased the transfer to unseen words (60.7% → 42.6%).
- Trusting a hand-written gradient without a finite-difference check. It costs two extra forward passes and catches most bugs.
Exercises
-
BPE by hand. Corpus (word: count):
hug10,pug5,pun12,bun4,hugs5. Starting from characters (ignore spaces), perform the first three merges. Then tokenize the unseen wordbugs.Answer
Pair counts: u g = 10 + 5 + 5 = 20, u n = 12 + 4 = 16, h u = 15, p u = 17, g s = 5, b u = 4. Merge 1: `u g` → `ug` (20). Now words: h ug, p ug, p u n, b u n, h ug s. Counts: u n = 16, h ug = 15, p ug = 5, p u = 12, ug s = 5, b u = 4. Merge 2: `u n` → `un` (16). Then: h ug = 15, p un = 12, p ug = 5, b un = 4, ug s = 5. Merge 3: `h ug` → `hug` (15). `bugs`: start b u g s; apply merges in learned order: `u g` → b ug s; `u n` does not apply; `h ug` does not apply → tokens `b · ug · s`. -
The cost of a vocabulary. A model has and ties its input embedding and output layer (one matrix). How many parameters does that matrix have for = 32,000, 128,000 and 256 (bytes)? If moving from 32k to 128k tokens shortens text by 15%, what else changes for the rest of the model?
Answer
131 M, 524 M and 1.05 M parameters. The rest of the network processes 15% fewer tokens for the same text: proportionally less compute per document, and a context window that holds ~18% more text (1/0.85). For attention, whose cost grows with the square of length (Lecture 5), the saving is larger still. The trade-off is memory and the softmax over 128k outputs at every position. -
Linear collapse. Show that a two-layer network without activations, , equals a one-layer network, and give and . Why does inserting tanh break the argument?
Answer
$s = (W_2 W_1) h + (W_2 b_1 + b_2)$, so $W' = W_2 W_1$, $b' = W_2 b_1 + b_2$. With $\tanh$, $W_2 \tanh(W_1 h + b_1)$ is not linear in $h$ ($\tanh(a + b) \ne \tanh a + \tanh b$), so no single matrix reproduces it for all $h$. -
An AND unit. Inputs are (two words present or not). Choose so that is close to only when and (“great AND NOT not”), and close to otherwise.
Answer
For example $w_a = 4$, $w_b = -8$, $c = -2$: (1,0) → tanh(2) = 0.96; (0,0) → tanh(−2) = −0.96; (1,1) → tanh(−6) ≈ −1; (0,1) → tanh(−10) ≈ −1. This is the kind of unit demo 03 found (unit 50). -
Sigmoid and BCE gradient. Prove , and use it to show .
Answer
$\sigma(z) = (1 + e^{-z})^{-1}$, so $\sigma'(z) = e^{-z}(1 + e^{-z})^{-2} = \sigma(z) \cdot \frac{e^{-z}}{1 + e^{-z}} = \sigma(z)(1 - \sigma(z))$. Then $\partial\mathcal{L}/\partial z = \left(-\frac{y}{p} + \frac{1-y}{1-p}\right) p(1-p) = -y(1-p) + (1-y)p = p - y$. -
KL vs cross-entropy. For target and model , compute , and in nats. Which model minimizes each?
Answer
$H(p_1, p_2) = -0.5 \ln 0.9 - 0.5 \ln 0.1 = 0.0527 + 1.1513 = 1.2040$; $H(p_1) = \ln 2 = 0.6931$; KL = 0.5108. Both are minimized by $p_2 = p_1$ (KL = 0, cross-entropy = $H(p_1)$ = 0.6931): they differ by a constant that does not depend on $p_2$. -
Backprop by hand. For at , , draw the graph, run forward and backward propagation, and verify .
Answer
Nodes: $s = a + b = 5$, $f = s \cdot a = 10$. Backward: $\partial f/\partial f = 1$; $\partial f/\partial s = a = 2$; $\partial f/\partial a$ (direct path through the product) $= s = 5$; $\partial f/\partial a$ via $s$: $2 \cdot 1 = 2$; total $= 7 = 2 \cdot 2 + 3$ ✓ (paths add). $\partial f/\partial b = 2 \cdot 1 = 2 = a$ ✓. -
Why order is lost. Prove that for any function , a model of the form assigns the same output to any two token sequences that are permutations of each other. What does that imply for the twins of demo 03, whatever is?
Answer
Addition is commutative, so the sum — and hence $g$ of it — is identical for any reordering. The adjective-swapped twins are permutations of each other with opposite labels, so at most one of each pair can be right: the 0/125 "both right" is guaranteed for every Deep CBoW, not an accident of training. -
Freeze or fine-tune? Using demo 05’s table, explain why fine-tuning pretrained vectors hurt unseen-word accuracy with 200 labels but gave the best dev accuracy with 2,000. What would you try with 200 labels to get the best of both?
Answer
With 200 labels, gradients only touch the words in those reviews; their vectors move to fit the labels while unseen words keep their pretrained positions, so the classifier's decision boundary (fit to the moved vectors) no longer applies to them. With 2,000 labels almost every word is touched, so adapting all vectors to the task wins. With few labels: freeze the embeddings and train only the layers on top (as in the table), or train the top layers first and then fine-tune everything with a small learning rate (the "linear probe, then fine-tune" recipe of Kumar et al., 2022), or regularize the vectors toward their pretrained values.
Related assignment (concepts only)
- Assignment 1 — Build your own LLaMa. Three pieces of this lecture are inside every LLaMa-style model: a subword tokenizer with digit splitting and byte fallback (§2), an embedding table as the first layer (§3), and training by backpropagation with cross-entropy (§5–6). These notes do not provide assignment code.
Further reading
- K. Cho, Natural Language Understanding with Distributed Representation, arXiv:1511.07916, ch. 2–3 — function approximation, neural networks, backpropagation (course reading).
- A. Karpathy, “Let’s build the GPT Tokenizer” (video, 2024) — byte-level BPE built from scratch (course reference); and his “micrograd”, the model for
minigrad.py. - R. Sennrich, B. Haddow, A. Birch, “Neural Machine Translation of Rare Words with Subword Units”, ACL 2016 — BPE for NLP.
- T. Kudo, J. Richardson, “SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing”, EMNLP 2018 (demo).
- A. Petrov, E. La Malfa, P. Torr, A. Bibi, “Language Model Tokenizers Introduce Unfairness Between Languages”, NeurIPS 2023.
- T. Mikolov, I. Sutskever, K. Chen, G. Corrado, J. Dean, “Distributed Representations of Words and Phrases and their Compositionality”, NeurIPS 2013 — skip-gram with negative sampling.
- V. Hatzivassiloglou, K. McKeown, “Predicting the Semantic Orientation of Adjectives”, ACL 1997 — polarity from “and”/“but” conjunctions.
- M. Iyyer, V. Manjunatha, J. Boyd-Graber, H. Daumé III, “Deep Unordered Composition Rivals Syntactic Methods for Text Classification”, ACL 2015 — the deep averaging network, a Deep CBoW.
- A. Kumar, A. Raghunathan, R. Jones, T. Ma, P. Liang, “Fine-Tuning can Distort Pretrained Features and Underperform Out-of-Distribution”, ICLR 2022.
- D. E. Rumelhart, G. E. Hinton, R. J. Williams, “Learning representations by back-propagating errors”, Nature 323, 1986.
Preview of Lecture 3 — Autoregressive language modeling
So far every model classified: a handful of labels. Next we model sequences themselves: a language model is a probability distribution over all token sequences. Lecture 1 showed that a softmax over whole sentences is hopeless ( terms). The fix is the autoregressive factorization , which reduces sequence modeling to repeated next-token classification over the vocabulary, the tool of this lecture. We start with counting (bigram and n-gram models, maximum likelihood, smoothing), measure them with log-likelihood and perplexity, and then build Bengio et al.’s feed-forward neural language model, where today’s embeddings and hidden layers let similar words and similar contexts share strength. To measure how close each model gets to the truth, we will use a toy language whose true sentence probabilities are known exactly.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| representation / learned representation | 表示 / 学习得到的表示 |
| token / tokenization / tokenizer | 词元 / 分词(词元化) / 分词器 |
| vocabulary / vocabulary size | 词表 / 词表大小 |
| out-of-vocabulary (OOV) / unknown token | 未登录词 / 未知词元 |
| subword / subword model | 子词 / 子词模型 |
| character / byte / UTF-8 | 字符 / 字节 / UTF-8 编码 |
| byte pair encoding (BPE) / merge | 字节对编码 / 合并 |
| pre-tokenization / chunk | 预切分 / 片段 |
| byte fallback | 字节回退 |
| compression ratio | 压缩率 |
| upsampling | 上采样 |
| one-hot vector / dense vector | 独热向量 / 稠密向量 |
| embedding / embedding layer / embedding dimension | 嵌入 / 嵌入层 / 嵌入维度 |
| lookup | 查表 |
| continuous bag of words (CBoW) / Deep CBoW | 连续词袋 / 深层连续词袋 |
| cosine similarity / nearest neighbour | 余弦相似度 / 最近邻 |
| distributional hypothesis | 分布假说 |
| skip-gram / negative sampling / context window | 跳字模型 / 负采样 / 上下文窗口 |
| antonym | 反义词 |
| pretrained / frozen / fine-tuned | 预训练的 / 冻结的 / 微调的 |
| feature distortion | 特征扭曲 |
| neural network / hidden layer / hidden unit | 神经网络 / 隐藏层 / 隐藏单元 |
| activation function / nonlinearity | 激活函数 / 非线性 |
| sigmoid / tanh / ReLU / GELU | S 型函数 / 双曲正切 / 修正线性单元 / 高斯误差线性单元 |
| combination feature / interaction | 组合特征 / 交互 |
| universal approximation theorem | 万能逼近定理 |
| compositional generalization | 组合泛化 |
| memorization | 记忆 |
| binary cross-entropy (BCE) / cross-entropy | 二元交叉熵 / 交叉熵 |
| entropy / KL divergence | 熵 / KL 散度 |
| chain rule / local gradient | 链式法则 / 局部梯度 |
| finite difference | 有限差分 |
| gradient descent / stochastic gradient descent (SGD) | 梯度下降 / 随机梯度下降 |
| learning rate / optimizer / Adam | 学习率 / 优化器 / Adam 优化器 |
| mini-batch / padding | 小批量 / 填充 |
| computation graph / node / edge | 计算图 / 节点 / 边 |
| directed acyclic graph (DAG) / topological order | 有向无环图 / 拓扑序 |
| forward propagation / backpropagation | 前向传播 / 反向传播 |
| automatic differentiation | 自动微分 |
| dynamic execution / compilation | 动态执行 / 编译 |