Lecture 3: Language Modeling

How can one simple task — predicting the next word — carry us from counting word pairs in Alice in Wonderland to BERT, T5 and GPT? Watch the lecture in nine short chapters with English and Chinese subtitles, follow the lecture map below, then build and sample your own language models in Colab.

📅 Oct. 9th, 2026 🎥 chapters · min 🖼 slides 💬 EN + 中文 subtitles 🧭 Lecture map 💻 Colab notebooks ⬇ Slides (PDF)
Transcript follows the video · click a sentence to jump · Shift + ←/→ jumps between slides

1The lecture map

What is a language model — and how did one objective, predicting the next word, grow from counting n-grams into BERT, T5 and GPT?

Five acts, nine chapters. First why next-word prediction is so powerful, then the narrow sense: count n-grams and generate with them, fix and measure them with smoothing and perplexity. Then the broad sense: learn representations with neural LMs, word vectors, ELMo and BERT, and finally choose an architecture — encoder, encoder-decoder or decoder — and see why decoders took over. Click a chapter to watch it.

IWhy
What an LM is, and why next-word prediction teaches so much
IICount
Build an LM from probability and counts, then let it write
IIIFix & measure
Unseen events, smoothing, perplexity and WER
IVLearn
From counts to vectors, from static to contextual
VScale
Three architectures, and why the decoder won
Chapter by chapter what each chapter covers, and the question it leaves for the next
  1. IWhyWhat an LM is, and why next-word prediction teaches so much
  2. 1

    Language Models in a Nutshell, and Why They Matter

    A language model scores how likely a text is, or equivalently predicts the next word; a neural LM generates "我思故我在" one token at a time. Because the text is its own label, the task scales, and filling blanks forces the model to learn arithmetic, sentiment, coreference and world knowledge.

    → What exactly is "the probability of a sentence"?
  3. IICountBuild an LM from probability and counts, then let it write
  4. 2

    Probability Foundations: Distributions and the Chain Rule

    A bag of colored shapes, then the Alice passage as a bag of words: sampling, distributions, conditional probability, and the chain rule that turns a sentence probability into a product of next-word predictions.

    → The full history is too long to count — what can we assume instead?
  5. 3

    N-gram Language Models: Counting and Estimation

    The Markov assumption keeps only the last n−1 words. Unigram and bigram models for Alice, estimated by relative frequency (MLE), become proper language models once we add EOS, UNK and BOS.

    → What kind of text does such a model write?
  6. 4

    Generating Text: Spinning the N-gram Wheel

    Sampling is spinning a roulette wheel whose slices are the next-word probabilities. The bigram wheel writes "the book her sister was reading"; the trigram wheel has a single slice almost every time and mostly copies the passage.

    → Bigger n is more fluent — what does it cost?
  7. IIIFix & measureUnseen events, smoothing, perplexity and WER
  8. 5

    Sparsity, Smoothing and Evaluation: Perplexity and WER

    Large n copies the corpus, and 99.96% of possible Shakespeare bigrams never occur, so MLE gives most sentences probability zero. Smoothing moves mass to unseen events; perplexity (computed in log space) and word error rate tell us which model is better.

    → Counts cannot share statistics between similar words — can a neural network?
  9. IVLearnFrom counts to vectors, from static to contextual
  10. 6

    From N-grams to Neural LMs and Word Vectors

    N-grams suffer from sparsity and storage. The fixed-window neural LM (Bengio et al., 2003) embeds the context instead of counting it, and its embeddings lead to word vectors and word2vec; subword models handle words the vocabulary has never seen.

    → One vector per word — but which "bank"?
  11. 7

    Contextualized Word Vectors: ELMo and BERT

    ELMo reads with two LSTM language models; BERT uses a bidirectional Transformer trained with masked LM and next sentence prediction, then fine-tunes all weights. A three-step walk-through follows one example from data to inference.

    → How else can we pretrain — and which architecture scales?
  12. VScaleThree architectures, and why the decoder won
  13. 8

    Encoders, Encoder-Decoders and Their Trade-offs

    Encoder variants (RoBERTa, SpanBERT, ALBERT, ELECTRA) and encoder-decoders (T5's text-to-text span corruption, BART's denoising), then a side-by-side table of the three families — including the KV cache — and DeepSeek-V4.1-Flash's causal encoder-decoder.

    → Back to plain next-word prediction — at scale.
  14. 9

    Back to Next-Word Prediction: GPT, LLaMA and Beyond

    Pretrained decoders as classifiers and as generators, GPT-2's unicorn story, GPT-3's in-context learning and open LLaMA models — ending with the two questions every student should be able to answer.

2Try it in Colab

Three short notebooks turn the lecture into experiments. Click Open in Colab, then Runtime → Run all. Each ends with exercises. All three run on a free CPU runtime; no GPU is needed.

Notebook 1 · Chapters 3–5 · ~2 min

N-gram LMs: counting, sampling, smoothing, perplexity

  • Reproduce the Alice counts and replay the spin-the-wheel runs with the slides' random numbers
  • Generate Shakespeare with 1- to 4-grams and measure how much is copied
  • Watch MLE give most test lines probability zero
  • Compare add-k smoothing and interpolation by perplexity
Open in Colab .ipynb · CPU, pure Python
Notebook 2 · Chapter 6 · ~5–8 min

A fixed-window neural LM

  • Build Bengio et al.'s model in 15 lines of PyTorch
  • Train it on the same Shakespeare split and compare perplexity with a trigram model
  • Sample with different temperatures
  • Inspect the word embeddings it learned along the way
Open in Colab .ipynb · CPU (GPU optional)
Notebook 3 · Chapters 1, 7, 9 · ~5 min

Sampling from GPT-2, filling BERT's blanks

  • Score the monkey's string, real and shuffled text with GPT-2
  • Run the autoregressive loop by hand, with and without the KV cache
  • Sample with temperature, top-k and top-p
  • Fill [MASK] with DistilBERT and compare the vectors of "bank"
Open in Colab .ipynb · CPU or GPU · ~0.8 GB download

3Concept index

Key terms of the lecture. Each link opens the video at the slide where the idea is explained.

5Quotes & reading

"You shall know a word by the company it keeps."

J. R. Firth, A Synopsis of Linguistic Theory 1930–1955 (1957), quoted on slide 94
Distributional semantics: the idea behind word2vec and every embedding since.

"The fundamental problem of communication is that of reproducing at one point either exactly or approximately a message selected at another point."

Claude Shannon, A Mathematical Theory of Communication (1948)
Text as a choice among possible messages — the probabilistic view of language. The same paper already generated English from word n-gram approximations, as in Chapter 5.

"But it must be recognized that the notion of ‘probability of a sentence’ is an entirely useless one, under any known interpretation of this term."

Norvig reads it as: a sentence never seen before must get probability zero. Smoothing (slide 66) and neural LMs are the answer.

Further reading

6About this video

This is an AI-narrated version of the lecture. The slides are the ones used in class. The spoken script was written from the slides with AI assistance and is read in an AI clone of Prof. Benyou Wang's voice (MiniMax speech synthesis); the picture in the corner is a still photo. The red dot points at what is being discussed. When the narration and the slides disagree, trust the slides and the in-class lecture — and please tell us, so we can fix it.
CSC5051/CSC6052/MDS5110 Natural Language Processing · CUHK-Shenzhen · Fall 2026 · Back to the course page