38 / 90

Day 38: N-gram Language Models — Counts, Conditional Probability, and Smoothing

Fit a count-based bigram baseline on the deterministic training split: build the count table, normalize it into conditional probabilities, smooth unseen events, and score held-out text with likelihood and perplexity — every number hand-checkable.

Models & Training 480 active minutes (8 hours focused study)
01 120 min

Counting bigrams: from token stream to count table

Agent-Assisted Engineering Check

Prerequisites

Complete Day 37. If blocked, use the Day 35 recovery link for probability review.

Learning Objective

Turn a token stream into a bigram count table C(w_{i-1}, w_i), separate context totals from pair counts, and verify every count against a manual trace.

Instructions

A bigram is two consecutive tokens. Required work: slide a length-2 window over the stream 'the cat sat the cat ran the dog sat' (the three train lines joined into one 9-token stream, as the text_tools train file behaves) and tally each adjacent pair with Counter(zip(words, words[1:])). An empty string '' yields an empty bigram dictionary; Unicode strings like 'é猫' follow the identical pairing logic. Optional work: repeat on the val split and compare sparsity.

Practice & Prediction Log

Write the 8 adjacent pairs and the full count table before running any code. Then compute character-level bigrams of 'banana' the same way and record both tables.

Independent Mastery Criterion

Your hand-written table matches Counter(zip(words, words[1:])) output exactly, and you can explain why context totals — not unigram counts — are the correct denominators for the next step.

Authoritative Source Resources & Provenance

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: makemore.py part 1 bigrams: counting consecutive character pairs into a frequency table

Verified Version & Date: Verified 2026-10-30

Selection Rationale:

Standard minimal implementation of a count-based bigram language model on the same names.txt corpus family.

Source Prerequisites:

Basic Python and Day 37 token ids

Safe Fallback (Offline Resilience):

The lesson builds the full count table locally in pure Python with verified counts.

Compared Candidate Sources & Selection Analysis (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

Author: Daniel Jurafsky, James H. Martin | Original Source Link ↗

Relevant Section / Range: Sections 3.1-3.2: n-gram counts, Markov assumption, and maximum-likelihood estimation

Verified Version & Date: Draft of 2026-08-19 (Verified: 2026-10-30)

Selection Rationale:

Standard reference text defining n-gram models, count normalization, and the chain-rule decomposition used in this lesson.

Source Prerequisites:

Basic probability

Safe Fallback (Offline Resilience):

All definitions and worked count tables are included in the lesson itself.

Compared Candidate Sources & Selection Analysis (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

02 120 min

Maximum-likelihood conditional probabilities

Independent Mastery Check (no AI assistance)

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Normalize each context row into a probability distribution P(next|context) = C(context,next) / C(context) and verify every row sums to 1.

Instructions

Required work: for each context token, divide each outgoing pair count by that context's total. Compute the rows P(·|the), P(·|cat), and P(·|dog) by hand, then confirm each row sums to 1. Optional work: express the same normalization over a 'banana' character table.

Practice & Prediction Log

Compute P(cat|the), P(dog|the), P(sat|cat), P(ran|cat), P(sat|dog). Then score the continuation 'cat ran' after 'the' as a product, and predict whether any context row fails to sum to 1.

Independent Mastery Criterion

Unaided, you produce all five conditionals as exact fractions, verify each context row sums to 1, and compute the two-factor likelihood product correctly.

Authoritative Source Resources & Provenance

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

Author: Daniel Jurafsky, James H. Martin | Original Source Link ↗

Relevant Section / Range: Section 3.2: relative-frequency normalization P(w_n|w_{n-1}) = C(w_{n-1} w_n) / C(w_{n-1})

Verified Version & Date: Draft of 2026-08-19 (Verified: 2026-10-30)

Selection Rationale:

Normative definition of maximum-likelihood n-gram estimation used for the hand-computed probabilities in this activity.

Source Prerequisites:

Basic probability

Safe Fallback (Offline Resilience):

The lesson includes the complete worked normalization with verified fractions and decimals.

Compared Candidate Sources & Selection Analysis (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: makemore.py part 1: row-normalizing the count matrix into P[i] = N[i] / N[i].sum()

Verified Version & Date: Verified 2026-10-30

Selection Rationale:

Shows the same normalization implemented over a real character-level count matrix on names.txt.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

The local worked example normalizes a fully printed 3-context table by hand.

Compared Candidate Sources & Selection Analysis (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.

03 120 min

Add-k smoothing, likelihood, and perplexity

Agent-Assisted Engineering Check

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Explain why zero counts destroy likelihood, apply add-one smoothing P(next|context) = (C+1)/(context_total + V) with vocabulary size V, and convert a smoothed sentence score into per-token NLL and perplexity.

Instructions

The stream's vocabulary is V=5 ({the, cat, sat, ran, dog}). Required work: recompute the 'the' and 'cat' rows with add-one smoothing, then score the held-out continuation 'cat ran' after 'the': likelihood L is the product of the smoothed conditionals, per-token NLL = -ln(L)/N over N=2 predicted tokens, perplexity = exp(per-token NLL). Optional work: repeat with add-0.5 smoothing and compare.

Practice & Prediction Log

Compute the smoothed rows for contexts 'the' and 'cat', the smoothed likelihood of the continuation, its per-token NLL, and perplexity. Predict first: will the smoothed likelihood be higher or lower than the unsmoothed 1/3, and why?

Independent Mastery Criterion

You can produce the complete smoothed row, the 3/28 likelihood, the ≈1.117-nat per-token NLL, the ≈3.055 perplexity, and explain why evaluation uses only held-out text.

Authoritative Source Resources & Provenance

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

Author: Daniel Jurafsky, James H. Martin | Original Source Link ↗

Relevant Section / Range: Sections 3.3-3.4: Laplace (add-one) smoothing, evaluation, and perplexity

Verified Version & Date: Draft of 2026-08-19 (Verified: 2026-10-30)

Selection Rationale:

Standard treatment of smoothing zero counts and of perplexity as the inverse likelihood per token.

Source Prerequisites:

Basic probability and logarithms

Safe Fallback (Offline Resilience):

The lesson contains the complete smoothed probability table and perplexity computation.

Compared Candidate Sources & Selection Analysis (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Python systems programming

Safe Fallback (Offline Resilience):

The lesson evaluates the smoothed model on a declared held-out sentence with verified numbers.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

04 120 min

Independent mastery check: implement and verify a bigram baseline

Independent Mastery Check (no AI assistance)

Prerequisites

Complete the previous activities; use the listed recovery link if blocked.

Learning Objective

Unaided, implement bigram counting, hand-compute conditionals and a smoothed probability, diagnose a zero-likelihood failure, and state the held-out evaluation rule.

Instructions

Do not consult answers or AI during this check. Required work: (1) implement the bigram count for 'banana' characters in Python; (2) hand-compute P(n|a) and P(a|n); (3) compute an add-one smoothed probability for an unseen pair; (4) explain why the test split stays untouched. Optional work: extend the count to trigrams.

Practice & Prediction Log

(a) List the 'banana' character bigrams and their counts. (b) P(n|a)=? and P(a|n)=? (c) With V={a,b,n} (V=3), what is add-one smoothed P(b|a)? (d) If the unsmoothed model scores 'cat dog' at 0, what single count causes it and what does add-one assign instead?

Independent Mastery Criterion

The implementation prints the same counts as Counter, every probability is an exact fraction, and the write-up names smoothing plus the train-only fitting rule as the two fixes for zero likelihood.

Authoritative Source Resources & Provenance

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

Author: Daniel Jurafsky, James H. Martin | Original Source Link ↗

Relevant Section / Range: Sections 3.1-3.4 combined: counts, MLE, smoothing, and evaluation

Verified Version & Date: Draft of 2026-08-19 (Verified: 2026-10-30)

Selection Rationale:

Single primary source covering every formula assessed in the independent check.

Source Prerequisites:

Basic probability

Safe Fallback (Offline Resilience):

All assessed quantities were derived locally and verified by execution.

Compared Candidate Sources & Selection Analysis (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: makemore.py part 1: negative log-likelihood averaging nll/N as the loss of the count model

Verified Version & Date: Verified 2026-10-30

Selection Rationale:

Connects the hand-derived likelihood to the averaged negative log-likelihood used as a training loss.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

The mastery check reproduces the nll/N computation on a fully specified toy corpus.

Compared Candidate Sources & Selection Analysis (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.