Lecture 2 · Learned Representations: Subwords, Embeddings, Neural Networks and Backpropagation

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

课程源码 ZIP ↓

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

本篇目录

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

  1. 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.
  2. 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.
  3. 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.
  4. 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”).
  5. Distinguish what a model can represent from what it actually learns from data, using the negation measurements of this lecture.
  6. Derive binary and multi-class cross-entropy, relate cross-entropy to the KL divergence, and compute a gradient with the chain rule.
  7. Describe a neural network as a computation graph, run forward propagation and backpropagation on it, and say what a framework such as PyTorch automates.
  8. 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, g(x)∈{1,…,K}g(x) \in \{1, \dots, K\}. 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

SectionIdeaDemo in code/lecture02/
§2UTF-8 bytes; BPE; vocabulary size; languages and numbers01_tokenization.py (+ bpe.py)
§3.1–3.3embedding lookup; BoW vs CBoW; what vectors encode; subword units02_embeddings.py (+ nn_text.py)
§3.4vectors from unlabeled text; freeze vs fine-tune05_pretrained_vectors.py (+ word2vec.py)
§4linear collapse; the negation XOR; Deep CBoW; representable vs learned03_deep_cbow.py
§5–6losses, chain rule, gradient descent; computation graphs and backprop04_backprop.py (+ minigrad.py)

0.4 Notation

SymbolMeaning
x1,…,xTx_1, \dots, x_Tthe tokens of an input, each an id in a vocabulary V\mathcal{V} of size V=∣V∣V = \lvert\mathcal{V}\rvert
dembd_\text{emb} or ddembedding dimension
E∈RV×dE \in \mathbb{R}^{V \times d}embedding table; row E[xt]E[x_t] is token xtx_t‘s vector exte_{x_t}
h∈Rdh \in \mathbb{R}^da hidden representation (a feature vector computed by the network)
W,bW, bweights and biases of a layer; W(ℓ),b(ℓ)W^{(\ell)}, b^{(\ell)} for layer ℓ\ell
σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z})the sigmoid function
pθ(y∣x)p_\theta(y \mid x)model probability; L\mathcal{L} a loss; η\eta 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 wordsExampleCureWhere
conjugated or compound wordsI love this movie → I loved this moviesubword models§2
word similarityI love this movie → I adore this movieword embeddings§3
combination featuresI love this movie → I don’t love this movieneural networks§4
sentence structureIt has an interesting story, but is boring overallsequence modelsLectures 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 (词元) x1,…,xTx_1, \dots, x_T, each an element of a fixed vocabulary (词表) V\mathcal{V}. Tokenization (分词 / 词元化) is the map from raw text to that sequence. The same sentence can be tokenized at different granularities:

Units“the companies are expanding”
wordsthe · companies · are · expanding
subwordsthe · compan · _ies · are · expand · _ing
characterst · 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):

textcharactersUTF-8 bytesbytes per character
English “Hello! I loved this movie.”26261.00
French “un café très agréable”21241.14
Japanese 今日は良い天気ですね10303.00
Chinese 这部电影很好看7213.00
emoji 🎬🍿👍3124.00
Python code23231.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:

  1. Count every pair of adjacent tokens in the corpus.
  2. Take the most frequent pair (a,b)(a, b), add a new token abab to the vocabulary, and replace every occurrence of a ba\,b by abab.
  3. 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:

wordtokenssplit
” 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 VV trades sequence length against parameters (demo 01, Part C; embedding dimension 64):

requested VVlearned VVtokens per reviewtokens per wordbytes per tokenembedding parameters
256 (bytes)25651.94.351.0016,384
30030032.02.681.6219,200
40040022.21.862.3425,600
60060016.01.343.2538,400
1,0001,00012.71.064.0964,000
2,0001,27212.31.034.2281,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 d=4,096d = 4{,}096, 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. With byte_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 mixEnglish tokens/wordZorbian tokens/wordZorbian / English
Zorbian = 5%1.373.402.5×
Zorbian = 50%1.741.971.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 reviewsunitsdev accuracymorphology reviews
200words61.4%67.1%
200BPE subwords62.4%73.5%
2,000words76.8%92.9%
2,000BPE subwords77.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 xtx_t is a one-hot vector xt∈{0,1}Vx_t \in \{0, 1\}^V: 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 (稠密向量) ext∈Rdembe_{x_t} \in \mathbb{R}^{d_\text{emb}} with, say, demb=64d_\text{emb} = 64 or 512, whose numbers are learned: an embedding (嵌入).

The embedding layer is a matrix E∈RV×dE \in \mathbb{R}^{V \times d} with a row per vocabulary token. “Looking up” token ii means reading row ii, and that is mathematically identical to multiplying a one-hot vector by the matrix:

one_hot(i)⊤E=E[i,:].\text{one\_hot}(i)^\top E = E[i, :].

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 dd numbers instead of performing V×dV \times d 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:

h=∑t=1Text∈Rd,s(x)=Wh+b∈RK,p(y∣x)=softmax⁡(s(x)),h = \sum_{t=1}^{T} e_{x_t} \in \mathbb{R}^d, \qquad s(x) = W h + b \in \mathbb{R}^K, \qquad p(y \mid x) = \operatorname{softmax}(s(x)),

with parameters θ=(E,W,b)\theta = (E, W, b), W∈RK×dW \in \mathbb{R}^{K \times d}, b∈RKb \in \mathbb{R}^K. Compare Lecture 1’s BoW: there each word had KK weights of its own (one per class), and the score was their sum. CBoW gives each word dd numbers that are shared features, and a single matrix WW reads class scores off the summed features. BoW is the special case d=Kd = K, W=IW = I.

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

modelparametersdevnegationcontrast
BoW (Lecture 1’s model, in PyTorch)1,92678.4%1358
CBoW, d=2d = 21,29175.6%2254
CBoW, d=8d = 85,15578.6%1556
CBoW, d=64d = 6441,21978.3%1661

Linear CBoW does not beat the bag of words, and for 3 classes it does not even save parameters (V×dV \times d vs V×KV \times K). That is expected once you see the algebra: W∑text=∑tWextW \sum_t e_{x_t} = \sum_t W e_{x_t}, 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 VV 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 (d=16d = 16) actually learn? (demo 02 Part C)

The output layer tells positive from negative along the direction u=W+1−W−1u = W_{+1} - W_{-1}. Project each sentiment adjective’s vector on it (“polarity score” ew⋅ue_w \cdot u):

adjective tiermean training countpositive words: mean scorenegative words: mean scorecorrect sign
common38.5+1.29−1.1620/20
mid15.5+1.73−1.4727/28
rare2.6−0.13−1.3020/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 cc and each word oo within a window of ±2\pm 2 positions, the model should say “real pair”; for kk random “noise” words n1,…,nkn_1, \dots, n_k (drawn from the unigram distribution raised to the 0.75 power) it should say “fake pair”:

L(c,o)=−log⁡σ(vc⊤uo)−∑j=1klog⁡σ(−vc⊤unj).\mathcal{L}(c, o) = -\log \sigma(v_c^\top u_o) - \sum_{j=1}^{k} \log \sigma(-v_c^\top u_{n_j}).

vv are the “input” vectors (the embeddings we keep) and uu 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 vv.

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, heartfeltmawkish, awful, engaging, sharp, predictable
neighbours of rare “turgid”plodding, grating, interminable, pretentious, witlessvirtuosic, fun, buoyant, weak, sloppy
cos(great, dull)0.710.98
polarity from 3 + 3 seed words (good, great, fun / bad, boring, dull), all 78 adjectives78/78 (rare: 36/36)43/78 (coin flip)
cos(loved, hated)0.991.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:

labelledembeddingsdev accuracydecisive word unseen (111 reviews)
200random init, trained59.9%44.7%
200pretrained (with “A and B”), frozen66.2%60.7%
200pretrained (with), fine-tuned63.3%42.6%
200pretrained (without), frozen55.7%46.8%
2,000random init, trained84.6%—
2,000pretrained (with), frozen76.4%—
2,000pretrained (with), fine-tuned87.8%—

Four lessons, each of which reappears with large language models (Lectures 6–8):

  1. 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%.
  2. Only if the pretraining data contains the signal: vectors trained without informative contexts do not help (55.7% / 46.8%).
  3. 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.
  4. 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:

h(0)=∑text,h(ℓ)=tanh⁡ ⁣(W(ℓ)h(ℓ−1)+b(ℓ)),s(x)=Wh(L)+b.h^{(0)} = \sum_{t} e_{x_t}, \qquad h^{(\ell)} = \tanh\!\big(W^{(\ell)} h^{(\ell - 1)} + b^{(\ell)}\big), \qquad s(x) = W h^{(L)} + b.

Why the tanh? Without an activation function, stacking layers buys nothing: W2(W1h+b1)+b2=(W2W1)h+(W2b1+b2)W_2 (W_1 h + b_1) + b_2 = (W_2 W_1) h + (W_2 b_1 + b_2), a single linear map W′h+b′W' h + b'. Demo 03 Part A checks it: a “deep” CBoW with three linear layers produces the same scores as its collapsed matrix WoutW2W1W_\text{out} W_2 W_1 to within 4.8×10−74.8 \times 10^{-7} (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 σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) (range 0 to 1), tanh (range −1 to 1, zero-centred), ReLU max⁡(0,z)\max(0, z) (cheap, does not saturate for z>0z > 0), 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 tanh⁡(w⊤h+b)\tanh(w^\top h + b), 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:

modelseed 0seed 1seed 2seed 3seed 4
CBoW (linear), d=8d = 82/42/42/43/42/4
Deep CBoW, one tanh layer of 8 units4/44/44/44/44/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):

modeldevplainmorphnegationcontrasttwins both right
BoW78.4%829613580/125
CBoW d=64d = 6478.3%809716610/125
Deep CBoW, 1 tanh layer85.1%909458540/125
Deep CBoW, 2 tanh layers82.0%829067490/125
Deep CBoW, 1 ReLU layer82.5%859264490/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:

modelpair seen in training (68 reviews)pair never seen (23 reviews)
CBoW d=64d = 6416.2%17.4%
Deep CBoW, 1 tanh layer66.2%34.8%
Deep CBoW, 2 tanh layers75.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 xx as positive (y=1y = 1) or negative (y=0y = 0). The model outputs a probability for the positive class through a sigmoid layer, pθ(x)=σ(sθ(x))∈(0,1)p_\theta(x) = \sigma(s_\theta(x)) \in (0, 1), and the loss is binary cross-entropy (BCE):

LBCE(θ;x,y)=−ylog⁡pθ(x)−(1−y)log⁡(1−pθ(x)).\mathcal{L}_\text{BCE}(\theta; x, y) = -y \log p_\theta(x) - (1 - y) \log\big(1 - p_\theta(x)\big).

If y=1y = 1, only the first term remains, −log⁡pθ(x)-\log p_\theta(x). As pθ(x)→1p_\theta(x) \to 1 the loss → 0, and as pθ(x)→0p_\theta(x) \to 0 the loss → ∞: being confidently wrong is punished without bound.

5.2 Multi-class cross-entropy

For KK classes (positive / neutral / negative), the model outputs scores z∈RKz \in \mathbb{R}^K, turned into probabilities by the softmax, pi=exp⁡(zi)/∑jexp⁡(zj)p_i = \exp(z_i) / \sum_j \exp(z_j). The true label is written as a one-hot vector yy (e.g. [0,0,1][0, 0, 1]):

LCE=−∑i=1Kyilog⁡pi=−log⁡ptrue class.\mathcal{L}_\text{CE} = -\sum_{i=1}^{K} y_i \log p_i = -\log p_{\text{true class}}.

High probability on the correct class gives a small loss; low probability, a large one. BCE is the K=2K = 2 case. Demo 04 Part C checks that for p=0.3p = 0.3, y=1y = 1 both give 1.2040.

5.3 Where does cross-entropy come from?

Suppose we want the model distribution p2p_2 to match a target distribution p1p_1. A natural measure of mismatch is the Kullback–Leibler divergence (KL 散度):

KL(p1 ∥ p2)=∑xp1(x)log⁡p1(x)p2(x)=−∑xp1(x)log⁡p2(x)⏟cross-entropy H(p1,p2)−(−∑xp1(x)log⁡p1(x))⏟entropy H(p1).\mathrm{KL}(p_1 \,\|\, p_2) = \sum_x p_1(x) \log \frac{p_1(x)}{p_2(x)} = \underbrace{-\sum_x p_1(x) \log p_2(x)}_{\text{cross-entropy } H(p_1, p_2)} - \underbrace{\Big(-\sum_x p_1(x) \log p_1(x)\Big)}_{\text{entropy } H(p_1)}.

The entropy H(p1)H(p_1) does not depend on the model, so minimizing cross-entropy over p2p_2 is the same as minimizing KL. For a one-hot target, H(p1)=0H(p_1) = 0 and the two are equal. Measured with p2=[0.2,0.5,0.3]p_2 = [0.2, 0.5, 0.3] (demo 04 Part C): for target [0,0,1][0, 0, 1], H(p1,p2)=KL=1.2040=−log⁡0.3H(p_1, p_2) = \mathrm{KL} = 1.2040 = -\log 0.3. For a soft target [0.1,0.2,0.7][0.1, 0.2, 0.7], H(p1,p2)=1.1424H(p_1, p_2) = 1.1424, H(p1)=0.8018H(p_1) = 0.8018, KL=0.3405\mathrm{KL} = 0.3405: 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, z=wx+bz = w x + b, p=σ(z)p = \sigma(z), L=−ylog⁡p−(1−y)log⁡(1−p)\mathcal{L} = -y \log p - (1 - y) \log(1 - p), the chain rule splits the derivative into three local pieces:

∂L∂w=∂L∂p⋅∂p∂z⋅∂z∂w=p−yp(1−p)⋅p(1−p)⋅x=(p−y) x.\frac{\partial \mathcal{L}}{\partial w} = \frac{\partial \mathcal{L}}{\partial p} \cdot \frac{\partial p}{\partial z} \cdot \frac{\partial z}{\partial w} = \frac{p - y}{p(1 - p)} \cdot p(1 - p) \cdot x = (p - y)\, x.

The messy terms cancel, leaving “prediction minus truth, times the input”: the same form as Lecture 1’s softmax gradient (pk−1[k=y])f(x)(p_k - \mathbb{1}[k = y]) f(x). With w=0.8w = 0.8, b=−0.3b = -0.3, x=1.7x = 1.7, y=1y = 1 (demo 04 Part B): p=0.7427p = 0.7427, and the three factors −1.3465×0.1911×1.7-1.3465 \times 0.1911 \times 1.7 multiply to −0.4374=(p−y)x-0.4374 = (p - y)x. A finite-difference check, (L(w+h)−L(w−h))/2h(\mathcal{L}(w + h) - \mathcal{L}(w - h)) / 2h with h=10−6h = 10^{-6}, agrees to 6.6×10−116.6 \times 10^{-11}. Finite differences are the standard way to test a hand-written gradient.

5.5 Optimizing parameters: gradient descent

Stochastic gradient descent (SGD): at step tt, compute the gradient on a mini-batch, gt=∇θℓ(θt−1)g_t = \nabla_\theta \ell(\theta_{t-1}), and update θt=θt−1−η gt\theta_t = \theta_{t-1} - \eta\, g_t. The learning rate η\eta matters enormously (demo 04 Part E, a 2-8-1 tanh network, 300 full-batch steps):

learning ratestep 1step 10step 50step 150step 300
0.010.7130.7110.7030.6900.675
0.50.7130.6630.5780.4260.219
50.7130.5500.2180.1500.010
500.71370.85670.52159.18145.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 y=x⊤Ax+b⋅x+cy = x^\top A x + b \cdot x + c. As a graph:

  • a node is a value: a scalar, vector, matrix or tensor (xx, AA, bb, cc, and every intermediate result such as x⊤x^\top, x⊤Ax^\top A, x⊤Axx^\top A x, b⋅xb \cdot x);
  • an edge points from a function’s argument to the node computed from it;
  • each node computed by a function ff knows how to compute its value from its inputs and its local gradient ∂f(u)/∂u\partial f(u) / \partial u 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 x=(1.5,−2)x = (1.5, -2), A=(0.5−120.3)A = \begin{pmatrix} 0.5 & -1 \\ 2 & 0.3 \end{pmatrix}, b=(0.7,−0.4)b = (0.7, -0.4), c=1.2c = 1.2 (demo 04 Part A): x⊤Ax=−0.675x^\top A x = -0.675, b⋅x=1.85b \cdot x = 1.85, y=2.375y = 2.375. 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 ∂y/∂y=1\partial y / \partial y = 1. 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:

∂F∂u=∂F∂f(u)⋅∂f(u)∂u.\frac{\partial F}{\partial u} = \frac{\partial F}{\partial f(u)} \cdot \frac{\partial f(u)}{\partial u}.

When a value feeds several nodes (xx appears three times in x⊤Ax+b⋅xx^\top A x + b \cdot x), 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 — ∂y/∂x=(A+A⊤)x+b=(0.2,−0.1)\partial y / \partial x = (A + A^\top) x + b = (0.2, -0.1), ∂y/∂A=xx⊤\partial y / \partial A = x x^\top, ∂y/∂b=x\partial y / \partial b = x, ∂y/∂c=1\partial y / \partial c = 1 — and PyTorch’s to 2.2×10−162.2 \times 10^{-16}.

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 if and for can 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 2.5×10−92.5 \times 10^{-9} (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

  1. 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.
  2. 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.
  3. 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).
  4. 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).
  5. 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%).
  6. 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).
  7. Training = loss (BCE / cross-entropy, i.e. KL to the data up to a constant) + gradients (chain rule; logistic: (p−y)x(p - y)x) + updates (SGD; the learning rate matters: 50 explodes, 0.01 crawls).
  8. 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 in minigrad.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

  1. BPE by hand. Corpus (word: count): hug 10, pug 5, pun 12, bun 4, hugs 5. Starting from characters (ignore spaces), perform the first three merges. Then tokenize the unseen word bugs.

    AnswerPair 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`.
  2. The cost of a vocabulary. A model has d=4,096d = 4{,}096 and ties its input embedding and output layer (one V×dV \times d matrix). How many parameters does that matrix have for VV = 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?

    Answer131 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.
  3. Linear collapse. Show that a two-layer network without activations, s=W2(W1h+b1)+b2s = W_2 (W_1 h + b_1) + b_2, equals a one-layer network, and give W′W' and b′b'. 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$.
  4. An AND unit. Inputs are a,b∈{0,1}a, b \in \{0, 1\} (two words present or not). Choose wa,wb,cw_a, w_b, c so that tanh⁡(waa+wbb+c)\tanh(w_a a + w_b b + c) is close to +1+1 only when a=1a = 1 and b=0b = 0 (“great AND NOT not”), and close to −1-1 otherwise.

    AnswerFor 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).
  5. Sigmoid and BCE gradient. Prove σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)), and use it to show ∂LBCE/∂z=p−y\partial \mathcal{L}_\text{BCE} / \partial z = p - y.

    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$.
  6. KL vs cross-entropy. For target p1=[0.5,0.5]p_1 = [0.5, 0.5] and model p2=[0.9,0.1]p_2 = [0.9, 0.1], compute H(p1,p2)H(p_1, p_2), H(p1)H(p_1) and KL(p1∥p2)\mathrm{KL}(p_1 \| p_2) in nats. Which model p2p_2 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$.
  7. Backprop by hand. For f(a,b)=(a+b)⋅af(a, b) = (a + b) \cdot a at a=2a = 2, b=3b = 3, draw the graph, run forward and backward propagation, and verify ∂f/∂a=2a+b\partial f/\partial a = 2a + b.

    AnswerNodes: $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$ ✓.
  8. Why order is lost. Prove that for any function gg, a model of the form g(∑text)g\big(\sum_t e_{x_t}\big) 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 gg is?

    AnswerAddition 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.
  9. 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?

    AnswerWith 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.
  • 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 (109410^{94} terms). The fix is the autoregressive factorization P(X)=∏tP(xt∣x<t)P(X) = \prod_t P(x_t \mid x_{<t}), 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 / GELUS 型函数 / 双曲正切 / 修正线性单元 / 高斯误差线性单元
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动态执行 / 编译
← 返回课程目录