01. The Language Modeling Pipeline and Tokenization#
Level: Practitioner · Reading time: 16 min · Exercise: 90 min
In one sentence: After this chapter you can turn any string into token IDs with a byte-pair encoding tokenizer you wrote yourself, and you can name the five pieces that CS336 builds to get from raw text to a trained language model.
Why this matters#
You paste a 2,000-character email into a token-counting tool and it reports about 500 tokens. Price lists, context limits and speed are all quoted in tokens, never in characters. Then two odd things show up. The word "world" costs one token in the middle of a sentence and two at the start of one. The phrase hello hello is split in two different ways, once with a space glued to the word and once without.
The model never sees your text. It sees integers. So two questions come before any architecture or training math:
- What are the units a language model actually reads, and how does text become them?
- Where does that step sit in the work of building a language model from scratch?
This chapter answers both: first the map of the whole build, then tokenization from bytes to byte-pair encoding.
The core idea#
A language model reads a sequence of tokens, gives a probability to every possible next token, and, when you ask it to generate, picks one. A token is an integer between 0 and V−1, where V is the vocabulary size.
Text is not integers. A Python str is a sequence of Unicode characters, and the UTF-8 encoding turns each character into one to four bytes, each a number from 0 to 255. So you need a translator. A tokenizer is two functions: encode turns a string into a list of integers and decode turns them back. The one hard requirement is the round trip: decode(encode(text)) == text.
The analogy is the lexer in a compiler, which turns characters into tokens such as keywords and identifiers. The analogy breaks in two places. A lexer's token kinds are fixed by the language grammar, while a tokenizer's vocabulary is learned from a corpus. And a lexer throws whitespace away, while a tokenizer keeps it: the space before a word is part of a token.
Why translate at all, if bytes are already integers? Because of cost. The work a model does per token is roughly fixed, but attention, the mechanism that lets each token look at the others, costs more as sequences get longer. Liang's reason, in Lecture 1, is that attention is quadratic in the sequence length, so a shorter sequence is cheaper (66:00). On screen he converts a 20-byte string into 8 tokens, 2.5 bytes per token. A modern tokenizer packs about 1,000 bytes into 250 tokens. That is four times less sequence for the model to process. He names a second, subtler benefit: common stretches of many bytes collapse into one token, while rare or interesting parts stay as several tokens, so the model spends more computation where it matters (28:00). Tokenization is an efficiency decision.
How CS336 frames the whole pipeline#
Stanford CS336, Language Modeling from Scratch (Spring 2026, taught by Percy Liang and Tatsunori Hashimoto), has one organizing idea: train the best model you can with a fixed budget of compute and memory. Every piece of the build is judged by that standard. The course splits into five units, each with one assignment:
| Unit | Question it answers | What students build |
|---|---|---|
| Basics | What are the atoms, the model and the training loop? | A tokenizer, a Transformer, a training loop; train on TinyStories and OpenWebText |
| Systems | How do you get the most out of GPUs? | A fused kernel in Triton, distributed training, profiling |
| Scaling laws | How big should the model be for a given budget? | Fits that predict loss from small runs |
| Data | What do you train on? | Text extraction, quality filters, deduplication |
| Alignment | How do you make the model useful and safe? | Fine-tuning and reinforcement learning methods |
For the big picture of why pretraining, see how large language models are trained. This part of the course follows the five units one chapter at a time.
The design space of tokenizers#
Four ways to choose the atoms are worth comparing. The measure that matters is the compression ratio: bytes per token. Higher is better for compute, because the sequence gets shorter.
| Scheme | Vocabulary size | Compression | Main problem |
|---|---|---|---|
| One token per Unicode character | About 150,000 | Low | Many characters are rare, so vocabulary slots are wasted |
| One token per byte | 256 | Very low | Sequences are far too long |
| One token per word | No fixed limit, in the millions | High | Rare words are learned badly; new words have no token |
| Byte-pair encoding (BPE) | You choose it | High | Adds a separate component with its own file to ship |
The character and byte schemes sit at opposite ends, and Liang builds both in Lecture 1. The character version offers about 150,000 tokens, but many characters are rare, which makes it an inefficient use of a vocabulary (68:00). The byte version has 256 tokens and a compression ratio of exactly 1, so its sequences can be very long. His verdict on both is blunt: really bad (70:00).
Words look better. Each token means something, because humans invented words and words keep a stable meaning. The cost is an open-ended vocabulary: at test time a word the tokenizer has never seen has to become a special UNK token, which Liang calls really ugly and says can mess up perplexity calculations (70:00). Perplexity is the model's average uncertainty about the next token (lower is better), counted per token, so two models with different tokenizers are not comparable on it.
How it works, step by step#
Byte-pair encoding learns the vocabulary from data. Common sequences of bytes become single tokens. Rare sequences stay split.
Training:
- Encode the corpus with UTF-8. You now have a long list of integers, each from 0 to 255.
- Count every pair of adjacent integers.
- Take the most frequent pair. Assign it the next free ID (the first is 256). Record the merge.
- Replace every occurrence of that pair in the list with the new ID.
- Repeat from step 2 until you have the number of merges you want.
Encoding new text:
- Encode the string as bytes.
- Apply the recorded merges in the order they were learned, one merge at a time over the whole sequence.
- Return the resulting IDs.
Decoding: each ID stands for a byte string (a raw byte for 0 to 255, the two merged strings joined for the rest). Join the byte strings and decode them as UTF-8.
Figure 1. Byte-pair encoding: training repeats a loop to learn merges, and encoding new text only replays them.
flowchart TD
C["Corpus as bytes"] --> P["Count adjacent pairs"]
P --> B["Pick the most frequent pair"]
B --> N["Give it the next free ID and record the merge"]
N --> R["Replace every occurrence of the pair"]
R --> X["Enough merges yet"]
X -->|"no"| P
X -->|"yes"| M["Merges in learned order"]
M --> A["Apply the merges one at a time"]
T["New text as bytes"] --> A
A --> I["Token IDs"]
I --> D["Look up the byte string of each ID"]
D --> U["Join and decode as UTF-8"]
The loop is training; the second path is encoding, which counts nothing, so text the tokenizer has never seen still falls back to bytes.
Liang's own example is the cat and the hat. The most frequent pair is the two bytes of th, which becomes token 256; the next merges produce the (257) and one more token (258), so the sequence shrinks while the vocabulary grows (74:00). The code he shows works, he says, but is extremely slow, and making it fast is part of the first assignment. Real tokenizers add three things (76:00):
- Pre-tokenization: splitting text into chunks first, with a regular expression as the GPT-2 tokenizer does, so merges never cross a word or punctuation boundary.
- Special tokens: strings such as
<|endoftext|>that mark document boundaries. The tokenizer must detect them and never split them. - Speed: when encoding, loop only over the merges that can actually apply, not over all of them.
Worked example#
A complete byte-level BPE in plain Python:
from collections import Counter
def merge(data, pair, new_id):
"""Replace every (pair[0], pair[1]) in `data` with `new_id`."""
out, i = [], 0
while i < len(data):
if i < len(data) - 1 and (data[i], data[i + 1]) == pair:
out.append(new_id)
i += 2
else:
out.append(data[i])
i += 1
return out
def train_bpe(text, num_merges):
"""Learn `num_merges` merges. IDs 0-255 stay the raw bytes."""
data, merges = list(text.encode("utf-8")), {}
for i in range(num_merges):
pairs = Counter(zip(data, data[1:]))
if not pairs:
break
pair = max(pairs, key=pairs.get) # most frequent adjacent pair
merges[pair] = 256 + i
data = merge(data, pair, 256 + i)
return merges
def encode(text, merges):
data = list(text.encode("utf-8"))
for pair in sorted(merges, key=merges.get): # in the order learned
data = merge(data, pair, merges[pair])
return data
def decode(ids, merges):
vocab = {i: bytes([i]) for i in range(256)}
for (left, right), new_id in merges.items():
vocab[new_id] = vocab[left] + vocab[right]
return b"".join(vocab[i] for i in ids).decode("utf-8")
corpus = ("the cat sat on the mat. the dog sat on the log. "
"a cat and a dog sat on a mat. ") * 50
m = train_bpe(corpus, 30)
Run on this corpus, the first merges are at, at, th, the, the, the, sat, sat o, sat on, og, a, a. Encoding four short strings gives:
| Input | Bytes | Tokens | Pieces |
|---|---|---|---|
the cat sat on a log |
20 | 6 | the, cat, sat on, a, l, og |
catalog |
7 | 5 | c, at, a, l, og |
The cat |
7 | 6 | T, h, e, , c, at |
the cat sat on the mat. |
23 | 3 | the, cat sat on the, mat. |
Five things to observe:
- Frequency drives everything.
atmerges first because it is the most common pair. - Spaces stick to words.
theandtheare different tokens, which is thehello helloeffect from the start of the chapter. - Nothing is unknown.
catalognever appears in the corpus, so it falls back into pieces the model has seen. - Capital letters are different bytes.
Thebreaks apart completely. - Merged phrases appear, such as
cat sat on the. The corpus is one tiny paragraph repeated, so merges run across word boundaries. Pre-tokenization prevents this, and so does diverse training text.
The round trip decode(encode(corpus)) == corpus holds.
What the practitioners say#
Percy Liang opens the course with a claim about what a small-scale course can teach. He sorts knowledge into three kinds: mechanics (how things work), mindset (squeezing the hardware, taking scaling seriously) and intuitions (which data and modeling choices work). The first two transfer to a larger scale. Intuitions only partly do, because small models behave differently: in an old plot he shows, the share of FLOPs (floating-point operations) spent in the MLP (feed-forward) layers is about 44% at small scale and about 80% at 175B parameters (6:00).
His organizing lens is efficiency, and he applies it to every unit, including data: "We don't want to waste time updating gradients on a bunch of redundant bad data" (64:00). With a fixed compute budget, time spent on bad data is time not spent on good data.
His advice for someone with an application has three steps, in order: prompt a model, fine-tune a model, and only as a last resort pretrain your own, because pretraining is a pain and expensive. He adds that watching lectures is not enough: "you learn really by doing the assignments" (22:00).
On tokenization itself, Lecture 1 makes four points:
- You can raise the compression ratio by growing the vocabulary, and multilingual tokenizers now have 100,000 to 200,000 tokens, but you then run into sparsity, because every element of the vocabulary is treated as a distinct element (66:00).
- BPE was introduced for data compression, long before language models, and entered NLP through neural machine translation. The first language model paper to use it was GPT-2 (72:00).
- BPE is a data-driven heuristic that works well. Character, byte and word tokenization are each "highly suboptimal" in their own way (76:00).
- The dream is a model that operates on bytes end to end. Recent work such as H-Net looks promising, but none of it has been scaled to the frontier, so the course still teaches tokenizers (28:00).
Liang closes with two properties any replacement must have (78:00): the model should operate on chunks, not on raw units, which matters even more for video or DNA than for text, and chunks should vary in size, because not all bytes deserve the same computation.
Pitfalls#
- Treating a token as a word. English averages roughly four bytes per token with a modern tokenizer, but punctuation, code and other languages differ. Fix: measure with the tokenizer you will ship.
- Cleaning text before tokenizing. Stripping leading spaces or lowercasing changes the token IDs. Fix: tokenize exactly what the model will see.
- Training BPE on a small or repetitive corpus. Merges cross word boundaries and become phrases. Fix: train on representative text and add pre-tokenization.
- A slow
encode. Applying every merge to the whole sequence for every input wastes time. Fix: consider only the merges that can apply, as the assignment asks. - Decoding bytes token by token. One emoji is four bytes that may land in four tokens. Decoding each one alone raises a UTF-8 error. Fix: join all bytes first, as
decodeabove does. - Reusing IDs across models. Every tokenizer has its own vocabulary. Token 256 is
thin Liang's example andatin the listing above; in another model it is something else. - Comparing perplexity across tokenizers. Fewer, longer tokens mean less uncertainty per token. Fix: compare models only on the same tokenizer, or convert to a per-byte measure.
Try it#
Save the code above as bpe.py and use a real text file of at least 1 MB as the corpus.
The listing is too slow for that size as written: encode loops over every merge for every input, and training with 5,000 merges takes about 20 minutes. Work line by line. To encode a line, build a dictionary from pair to merge order and apply only the merges whose pair is present, lowest order first.
Deliverable: a script that trains on 90% of the file and reports results on the other 10%.
You are done when:
- The round trip holds on the held-out text, including at least one line with non-ASCII characters.
- A word absent from the training split still encodes without any unknown-token marker.
- You report the compression ratio on held-out text for 50, 500 and 5,000 merges, and it is lower than on the training text.
- Encoding the held-out text takes under 30 seconds, without looping over every merge.
Stretch: add pre-tokenization with a regular expression that keeps letters, digits, spaces and punctuation apart. Compare the first 30 merges with and without it.
Key takeaways#
- A language model reads integers. The tokenizer converts between strings and token IDs and must round-trip exactly.
- Tokenization exists for efficiency: fewer tokens means a shorter sequence and less attention work.
- Byte-pair encoding starts from bytes and repeatedly merges the most frequent adjacent pair. Common chunks become one token and anything unseen falls back to bytes.
- CS336 treats every part of the build, tokenization included, as a question of efficiency under a fixed budget.
- The course teaches mechanics and mindset; intuitions from small models only partly carry over.
Self-check#
- What must every tokenizer guarantee? - A. The most frequent words map to the lowest IDs - B. Encoding and decoding return the original string - C. Every input string uses fewer tokens than bytes - D. The vocabulary stays below 65,536 entries
- Why are raw bytes a poor choice for a Transformer in CS336's view? - A. Bytes cannot represent text that is not English - B. GPUs refuse to multiply integer matrices efficiently - C. Long sequences make the attention cost grow too quickly - D. Byte sequences cannot be decoded without loss
- In BPE training, what picks the next merge? - A. The pair of adjacent tokens that occurs most often - B. The pair whose tokens have the smallest IDs - C. The longest word in the current vocabulary - D. The pair whose merge shortens the text least
- You train byte-level BPE with 1,000 merges. How many token IDs exist? - A. 1,000 - B. 256 - C. 1,256 - D. 512
- Why does
The cattake six tokens whenthe cattakes three? - A. Capital letters are encoded as two bytes each - B. No merge was learned for the byte sequences of that variant - C. The tokenizer rejects words at the start of a string - D. The encoder sorts tokens before merging
Show answers
1. B. The round trip `decode(encode(text)) == text` is the one hard requirement. 2. C. Attention cost grows about quadratically with sequence length, and bytes make sequences long. 3. A. Each round merges the most frequent adjacent pair in the current sequence. 4. C. The 256 raw byte IDs plus 1,000 merged IDs. 5. B. `T` and `t` are different bytes, so the merges learned for `the` never apply to `The`.Sources#
- Lecture: Percy Liang, "Lecture 1: Overview, Tokenization", Stanford CS336 Language Modeling from Scratch (Spring 2026): video · guide, used at three kinds of knowledge, learn by doing, efficiency lens, tokenization, what replaces tokenization
- Course: Stanford CS336, course page
- Reading: Philip Gage, "A New Algorithm for Data Compression" (1994), where BPE was introduced
- Reading: Rico Sennrich, Barry Haddow and Alexandra Birch, "Neural Machine Translation of Rare Words with Subword Units" (2016): arXiv
- Reading: Andrej Karpathy, "Let's build the GPT Tokenizer" (2024), the video Liang recommends in Lecture 1 (64:00): video
Next#
→ Resource Accounting: FLOPs, Memory and Arithmetic Intensity, because the efficiency argument for tokenization only makes sense once you can count what a model spends. When you are ready for the model itself, continue with Transformer Architectures and Hyperparameters, and see Building Your Own for how the tokenizer fits into the first assignment.