cat /en/llm-tokenization-from-text-to-numbers/
MDN-119:35

From text to numbers: tokenization

· Artificial Intelligence · 6 min read

When we type a question to a language model, it feels as if it reads our words, just as a person would. In reality a model sees neither letters nor words: it sees only integers. Before the neural network does any computation at all, a separate program, the tokenizer, cuts the text into pieces and replaces each piece with a number.

The reason is simple. A neural network is a long chain of multiplications and additions: it works with vectors and matrices, not with strings. So we need a stable, reversible way to turn any text into a sequence of numbers, and then to turn it back. This first article of the Inside an LLM series explains how that is done, and why the choice matters more than it seems.

Characters, words or pieces of words?

The first idea that comes to mind is to give a number to every character. The vocabulary would be small (letters, digits, punctuation) and any text could be represented. The drawback is that sequences become very long: a page turns into thousands of symbols, and the model has to learn from scratch, every time, that “h”, “o”, “u”, “s”, “e” form a word with a meaning.

The second idea is to give a number to every word. Sequences get shorter, but the vocabulary explodes: “speak”, “speaks”, “spoke”, “speaking” would all be separate entries, and the same goes for proper names, typos, technical terms and new words. Any word that is not on the list becomes “unknown”, and the model loses the information.

The solution used today sits in between: subwords. Frequent words become a single piece, while rare ones are split into smaller, already known parts. These pieces are called tokens. A token can be a whole word, a syllable, a suffix such as “-ly”, a single letter or a punctuation mark. With a few tens of thousands of tokens you can write any text, with no unknown words.

Byte Pair Encoding, step by step

How do we decide which pieces go into the vocabulary? The most widespread method is Byte Pair Encoding (BPE). It was born in 1994 as a data compression algorithm, proposed by Philip Gage; in 2016 Sennrich, Haddow and Birch adapted it to neural machine translation to handle rare words. Since then, with a few variants, it has become the standard for language models.

The idea is almost trivial: start from single characters and repeatedly merge the most frequent pair of neighbouring symbols. Let us see it on a tiny text, made of three Italian words: “gatto” (cat) appears 5 times, “gatti” (cats) 3 times and “tutto” (all) 4 times.

  1. At the start every word is a sequence of characters: g a t t o, g a t t i, t u t t o. We count the adjacent pairs, weighted by how often each word appears: t t occurs 5 + 3 + 4 = 12 times, and is the most frequent. We merge it into the new symbol tt.
  2. We count again: now the most frequent pair is tt o, with 5 + 4 = 9 occurrences. The token tto is born.
  3. Next comes g a (8 times), which becomes ga.
  4. Finally ga tto (5 times) becomes gatto, a token that stands for the whole word.

After four merges the vocabulary holds the initial characters plus tt, tto, ga and gatto. “gatto” is a single token, “gatti” becomes ga + tt + i, “tutto” becomes t + u + tto. And a word never seen before, such as “gattino” (kitten), can still be written: ga + tt + i + n + o. No word is unknown; at worst it is split into more pieces.

A real tokenizer repeats this step tens of thousands of times over a huge amount of text. The result is a vocabulary of tens of thousands of tokens, in which every token has a number, its ID. To tokenize a new text, the learned merges are applied in the same order. Many modern tokenizers work on bytes rather than characters: that way any text, in any language or alphabet, emoji included, can be represented.

The consequences: spaces, capitals, numbers and languages

The tokenizer learns from data, and this has some curious effects that are worth knowing.

  • Spaces matter. The space before a word is usually part of the token: “ house” with a space in front and “house” at the start of a line are different tokens, with different IDs.
  • Capitals matter. “House”, “house” and “HOUSE” are different sequences; the less common versions are often split into more pieces.
  • Numbers are split oddly. A frequent year may be a single token, while a long number is cut into groups of digits that do not follow units, tens or thousands. This is one of the reasons why language models struggle with arithmetic.
  • Not all languages cost the same. A language that is very common in the training data, such as English, gets long tokens; a less common one, such as Italian, is split into shorter pieces. The same sentence therefore needs more tokens in Italian than in English.

The last point has practical consequences. The cost of a request to a model and the length of the context it can read are measured in tokens, not in words. A text that needs more tokens costs more and fills the context sooner. For English a rule of thumb is often quoted: on average one token is worth about four characters. For Italian the ratio is usually lower.

DEMO BPE Tokenizer · about this demo · full screen ↗

What to try in the demo

The demo contains a small BPE tokenizer that learns right in the browser, from a few paragraphs of English text about computers and models. It is a teaching tool: real tokenizers are trained on billions of words.

  • Press English and then Try in Italian: the two sentences say the same thing, but Italian needs many more tokens, because the tokenizer has only seen English. Watch the characters-per-token counter.
  • Press Reset and then Step several times: at each step you see the merged pair and how often it appeared. The first merges are pieces such as “ t” or “er”; after a few dozen, whole words such as “ the” appear.
  • Move the Merges slider from 0 to 400 and watch the text at the top: characters fuse into syllables and then into words.
  • Try the Numbers and Capitals & spaces presets, and tick show IDs to see the numbers the model would actually receive.

In Python

The tiktoken library contains real BPE tokenizers, with a vocabulary of about a hundred thousand tokens. Here is how to compare an Italian sentence with its English translation:

import tiktoken

enc = tiktoken.get_encoding("cl100k_base")

sentences = {
    "it": "Il computer legge il testo e lo trasforma in numeri.",
    "en": "The computer reads the text and turns it into numbers.",
}

for lang, sentence in sentences.items():
    ids = enc.encode(sentence)                # text -> list of integer IDs
    pieces = [enc.decode([t]) for t in ids]   # each ID -> its piece of text
    print(lang, len(sentence.split()), "words,", len(ids), "tokens")
    print("  IDs:   ", ids)
    print("  pieces:", pieces)

print("vocabulary size:", enc.n_vocab)
print(enc.decode(enc.encode("Ciao!")))       # back to the original text

For each language the program prints the number of words and tokens, the list of IDs and the matching pieces: the Italian sentence usually needs a few more tokens, with words split into more parts. If a piece shows up as “�”, it is because that token holds only some of the bytes of an accented letter.

From tokens to vectors

Tokenization is the least glamorous step of a language model, and also the one most often forgotten. To me it is well worth knowing, because it explains many behaviours that would otherwise seem mysterious: why a model gets the letters of a word wrong when counting them, why it struggles with numbers, why the same text costs more in Italian.

We now have a sequence of integer IDs. But an ID is just a label: number 1000 is not “similar” to 1001. In the next part we will see how every token becomes a vector of numbers, an embedding, and how in that space meaning takes the shape of geometry. If you want to go deeper into language processing with neural networks, the basics are in chapter 9 of the book Deep Learning con Keras e Tensorflow (in Italian).

The “Inside an LLM” series

  1. From text to numbers: tokenization
  2. Meaning as geometry: embeddings
  3. Predicting the next word
  4. Attention, explained
  5. The Transformer and its training
  6. From model to assistant: fine-tuning, RLHF and RAG