Learn the MachineDansk

Explained with an interactive demo

Byte pair encoding (BPE), step by step

Byte pair encoding is the method many language models use to split text into tokens. The idea is simple: start with single characters, find the neighbouring pair that occurs most often, and merge it into one new piece. Repeat. Watch it happen below, one merge at a time, and try your own text.

The demo needs JavaScript. The text below explains what it shows.

Embed this demo on your site

Copy the code into your page. The demo loads from learnthemachine.com, so it stays up to date, and the link under it shows where it comes from.

How BPE works

  1. Start with characters. Every word is split into single characters. The vocabulary is the distinct characters in the text.
  2. Count neighbouring pairs. For every pair of characters that sit next to each other, count how many times it occurs in the whole text.
  3. Merge the most frequent pair. The pair becomes a new piece, which is added to the vocabulary and replaced everywhere in the text.
  4. Repeat until the vocabulary reaches the size you want.

The result is an ordered list of merges. That list is the tokenizer: to split new text, you start again from characters and apply the merges in exactly the order they were learned. That is why a word that never appeared in the training text can still be split into known pieces, for example “lowest” into “low” and “est”.

A worked example

The demo’s English text is the example from Sennrich, Haddow and Birch: “low” 5 times, “lower” 2, “newest” 6 and “widest” 3. Split into characters, that is 79 tokens and a vocabulary of 10 characters.

  1. “e” + “s” occurs 9 times (6 in “newest”, 3 in “widest”) and is merged first, into “es”.
  2. “es” + “t” also occurs 9 times and becomes “est”.
  3. “l” + “o” and then “lo” + “w” occur 7 times and give “low”.
  4. “n” + “e”, “ne” + “w” and “new” + “est” turn all six “newest” into a single token.

After 12 merges no pair occurs twice, and training stops: the text is down to 16 tokens with a vocabulary of 22 pieces. The word “lowest” is not in the text, but the merges split it into “low” + “est”.

BPE in Python

The whole algorithm fits in about 40 lines of Python. It does the same as the demo: it counts pairs only inside words, breaks ties by the pair seen first, and stops when no pair occurs at least twice. Run it, and it prints the first four merges from the example above.

from collections import Counter

def merge(symbols, pair):
    # Replace the pair everywhere, left to right.
    out, i = [], 0
    while i < len(symbols):
        if symbols[i:i + 2] == pair:
            out.append(pair[0] + pair[1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)

def train(text, max_merges=50):
    # Each distinct word as characters, with its count.
    counts = Counter(text.split())
    words = {tuple(w): n for w, n in counts.items()}
    merges = []
    for _ in range(max_merges):
        pairs = Counter()
        for symbols, n in words.items():
            for pair in zip(symbols, symbols[1:]):
                pairs[pair] += n
        if not pairs:
            break
        # Most frequent pair (ties: the one seen first).
        best = max(pairs, key=pairs.get)
        if pairs[best] < 2:
            break
        merges.append(best)
        words = {merge(s, best): n
                 for s, n in words.items()}
    return merges

def encode(word, merges):
    # Start from characters, apply merges in order.
    symbols = tuple(word)
    for pair in merges:
        symbols = merge(symbols, pair)
    return list(symbols)

text = ("low " * 5 + "lower " * 2
        + "newest " * 6 + "widest " * 3)
merges = train(text)
print(merges[:4])
# [('e', 's'), ('es', 't'), ('l', 'o'), ('lo', 'w')]
print(encode("lowest", merges))
# ['low', 'est']

Counting every pair again after each merge is fine for a small text but slow for a large one. Real implementations keep track of where each pair occurs and update only the counts a merge changes. Byte-level versions start from bytes instead of characters (see below).

Why do language models use BPE?

A model needs a fixed vocabulary. Whole words give a huge vocabulary with no room for new words. Single characters give very long sequences. BPE sits in between: common words become one token, rare words are split into recognisable pieces, and no word is unknown, because you can always fall back on the smallest pieces.

The method comes from data compression and was used to split words for machine translation by Sennrich, Haddow and Birch in 2016. The English example in the demo is the one from their paper. GPT-2 and many later language models use a variant that works on bytes instead of characters.

How real tokenizers differ

What it means for other languages

A tokenizer learns its merges from its training text. If that text is mostly English, English words often become a single token while words in other languages are split into more pieces. The same meaning can then cost more tokens, and so more of the model’s context. In the Tokenization lab you can compare how different tokenizers split the same text.

Try it on real tokenizers

In the free Tokenization lab you see how real language models’ tokenizers split your text, follow BPE merges on your own text, and train a small model on tokens.

Open the Tokenization lab

More explainers