Skip to content

3.8 Neural language models

ready≈ 11.5 hoursNeeds: 3.2, 2.4Unlocks: 4.1
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Character language model)
  4. 4 Do
  5. 5 Check

A language model assigns a probability to every sequence by the chain rule, p(x1,…,xT)=∏tp(xt∣x<t)p(x_1,\dots,x_T) = \prod_t p(x_t \mid x_{<t}), so all it has to do is predict the next symbol. Here the symbols are characters and the sequences are names. A boundary token ”.” marks both the start and the end, so the model also learns how names begin and when they stop. The score is the mean negative log likelihood per character, the cross-entropy from 2.4; its exponential, the perplexity, is the effective number of equally likely choices (Karpathy, makemore part 1).

The bigram model looks only at the previous character. Its maximum-likelihood estimate is a table of counts with each row normalised. A pair never seen in training gets probability zero and an infinite loss, so add a pseudo-count to every cell first. Adding one is Laplace smoothing; like the prior in module 2.4’s MAP estimate, it pulls rare estimates away from the extremes (Jurafsky & Martin, SLP3 §3.6).

The MLP model (Bengio et al. 2003) looks at the last few characters. Each one is looked up in an embedding table C\mathbf{C}, the vectors are concatenated, and a tanh hidden layer and a softmax produce the next-character distribution. The lookup is a matrix product with a one-hot vector, so backprop sends each row’s gradient back to the row of C\mathbf{C} it came from. A character that appears twice in a batch gets two contributions, and they must be added: np.add.at, not assignment (Karpathy, makemore part 2). Because similar characters end up with similar vectors, what the model learns about one transfers to the others. A table of counts cannot do that, and it grows exponentially with the context length, while the MLP’s parameters grow linearly.

Sampling draws a character from the predicted distribution, appends it, and repeats until the boundary comes out. Dividing the logits by a temperature below 1 sharpens the distribution; above 1 flattens it (Holtzman et al. 2020, §3).

Character language model

Learned character embeddings, bigram vs MLP, sampling

Static view on small screens. Open this page on a laptop to interact.

embeddings: vowels, y · consonants · • boundary 2.02.53.0uniform: log 27 = 3.30bigram counts: 2.45NLL/char: line train, dots validation
step 0 validation NLL NaN (perplexity NaN) bigram 2.45 (perplexity 11.6) parameters 2257

An MLP language model from module 3.8, trained here on 3,600 names with batch-32 SGD; its validation loss is measured on 250 other names every 500 steps. Each character has a learned 2-D vector, plotted on the left. Before training they are random. After a few thousand steps characters that behave alike move together; the vowels usually form their own group. With context length 1 the model can only learn bigram statistics, so it stops near the dashed bigram line. A longer context lets it go below. Low temperatures give common, repetitive names; high temperatures give strange ones.

Trains an MLP language model on 3,600 names in the browser. One plot shows the 2-D embedding vector of each of the 27 characters, coloured by vowel, consonant or boundary (a dot); the other shows the smoothed training loss, validation loss every 500 steps, and dashed lines for a uniform guess and for the bigram model. Controls set the context length, hidden size and learning rate; a temperature slider changes the sampled names listed below. Keyboard: Tab to the buttons and press Enter; arrow keys adjust the sliders.
Neural language models stubs/m3_8_char_lm.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m3_8_char_lm.py and run mlc check 3.8. The tests are identical; import the results on the progress page.

Hints · bigram_nll 0/3 revealed
Hints · mlp_lm_forward_backward 0/3 revealed

Then train on all 32,000 names (locally; downloads about 230 KB once):

Terminal window
cd exercises && python projects/makemore_names.py

It fits the bigram model, then trains the MLP with 10-dimensional embeddings and 200 hidden units for 30,000 steps (under a minute). The reference solution reaches a validation NLL of about 2.13, against 2.45 for bigrams, and samples names like briannan, dalyn and ammari. Part 4 replaces the fixed context window, first with recurrence and then with attention.

1. A model has mean NLL log 27 ≈ 3.30 per character on 27 symbols. What does that mean?
2. Why smooth the bigram counts?
3. In the embedding backward pass, the batch contains the character "a" in five positions. dC[a] should be…
4. Lowering the sampling temperature towards 0 makes samples…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.