Tools › Tokenizer

Tokenizer: how text becomes tokens

A language model does not read letters or words but tokens, pieces of text from a fixed vocabulary. Most tokenizers learn that vocabulary with byte-pair encoding. Here you can watch it learn.

What to look for

  • Drag the merge slider from 0 to the end. At 0 every byte is a token. Frequent pairs such as “th” or “ e” join first, then whole common words.
  • Tokens are not words. A rare word is cut into several pieces, a frequent word is one token, and a leading space belongs to the word after it.
  • Numbers and other scripts cost more. Switch to the numbers, German or emoji sample. An accented letter, a Japanese character or an emoji is two to four bytes, so it needs several tokens until it has been seen often enough to merge.
  • The training text decides the vocabulary. Learn from English, then tokenize German: the same sentence needs many more tokens. This is one reason why the same text can cost more in some languages.

The algorithm

  1. Cut the text into “words” (a run of letters, a run of digits, or a run of other symbols, with a leading space attached) and write each word as a list of bytes in UTF-8. The vocabulary starts with the 256 possible byte values.
  2. Count how often every neighbouring pair of tokens occurs inside the words, weighted by how often each word occurs.
  3. Join the most frequent pair into a new token and record the merge. Replace the pair everywhere.
  4. Repeat. To tokenize new text, apply the recorded merges in the same order.

Working on bytes means that no text is ever unknown, because anything can be written as bytes. This is the idea of byte-level BPE used by many current models. Ties go to the smaller pair, so the result is repeatable. The demo stops when no pair occurs twice.

What it simplifies

Real tokenizers learn from gigabytes of text and use vocabularies of 30 000 to 250 000 tokens, with extra rules for the cut into words, special tokens such as “end of text”, and sometimes normalisation of the input. This demo learns at most 300 merges from the text you enter.

References

  1. Sennrich, Haddow, Birch, Neural Machine Translation of Rare Words with Subword Units (2015)
  2. Kudo, Richardson, SentencePiece: A simple and language independent subword tokenizer and detokenizer (2018)