Skip to content
INDIE / MACHINE
CONCEPTLESSON 1 OF 65 MIN

What is an n-gram?

Bigrams, why counting them predicts the next word, and why N-Grammer uses latent bigrams instead of token bigrams.

STEP 1 / 5QUIZ 0 / 2
01 /

Language is full of local patterns

“New” is often followed by “York”. In Rust, “fn” is followed by a name and “impl” by a type.

An n-gram is a run of n consecutive tokens. A unigram is one token, a bigram is a pair, a trigram is three. Before neural networks, language models were mostly n-gram counts: look at the last token or two, and predict what usually came next.

Transformers can learn these patterns too, but they have to spend attention and layers on it. The N-Grammer idea is to hand the model a cheap, explicit memory for “what usually follows this”, and let the rest of the network work on harder things.

02 /

Count some bigrams

Every adjacent pair is one bigram. Counting them already gives you a next-word predictor.

INTERACTIVE / BIGRAM COUNTER
ALL BIGRAMS (12 DISTINCT)
  • the cat3
  • . the2
  • mat .2
  • on the2
  • sat on2
  • the mat2
  • cat ran1
  • cat sat1
  • dog sat1
  • ran to1
  • the dog1
  • to the1
AFTER “the” COMES…
  • cat50%
  • mat33%
  • dog17%
Edit the text. Every adjacent pair of words is one bigram. Click a word to see what tends to follow it - a bigram table is a tiny next-word predictor.
03 / CHECK YOURSELF

Quick check

In “the cat sat”, which pairs are the bigrams?

04 /

The problem with token bigrams

A table with one row per token pair grows with the square of the vocabulary. The Yumon model used throughout this course has 8,192 tokens:

8,192 × 8,192 = 67,108,864 possible bigrams
Most of those pairs never occur, and you would still need a vector for each one.

N-Grammer's trick is to build bigrams over something much smaller than the vocabulary. It clusters the model's own hidden vectors into a few hundred latent ids, and pairs those up instead. Similar tokens in similar contexts share ids, so they share table rows - and the table stays small enough to train.

05 / CHECK YOURSELF

Quick check

Why does N-Grammer pair up cluster ids instead of raw token ids?

LESSON 1 COMPLETE

Up next: The N-Grammer layer at a glance