Overview & Tokenization

A language model reads integers, not letters. Bytes make every sentence long; whole words cannot spell a word they never saw. Byte-pair encoding learns 209 merges from a 1,194-byte story and cuts a new 44-byte sentence to 19 tokens, with no unknown words.

Pick a tokenizer and read the sentence it makes. Then choose BPE and drag the merges from 0 to 209. Then we build each tokenizer from zero, watch three of them fail, and grow the fourth one merge at a time.

You need a little Python and a list of integers. We build the rest from zero.

Lecture 1 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Next: Lecture 2, PyTorch and Resource Accounting.

Tokenize a sentence four ways

209 merges

Illustrative toy, computed live in your browser. We trained the BPE and the word list on a 1,194-byte children's story written for this lesson (Chapter 9 has it), with GPT-2's pre-tokenizer. The sentence is not in the story. After 209 merges every story word is one token, so more merges change nothing.

Chapter 0

Why Build a Language Model From Scratch

Climb down the abstraction ladder, and find the first place where efficiency is won or lost

Eight years ago, researchers trained their own models. Six years ago, they downloaded one, such as BERT, and fine-tuned it. Today, most of them prompt a closed model. Each step up the ladder raises productivity. CS336 starts from one problem with that climb: these abstractions leak.

A programming language almost never leaks; you rarely need the machine code. A prompt that works at one model size and breaks at another does leak. The cause sits several rungs down. So the course rebuilds the stack by hand: tokenizer, Transformer, optimizer, kernels, data and alignment. Its motto is understanding via building.

A class cannot train a frontier model. The course models stay under 1 billion parameters, and more is different. The share of compute spent in attention changes with size, and some abilities appear only at scale. So the lecture sorts what transfers. Mechanics (how a Transformer works) and mindset (squeeze the hardware, take scale seriously) transfer. Intuitions about which choices help transfer only in part.

The course reads the "bitter lesson" this way: algorithms that scale are what matter. Its slogan is accuracy = efficiency × resources. At large scale you cannot afford waste, so efficiency matters more, not less. Hernandez and Brown measured a 44-fold gain in algorithmic efficiency on ImageNet from 2012 to 2019. The lecture's question: given a Common Crawl dump and 32 H100 GPUs for two weeks, what is the best model you can build?

UnitWhat it buildsThe waste it fights
Basicstokenizer, Transformer, training loop (Lecture 3)a pipeline that does not run end to end
Systemskernels, parallelism, inference (Lecture 5)idle GPUs and needless data movement
Scaling lawssmall runs that predict big ones (Lecture 9)tuning at full size
Dataextract, filter, deduplicate (Lecture 14)updates spent on bad or repeated text
AlignmentSFT, then learning from feedback (Lecture 15)a bigger base model than the task needs

Tokenization is the first stage, and it is an efficiency decision. A model works on a fixed number of positions, one token each. The more text one token carries, the more text the same compute reads.

Fill the same window three ways

The yellow frame is a window of positions, one token each. Choose a tokenizer and see how much of the paragraph fits. Then widen the window.

32 positions

Illustrative. The paragraph (282 bytes) is not in the story that trained the Story BPE. GPT-2's tokens come from OpenAI's tiktoken "gpt2" encoding; we stored them in the page.

With 32 positions, bytes hold 32 bytes of text, our story BPE holds 84, and GPT-2 holds 116. Same compute, 3.6 times the text. That ratio is the first number this lesson teaches you to measure.

Symptom: a choice that helped a 100M-parameter model hurts at 10B parameters.

Measure: run the same comparison at two or more sizes before you trust it.

Fix: trust mechanics and mindset; hold small-scale intuitions loosely, and use scaling laws to predict what changes with size.

The road

  1. Two functions: a tokenizer is encode and decode, scored by its compression ratio.
  2. Characters: one token per code point needs a huge vocabulary.
  3. Bytes: 256 entries, but the longest sequences.
  4. Words: short sequences, and unknown words.
  5. Merges: BPE fuses the most frequent pair, again and again.
  6. Encoding: replay the merges, in order, on new text.
  7. Pre-tokens: cut text into word pieces before you merge.
  8. Vocab size: more entries, shorter sequences, bigger tables.
  9. Showcase: train BPE one merge at a time on your own text.
  10. Field guide: the table, the code and the checks.
The slogan is "accuracy = efficiency × resources". Why does it make efficiency matter more at large scale?

Chapter 1

A Tokenizer Is Two Functions

Turn a string into integers and back, and score how much text each integer carries

A neural network multiplies numbers. It reads a list of integers and looks each one up in a table of vectors, the embedding matrix. So before any model runs, something must turn the string into integers. That something is a tokenizer: a pair of functions, encode and decode.

python
class Tokenizer:
    def encode(self, string: str) -> list[int]: ...
    def decode(self, indices: list[int]) -> str: ...

Each integer is a token. The vocabulary size is how many different tokens there can be. One rule never bends: decode(encode(s)) must give back s exactly, for every string. If the round trip loses something, the model never had it.

The device runs GPT-2's real tokenizer. Three habits show at once. A word takes the space before it, so "hello" and " hello" are different tokens. Numbers break into chunks of a few digits. An emoji can split into pieces that are not characters at all.

Run GPT-2's tokenizer

Each chip is one token, with its id below. ␣ is a space. A chip in hex is a piece of a character. Pick a string, then decode one token at a time.

Real GPT-2 tokens: we ran tiktoken's "gpt2" encoding on each string and stored the ids and bytes in this page.

How do we score a tokenizer? Count the string's UTF-8 bytes; call that B. Count the tokens encode returns; call that T. The compression ratio r is:

Say it aloud

r equals B divided by T.

r
r the compression ratio: how many bytes of text one token carries, on average. Higher is better.
B
B the number of bytes in the string, in UTF-8.
T
T the number of tokens the tokenizer returns for that string.
In plain words

Encode the string to bytes and count them: that is B. Run the tokenizer and count the tokens: that is T. Divide B by T to get r.

With numbers

From the device: "Hello, 🌍! 你好!" is B = 20 bytes, and GPT-2 returns T = 12 tokens. So r = 20 / 12 = 1.67. "the quick brown fox" is B = 19 and T = 4, so r = 4.75. Plain English packs far more text per token.

Symptom: a chat app streams "�" for a moment where an emoji should be.

Measure: decode each token alone. GPT-2 splits 🌍 into three tokens, and none of them is a whole character.

Fix: join the bytes of all tokens so far and decode only complete UTF-8 characters; hold back the last few bytes until they finish one.

A tokenizer turns a 40-byte string into 10 tokens. What is its compression ratio, and is higher better?

Chapter 2

Characters: A Vocabulary Too Big

Give every Unicode character its own token, and pay for a table that is mostly empty

The first idea is the most literal. A Python string is a list of Unicode characters, and each character has an integer, its code point. ord("a") is 97 and ord("🌍") is 127,757. chr goes back. So encode is list(map(ord, s)) and decode is "".join(map(chr, ids)).

The round trip is perfect, because ord and chr are exact inverses. The problem is the vocabulary. Unicode assigns about 150,000 characters (Python's Unicode 15.1 tables list 149,878, not counting private use). The model needs one embedding row for each, and one output score for each.

Place each character on the code-point line

Top: each character and its code point. Bottom: the vocabulary as a line from 0 to 150,000, with a tick for every code point the string uses. Pick a string.

Code points from JavaScript's codePointAt, the same numbers as Python's ord. The 150,000 line is the lecture's round figure for the number of Unicode characters.

"Hello, 🌍! 你好!" has 13 characters and 10 different ones. Its largest code point is 127,757, so a table indexed by code point needs at least 127,758 rows to hold it. The string uses 10 of them. "the cat in the hat" uses 8 rows, all below 128.

Most of the table is rare. Little text holds 🌍, but its row costs as much memory as the row for "e". A row the model rarely sees, it rarely trains. That is the lecture's second problem: an inefficient use of the vocabulary.

Symptom: the model writes rare characters badly or never, though they are in the vocabulary.

Measure: count how often each code point occurs in the training text; most rows get a handful of updates.

Fix: do not give rare characters their own rows. Write them as smaller, shared pieces: the bytes of the next chapter.

Why is a character tokenizer's vocabulary of about 150,000 entries a problem?

Chapter 3

Bytes: A Sequence Too Long

Shrink the vocabulary to 256, and pay for it in sequence length, squared

Go to the smallest alphabet there is. UTF-8 writes every character as 1 to 4 bytes, each an integer from 0 to 255. ASCII letters take 1 byte; "你" takes 3; "🌍" takes 4: 240, 159, 140, 141. Encode is list(s.encode("utf-8")) and decode is bytes(ids).decode("utf-8").

The vocabulary is exactly 256. It covers every language and every emoji, and no string is ever unknown. So why not stop here? Because the number of tokens now equals the number of bytes, by definition. T = B, so r = 1: no compression at all.

Explode characters into bytes, then price attention

Top: each character and the UTF-8 bytes it becomes. Bottom: two squares. Each side is a sequence length, so the area is the attention work. Pick a string.

Bytes from TextEncoder. GPT-2 token counts from tiktoken, stored in the page. The squares count only the attention score matrix, which grows with length squared; the rest of the model grows with length.

Why does length hurt so much? In attention, every position scores every other position, so one layer builds a table of T by T scores. If the byte sequence is r times longer than the token sequence, that table is r times wider and r times taller:

Say it aloud

C-bytes over C-tokens equals B over T, squared, which is r squared.

Cbytes
C-bytes the attention work on the byte sequence: B times B scores per layer and head.
Ctokens
C-tokens the attention work on the token sequence: T times T scores.
B
B the length in bytes.
T
T the length in tokens.
2
squared because the score table has one row and one column per position.
r
r the compression ratio from Chapter 1.
In plain words

Find how many times longer the byte sequence is than the token sequence: that is r. Multiply r by itself. That is how many times more attention work bytes cost.

With numbers

From the device: the paragraph is B = 282 bytes and GPT-2 gives T = 75 tokens, so r = 3.76. Bytes cost 282 × 282 = 79,524 scores against 75 × 75 = 5,625: 14.1 times the work, and 3.76 squared is 14.1.

The context window suffers the same way. GPT-2 sees 1,024 positions. At 3.76 bytes per token that is about 3,850 bytes of this English; as raw bytes it is 1,024.

Symptom: a byte-level model runs out of context, or memory, on documents a token model reads whole.

Measure: compute r for your data. Attention work grows as r squared, and the context in bytes shrinks by r.

Fix: merge common byte runs into single tokens, so T falls well below B. That is byte-pair encoding.

A byte tokenizer has a perfect vocabulary of 256 and always round-trips. What is its fatal flaw?

Chapter 4

Words: The Unknown Word

Give every word its own token, and find what happens to a word you never saw

Classical NLP split text into words. One token per word gives short sequences. A regular expression does the split. The simplest one, \w+|., keeps runs of letters together and makes every other character its own piece.

GPT-2 uses a more careful pattern, and you will meet it again in Chapter 7:

regex
'(?:[sdmt]|ll|ve|re)   # the endings 's 'd 'm 't 'll 've 're
 ?\p{L}+              # an optional space, then a run of letters: " world"
 ?\p{N}+              # an optional space, then a run of digits: " 2025"
 ?[^\s\p{L}\p{N}]+    # an optional space, then punctuation or symbols: " 🐈"
\s+(?!\S)|\s+        # runs of whitespace

The optional space in front is why " world" carries its space. To make a word tokenizer, collect every piece in the training text and give each one an integer. Our story has 98 different pieces. Now feed it a paragraph it has not seen.

Meet the unknown word

The chips are the held-out paragraph split by GPT-2's pattern. Red chips are not in the vocabulary, so they become UNK. Drag to keep more of the story's words.

98 words

Illustrative. The vocabulary is the story's most frequent pieces. We wrote the paragraph (74 pieces) separately and never trained on it.

Even with every one of the story's 98 words, 17 of the paragraph's 74 pieces are unknown: 23%. "found", "small", "bed", "little". The story was small, but the problem does not go away with size: real text holds names, typos, numbers and URLs without end. Of the 98 words, 50 appear only once in the story, so their embeddings would barely train.

The lecture lists three problems. The number of words is huge. Many words are rare. And there is no fixed vocabulary size. A word outside the vocabulary becomes a special UNK token, and that breaks scoring too.

Symptom: a word model's perplexity looks good on text full of names, yet its outputs are full of UNK.

Measure: count UNKs. Every unknown word maps to one shared token, so predicting UNK is easy and the score hides the loss.

Fix: use a vocabulary that can spell anything. Bytes can; the next chapter keeps that and adds short sequences.

What is the UNK problem of word-level tokenization?

Chapter 5

BPE: Merge the Most Frequent Pair

Start from bytes, count every adjacent pair, fuse the winner into a new token, and repeat

Byte-pair encoding (BPE) takes the middle road: start from bytes, so nothing is ever unknown, then merge byte runs that are common in the data. Philip Gage introduced it in 1994 for data compression. Sennrich, Haddow and Birch adapted it to neural machine translation in 2016, and GPT-2 used it on bytes.

Training is one loop. Write the text as bytes. Count every pair of neighbouring tokens. Give the most frequent pair a new id (256 for the first), replace it everywhere, and count again: the merge changed the neighbours.

Call the count of a pair of neighbouring tokens a then b count(a, b). The pair the loop picks is:

Say it aloud

The pair a-star, b-star equals the argmax over pairs a, b of count of a, b.

(a*, b*)
a-star, b-star the pair this step merges into one new token.
argmax(a, b)
the argmax over pairs a, b the pair that makes the count largest, among all neighbouring pairs in the text right now.
count(a, b)
count of a, b how many times token b comes right after token a.
In plain words

Walk the sequence once and add one to count(a, b) for each neighbouring pair. Pick the pair with the largest count. If several tie, a fixed rule picks one.

With numbers

"the cat in the hat" is 18 bytes. Four pairs have count 2: (t, h), (h, e), (e, ␣) and (a, t). Every other pair has 1. The lecture's code keeps the first pair it saw, (t, h), and makes token 256 = "th".

Step the merge loop by hand

Top: the sequence as tokens. Bottom: every pair's count, teal, with ties edged in yellow and the chosen pair in purple. Press Merge.

The lecture's train_bpe, run live: no pre-tokenizer, ties go to the pair seen first.

Three merges make 18 tokens into 12: "the ", c, a, t, ␣, i, n, ␣, "the ", h, a, t. The loop found "the " by counting alone. The fourth merge is (a, t), tied all along.

How much shorter does each merge make the sequence? Call the length before the merge T and the number of places the merge replaced k. Each replacement turns two tokens into one:

Say it aloud

T-prime equals T minus k.

T′
T-prime the sequence length after this merge.
T
T the sequence length before it.
k
k how many times the merge fired, scanning left to right. k is never more than count(a*, b*).
In plain words

Scan left to right. Each time the pair appears, write the new token and skip both halves: one token saved. Subtract the number of fires k from the old length T.

With numbers

"aaabdaaabac" is T = 11 bytes. count(a, a) = 4, because "aaa" holds two overlapping pairs, twice. The scan fires only k = 2 times ("aa" then a lone "a"), so T′ = 11 − 2 = 9, not 7.

Symptom: your BPE and a reference BPE learn different merges from the same text.

Measure: print each step's top counts. On "low lower lowest", (l, o) and (o, w) tie at 3.

Fix: fix one tie rule. The lecture keeps the pair seen first, (l, o); the Assignment 1 handout takes the lexicographically greater pair, (o, w). They give different tokenizers.

After BPE merges the most frequent pair, what must it do before it picks the next merge?

Chapter 6

Encoding New Text: Replay the Merges

Apply the learned merges to unseen text in learned order, and decode by joining bytes

Training leaves two tables. The vocab maps each id to its bytes: ids 0 to 255 are the raw bytes, 256 and up are merges. The merges list maps a pair of ids to its new id, in learned order. That is the whole tokenizer.

To encode new text, turn it into bytes and replay the merges, first to last. To decode, look up each id's bytes and join them. The lecture trains three merges on "the cat in the hat", then encodes "the quick brown fox". Only "the " fires, so 19 bytes become 16 tokens. Unseen words fall back to bytes; nothing is ever unknown.

Replay the merges on a new word

The chips start as bytes. Each press applies the next learned merge that can fire, in learned order; its rank is its place in the merges list. Pick a word.

Illustrative: the 209 merges our trainer learned from the story with GPT-2's pre-tokenizer, the same ones as the hero.

The lecture's encode loops over every merge and scans the whole sequence each time. Call the number of merges M and the number of bytes in the text n. The pair checks it makes are:

Say it aloud

Work equals M times n.

work
work the number of pair checks the naive encoder makes, at most.
M
M the number of learned merges: 209 here, 50,000 for GPT-2.
n
n the length of the text in bytes.
In plain words

For each of the M merges, walk all n positions of the text looking for that pair. Multiply M by n for the total checks.

With numbers

GPT-2 has M = 50,000 merges. One page of n = 4,000 bytes costs up to 50,000 × 4,000 = 200 million checks. Only a few hundred merges can fire on it.

Symptom: tokenizing a dataset takes longer than training on it.

Measure: time encode against the number of merges; the naive loop grows with M × n.

Fix: the lecture's note for Assignment 1: loop only over the merges that matter. One way: look only at pairs present in the text, and merge the lowest-rank one first. Pre-tokens (next chapter) also let you cache each word's result.

How does a trained BPE tokenizer encode a word it never saw in training?

Chapter 7

Pre-tokenize, Then Merge Inside the Pieces

Cut text into word-like pieces first, so merges never cross a word, and keep special tokens whole

Run BPE on raw text and it merges whatever is frequent, spaces and punctuation included. On our story it learns ". The cat " as one token. It also learns "dog.", "dog!" and "dog?" as separate tokens; the GPT-2 paper names that waste of vocabulary slots.

The fix is pre-tokenization: split the text with the Chapter 4 regex first, then run BPE inside each piece. Merges cannot cross a piece boundary. GPT-2 does this, and so does Assignment 1. It is also faster: count each distinct piece once and weight its pairs by how often it occurs.

Train with and without pre-tokens

Top: one story sentence, cut into pieces. Bottom: the first 24 merges learned from the whole story. A red merge spans two pieces. Switch the pre-tokenizer.

Illustrative: our trainer on the 1,194-byte story. "Crosses a word" means GPT-2's pattern would cut the merged token into two or more pieces.

Without pre-tokens, 27 of the first 50 merges span two pieces: "he ", ". T", ". The cat ". With them, none can. Encoding must use the same split as training, or the merges will not match.

One more rule. Training text holds markers such as <|endoftext|> between documents. These special tokens must stay one token, never split and never merged across. GPT-2 has one, id 50256. Its vocabulary is 256 bytes + 50,000 merges + 1 special token = 50,257.

Symptom: documents bleed into each other in training, or a user can type the end-of-text marker.

Measure: encode the marker. As plain text GPT-2 makes 7 tokens: < | end of text | >. As a special token it is one id, 50256.

Fix: split the corpus on special tokens before you pre-tokenize, and map each to its id. Refuse them in user text unless allowed; tiktoken raises an error by default.

Why does Assignment 1 pre-tokenize with the GPT-2 regex before running BPE merges?

Chapter 8

Vocabulary Size Is a Trade

Buy shorter sequences with more merges, and pay in table size and in rarely trained tokens

BPE lets you choose the vocabulary size: stop after M merges. Each merge adds one entry. Call the number of special tokens S. The vocabulary size V is:

Say it aloud

V equals 256 plus M plus S.

V
V the vocabulary size: how many different token ids exist.
256
two hundred fifty-six one entry for every possible byte, ids 0 to 255.
M
M the number of merges training ran; each adds one id.
S
S the number of special tokens, such as end-of-text.
In plain words

Start with the 256 bytes. Add one entry for each of the M merges. Add the S special tokens. The sum is V.

With numbers

GPT-2: 256 + 50,000 + 1 = 50,257, which tiktoken reports. Our story BPE: 256 + 209 + 0 = 465.

Every entry costs a row in the input table and a column in the output layer. Call the model width d, the length of each embedding vector. The parameters in those two tables are:

Say it aloud

P-emb equals two times V times d.

Pemb
P-emb the parameters in the input embedding table plus the output layer.
2
two one table in, one out. A model that ties them, as GPT-2 does, pays once.
V
V the vocabulary size from the line above.
d
d the model width: numbers per embedding vector.
In plain words

Each of the V tokens gets a vector of d numbers going in, and another d coming out. Multiply 2 by V by d.

With numbers

GPT-2 small has d = 768. Untied, 2 × 50,257 × 768 = 77.2 million. GPT-2 ties the two, so it pays 38.6 million, about a third of its 124 million parameters.

Grow the vocabulary, measure two ways

Teal: the compression ratio on the story the merges came from. Pink: on the held-out paragraph. Drag the merges and watch the gap.

100 merges

Illustrative toy, computed live. Embedding size shown at d = 768, untied, to compare with GPT-2 small.

The first merges save the most: 55 tokens of the story, then 52, then 41. By merge 100, each saves 2. On the story, 209 merges reach r = 3.55; on the held-out paragraph, only 2.50. Real vocabularies stop between about 50,000 and 200,000 entries for the same reason: each new entry buys less.

TokenizerVParagraph (282 bytes)"Hello, 🌍! 你好!" (20 bytes)
GPT-2 (gpt2)50,25775 tokens12 tokens
GPT-4 (cl100k_base)100,27775 tokens10 tokens
GPT-4o (o200k_base)200,01975 tokens8 tokens

Quadrupling V changes nothing on simple English: all three use 75 tokens. On the Chinese characters it does: "你好" goes from 4 tokens to 2 to 1. Extra entries pay off only on text they cover.

Symptom: the model acts strangely when it meets certain single tokens.

Measure: look for vocabulary entries that are rare in the model's training data. GPT-2's vocabulary holds " SolidGoldMagikarp" as one token; Rumbelow and Watkins (2023) found such tokens make GPT models misbehave.

Fix: train the tokenizer on data like the model's, and check that every entry occurs often enough to train its row.

You double the number of BPE merges. What do you buy, and what do you pay?

Chapter 9

Showcase: Train BPE One Merge at a Time

Pick or type a corpus, step the trainer, and watch the counts, the curve and the sequence change together

This is the whole loop, live. The bars are the current top pair counts. The curve is the compression ratio after each merge. The chips are the start of the corpus, with every learned merge edged in purple.

Train your own tokenizer

Pick a corpus or type one. Press Step to merge once, Play to run, or drag the slider. Switch pre-tokens off and watch merges cross words.

0 merges

Illustrative. Your browser trains the lecture's algorithm on the text above, up to 2,000 characters and 400 merges. Ties go to the pair seen first.

Things to try. Use the repetitive corpus: a few merges swallow whole phrases and r shoots up, which is why repeated data compresses well and teaches little. Watch the first story merges: "at", "he", " t", " the". BPE finds word parts from counts alone. Choose mixed scripts: the emoji's four bytes merge only if the emoji repeats.

Check yourself. Set merges to 0 and read r: it is 1. Step until r passes 1.5. Can you name the first three merges and say why each won? Then you can train a tokenizer.

Chapter 10

Field Guide

Keep the comparison, the code, the checks, and where tokenization goes next

A language model never sees text. It sees integers, and the tokenizer decides how much text each integer carries. Characters and words need open, mostly idle vocabularies; bytes need no vocabulary and make the longest sequences. BPE starts from bytes and merges what the data repeats, to a size you choose.

TokenizerVocabularyHero sentence (44 bytes)Fails on
Charactersabout 150,00041 tokens, r = 1.07a huge table of rare rows
Bytes25644 tokens, r = 1.00length; attention grows as r squared
Words98 (the story)11 tokens, 3 of them UNKunseen words
BPE, 209 merges46519 tokens, r = 2.32little: a small, fixed trade
GPT-2 BPE50,25714 tokens, r = 3.14splits rare text into bytes

The core, as the lecture writes it. merge is the one primitive that training and encoding share.

python
from collections import defaultdict

def merge(indices, pair, new_index):
    """Return indices with every adjacent pair replaced by new_index."""
    out, i = [], 0
    while i < len(indices):
        if i + 1 < len(indices) and (indices[i], indices[i + 1]) == pair:
            out.append(new_index); i += 2      # consume both halves
        else:
            out.append(indices[i]); i += 1
    return out

def train_bpe(string, num_merges):
    indices = list(string.encode("utf-8"))         # start from bytes
    vocab = {x: bytes([x]) for x in range(256)}    # id -> bytes
    merges = {}                                     # (id, id) -> new id, in order
    for i in range(num_merges):
        counts = defaultdict(int)
        for a, b in zip(indices, indices[1:]):
            counts[(a, b)] += 1
        pair = max(counts, key=counts.get)          # ties: first pair seen
        new_index = 256 + i
        merges[pair] = new_index
        vocab[new_index] = vocab[pair[0]] + vocab[pair[1]]
        indices = merge(indices, pair, new_index)
    return vocab, merges

def encode(string, merges):
    indices = list(string.encode("utf-8"))
    for pair, new_index in merges.items():          # replay in learned order
        indices = merge(indices, pair, new_index)
    return indices

def decode(indices, vocab):
    return b"".join(vocab[i] for i in indices).decode("utf-8")

vocab, merges = train_bpe("the cat in the hat", 3)
ids = encode("the quick brown fox", merges)
assert decode(ids, vocab) == "the quick brown fox" and len(ids) == 16

We ran this code: it learns "th", "the", "the " and encodes the fox sentence in 16 tokens. For real work, use OpenAI's tiktoken: tiktoken.get_encoding("gpt2").encode("hello hello") returns [31373, 23748].

Assignment 1 builds the full version: pre-tokenize with the GPT-2 regex, keep special tokens whole, encode fast, and train on TinyStories and OpenWebText. The current handout asks for vocabularies of 10,000 and 32,000.

Where it goes next. The lecture calls tokenization a necessary evil. ByT5, MegaByte, the Byte Latent Transformer and T-FREE feed the model bytes or skip the vocabulary. They are promising, but not yet scaled to the frontier, because of the length problem in Chapter 3.

Keep going

Read next

The habit. For any tokenizer, ask three things: does it round-trip, what is r on held-out text, and what does each entry cost in the model.
In one sentence, why is BPE the best of both worlds between bytes and words?

Now teach it: press Present or Teach. Explain why bytes never meet an unknown word but cost r squared in attention, and how one merge loop fixes it. Then go back to the sentence and predict its token count at 50 merges before you drag there.

Overview & Tokenization · Stanford CS336, Lecture 1
Next: PyTorch and Resource Accounting · Course site · Back to Gleams