LLMsLoading progress…

Byte-pair merging

Trace a toy tokenizer and explain byte-pair merges, vocabulary IDs and token-budget limits.

Learning pieces by merging frequent pairs

Byte-pair encoding (BPE) builds a vocabulary of useful pieces from data. Start with single symbols. Count every pair of adjacent symbols across the corpus, merge the most frequent pair into a new symbol, and repeat. Frequent chunks ("est", "low") become single tokens; rare words are still spelled out of smaller pieces.

The smallest case: in the symbols a, b, a, b the pair (a, b) occurs twice. Merging it gives ab, ab and shortens the sequence from 4 to 2.

After merge 1 of 6

Start: every word is a list of single letters. Total symbols: 79

low × 5
lower × 2
newest × 6
widest × 3
most frequent pairs nowcount
(e, s)9
(s, t)9
(w, e)8
(l, o)7
(o, w)7

Ties are broken alphabetically by this toy learner. Real tokenizers define their own rules.

A classic toy corpus. Step through the merges and watch the pair counts and total length change.

Predict first. In the toy symbols a, b, a, b, how often does the adjacent pair a, b occur?

Chapter context

A language model receives token IDs, not visible words. The tokenizer chooses how text becomes those IDs. Different tokenizers can represent the same string with different lengths, so character count is not a universal token count.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

In a toy merge, replacing m nonoverlapping adjacent pairs by one symbol reduces sequence length by m. A request budget must include formatted input plus requested output within the model's supported context; exact accounting is model-specific.

Worked example

Start with toy symbols ['a','b','a','b'] and a vocabulary containing a and b. The pair (a,b) occurs twice. A merge creates symbol ab and encodes the sequence as ['ab','ab'], reducing length from 4 to 2. This deliberately omits byte encoding and pre-tokenization so the merge operation is visible.

Reference code

The following example uses the Python standard library and does not call a remote service.

tokens = list('abab')
merged=[]
i=0
while i < len(tokens):
    if tokens[i:i+2] == ['a','b']:
        merged.append('ab'); i += 2
    else:
        merged.append(tokens[i]); i += 1
assert merged == ['ab','ab']
assert len(tokens)-len(merged) == 2

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

A token is not necessarily a word. A vocabulary ID is a label, not a magnitude. A hand-built toy merge sequence is not a drop-in replacement for a production tokenizer.