Tokenwerk · The LLM textbook

Chapter 10 · II · From numbers to language · 9 minutes

From text to token IDs

Language at last! But a computer can't read, only compute. So we chop text into pieces and give each piece a number. Sounds trivial, but it is full of clever ideas.

What is a token, and why do we need it?

A computer can't compute with letters, only with numbers. Our network from the first chapters takes numbers, multiplies them by weights and adds up. So before a language model can process a text, the text has to be translated into numbers.

To do that, we first chop the text into small pieces. Such a piece is called a token. Depending on the method, a token is a single character, part of a word or a whole word. Every possible token gets a fixed number, the token ID. The list of all possible tokens is called the vocabulary.

Illustration: scissors cut a long paper ribbon of writing into colorful puzzle pieces that get sorted into a chest of drawers.

The program that chops and numbers is called the tokenizer. It works in both directions: encoding turns text into a list of IDs, decoding turns IDs back into text. The language model itself never sees a single letter, only these IDs. Even when it writes, it picks IDs that the tokenizer then turns back into readable text.

Step Example
Text The cat
Tokens The · ␣cat
Token IDs [312, 1045]
decoded back The cat

The IDs are made up; every tokenizer assigns its own. ␣ stands for the space, which belongs to the token here.

Why not just whole words? Because there are infinitely many: new names, typos, monster compounds like “catfoodbowlholder”. A vocabulary of word pieces stays manageable and can still build every new word from known parts, like Lego. This chapter shows how to find good pieces.

A side effect you may have seen: because language models see tokens instead of letters, they often struggle with questions like “How many r's are in strawberry?”. They never see the word letter by letter.

IDs are house numbers, not amounts

The ID 42 doesn't mean “more” than the ID 17. It is an address, like a house number: house 42 isn't twice as big as house 21. If we shuffled all IDs and reordered the tables to match, exactly the same thing would come out. That is why the model never computes with the ID directly, but uses it to look up a row in a table. How that works is shown in the chapter on embeddings.

A token can be a character, a byte, a word piece, a whole word or a control marker. So tokens are not automatically words. The tokenizer decides which pieces the text falls into, and therefore at which spots the model will later predict the next piece.

The simplest tokenizer: every character a token

The simplest idea: every character becomes a token. The following Python code collects all characters that occur, numbers them and translates the text. stoi (“string to integer”) is the table from character to number, itos the reverse. The assert at the end checks that there and back gives exactly the original text.

python
text = 'Hallo Welt!'
vocab = sorted(set(text))
stoi = {c: i for i, c in enumerate(vocab)}
itos = {i: c for c, i in stoi.items()}
ids = [stoi[c] for c in text]
assert ''.join(itos[i] for i in ids) == text

Works, until a character shows up that the tokenizer has never seen. Then it is stuck. You could add a placeholder token “unknown”, but then you lose the exact original text.

Two terms on that: Unicode is the worldwide standard that gives every written character a number: letters, umlauts, Chinese characters, emoji. That number is called a code point. A small gotcha: one visible letter can consist of several code points. Corpus is what we call the collection of texts we work with.

Bytes: the robust foundation

A byte is a small unit of storage made of 8 bits and can take exactly 256 different values, from 0 to 255. UTF-8 is today's standard rule for storing text as bytes: an “a” becomes one byte, a “ü” two, many emoji four.

The trick: every text in the world can be broken into bytes between 0 and 255 this way. A byte tokenizer therefore needs only 256 normal tokens plus a few special tokens, and never meets an “unknown character”.

python
raw = 'Grüße 🐈'.encode('utf-8')
ids = list(raw)
text = bytes(ids).decode('utf-8')
assert text == 'Grüße 🐈'

The catch: a single byte is not necessarily a whole character. If the model later produces an incomplete byte sequence, the program has to cope with that. Our tokenizer then inserts a replacement character.

Byte pair encoding: merging frequent pairs

Bytes alone would be impractical, though: a sentence would get very long. That is why there is byte pair encoding, BPE for short. The idea is brilliantly simple: if “e” and “n” constantly stand next to each other in the text, they get a shared token “en”. Then the same text needs fewer tokens. Such a joining is called a merge. Repeated often enough, tokens appear for common syllables and whole words.

The procedure in our project: start with bytes. Count all neighboring pairs in the training text. Take the most frequent one (on a tie, the one with the smallest IDs), give it a new ID and replace all its occurrences. Count again. Repeat until there are enough merges.

In the word “hallo”, first l,l might become ll and later h,a become ha. Which merges appear is decided by the text alone, not by any grammar rule. In the figure below we use letters instead of bytes to keep it readable; the logic is the same.

And now with real text: the tokenizer below has just learned its merges in your browser, from the first chapters of this book. Type anything into it, your name, a long word, an emoji, and move the slider. With zero merges every byte is a token. The more merges, the bigger the pieces and the fewer tokens the same text needs.

How big should the vocabulary be?

It's a trade-off. A large vocabulary makes texts shorter (fewer tokens), but needs more parameters: the model gets its own row for every token in two big number tables, one for the input and one for the output (see embeddings). And rare tokens hardly ever show up in training. A small vocabulary saves parameters but makes texts longer. For our mini model, a few hundred tokens are enough.

A trap when comparing: the error “per token” of two different tokenizers is not comparable; with one, a token is a byte, with the other half a word. It becomes fair with a shared unit, such as bits per byte: the error per byte of text instead of per token, measured on the same texts.

Special tokens: control markers with their own ID

Our project reserves a few special IDs: PAD, BOS, EOS, USER, ASSISTANT and SYSTEM.

  • BOS (“beginning of sequence”) marks the start of a text, EOS (“end of sequence”) its end. EOS matters: it is how the model later learns when to stop talking.
  • PAD (“padding”) is a placeholder used to bring short examples to the same length.
  • USER, ASSISTANT and SYSTEM later mark who is speaking in a chat.

These markers are not strings of letters but IDs of their own. Normal text can't produce them by accident. If someone writes <assistant> in a text, that is just text, not a role marker. Important, so that nobody can trick the model with a cleverly typed string.

Two rules for later

When you build your own tokenizer in part VII, two rules help:

  • Learn the merges only from the training texts. Split the texts into training and test first. Otherwise the tokenizer already “knows” the test texts, and the model looks better than it is. Such unnoticed seeping through is called data leakage, like someone who saw the exam questions in advance.
  • Check the round trip. For normal text, umlauts, line breaks, emoji and empty texts it must hold: encoding and decoding again gives exactly the original text, so decode(encode(text)) == text. Before a model learns anything, the trip into the world of numbers and back has to be solid.

Build it yourself: in step 1 of part VII you program exactly this byte-level BPE tokenizer.

Key points

  • A tokenizer chops text into tokens and gives each one an ID. The model only sees IDs, never letters.
  • IDs are addresses, not amounts. 42 is not “more” than 17.
  • BPE merges frequent pairs into new tokens. That keeps the vocabulary small and every word representable.