AI Logic

Tokenization

Byte Pair Encoding (BPE)

Updated:

BPE procedure. The left side shows training: words in the training data are split into characters and the most frequent pairs are merged five times in order. The right side shows application: the same rules are applied in the same order to the new word lowest, splitting it into low and est</w>

What Is BPE?

BPE (Byte Pair Encoding) is a tokenization method that splits words into subwords (parts of words) by repeatedly merging the pair of characters that most often appear next to each other in text into a single symbol. It was originally a data compression method proposed by Gage in 1994, and in 2016 Sennrich et al. adopted it as a way to split words in machine translation.

Using whole words as the vocabulary makes it hard to handle words absent from the training data (unknown words) and rare words. If the vocabulary is limited to tens of thousands of words, all remaining words become an "unknown" symbol. Conversely, splitting into single characters can represent any word, but the sequences become long and it is harder for the model to grasp meaning.

BPE sits in between. Frequent words remain single symbols, and rare words are represented by splitting them into frequent parts. For example, even if "lowest" is not in the training data, splitting it into "low" and "est" lets both be treated as known parts. Today, many language models, starting with the GPT family, use BPE or one of its variants.

Training Procedure

BPE training proceeds as follows (Section 3.2 and Algorithm 1 of the paper).

  1. Split each word in the training data into characters, and append a symbol marking the end of the word (here </w>).
    • The initial vocabulary is the set of characters.
    • Thanks to the end-of-word symbol, the positions of spaces can be restored when the symbols are joined back together later.
  2. Across all words, count the pairs of adjacent symbols, weighted by the frequency of each word.
    • Pairs that cross word boundaries are not counted.
  3. Merge the most frequent pair into a single new symbol, and record this merge as a rule.
  4. Repeat steps 2–3 a fixed number of times.

The final vocabulary size is the number of initial characters + the number of merges. The number of merges is BPE's only hyperparameter.

The left side of the figure at the top of the article computes the first five merges on the same training data as Algorithm 1 in the paper (low 5 times, lower 2 times, newest 6 times, widest 3 times).

StepPair mergedCountHow it is counted
1e + s9newest 6 times + widest 3 times
2es + t9newest 6 times + widest 3 times
3est + </w>9newest 6 times + widest 3 times
4l + o7low 5 times + lower 2 times
5lo + w7low 5 times + lower 2 times

In step 1, e + s, s + t, and t + </w> are tied at 9. The paper's program picks the pair counted first in case of a tie, so e + s is selected. After five merges, the frequent parts "est</w>" (word-final est) and "low" have each become a single symbol.

Because of the end-of-word symbol, the same "est" becomes different symbols depending on position: the word-final "est</w>" (the est in widest) and "est" in the middle of a word. Parts whose meaning or usage differs depending on whether they end a word can be learned separately.

Splitting a New Word

To split a new word, first split it into characters, then apply the merge rules recorded during training in the order they were recorded. The right side of the figure at the top of the article shows how "lowest," which is not in the training data, is split.

  1. Split into characters: l o w e s t </w>
  2. Rule 1 (e + s): l o w es t </w>
  3. Rule 2 (es + t): l o w est </w>
  4. Rule 3 (est + </w>): l o w est</w>
  5. Rule 4 (l + o): lo w est</w>
  6. Rule 5 (lo + w): low est</w>

"lowest" has been split into two parts known from the training data: "low" and "est</w>". Likewise, "lower" is split into low e r </w>. As long as no character absent from the training data appears, any word can be represented as a sequence of known symbols.

When splitting new text, the same rules as in training must be applied in the same order. If the splitting differs even slightly from the vocabulary the model was trained with, the same word becomes a different sequence of symbols and the model cannot read it correctly. When using a published model, use the tokenizer that comes with that model.

Choosing the Number of Merges

The number of merges (the vocabulary size) is chosen as a trade-off between sequence length and vocabulary size.

  • More merges: frequent words become single symbols and sequences get shorter. However, the larger vocabulary makes the embedding matrix bigger, and rare symbols get fewer chances to be learned.
  • Fewer merges: the vocabulary is smaller, but words are split more finely and sequences get longer.

For English→German translation, the paper uses 59,500 merges for BPE learned separately for the source and target languages, and 89,500 merges for BPE learned jointly on both languages (joint BPE). Joint BPE splits the same person names and the like consistently in both languages, which suits translation that copies names as is. The Transformer paper also uses a shared English–German BPE vocabulary of about 37,000 tokens.

Comparison with Other Tokenization Methods

The table below compares methods based on BPE and other subword methods from the same perspectives.

MethodHow the vocabulary is builtInitial symbolsMain uses
BPE (this article)Merge pairs in order of frequencyCharactersMachine translation, the original Transformer
Byte-level BPESame as BPE256 byte valuesThe GPT family from GPT-2 onward. No character ever becomes unknown
WordPieceMerge the pair that most increases the likelihood of the training dataCharactersBERT
UnigramStart from a large vocabulary and remove symbols with little effect on the likelihoodMany candidatesModels that use SentencePiece, such as T5
BPE-dropoutSame as BPE; merge rules are randomly skipped during training onlyCharactersBuilding models robust to variation in segmentation

SentencePiece is a tool that treats whitespace as a symbol too, and learns BPE or Unigram directly from raw text without first splitting it into words. It works even for languages such as Japanese and Chinese, which have no spaces between words.

Rough guidelines for choosing:

  • Using a published model: use that model's tokenizer as is.
  • Handling text with many languages and symbols: use byte-level BPE, which never produces unknown tokens, or SentencePiece.
  • Training a model from scratch: try BPE or Unigram, starting with a vocabulary size of a few tens of thousands.

PyTorch example

Show code
python
import re
from collections import defaultdict


def get_stats(vocab):
    """Count adjacent symbol pairs within words, weighted by word frequency (never across word boundaries)"""
    pairs = defaultdict(int)
    for word, freq in vocab.items():
        symbols = word.split()
        for i in range(len(symbols) - 1):
            pairs[symbols[i], symbols[i + 1]] += freq
    return pairs


def merge_vocab(pair, vocab):
    """Merge the pair into a single symbol in every word"""
    pattern = re.compile(r"(?<!\S)" + re.escape(" ".join(pair)) + r"(?!\S)")
    return {pattern.sub("".join(pair), word): freq for word, freq in vocab.items()}


def learn_bpe(vocab, num_merges):
    merges = []
    for _ in range(num_merges):
        pairs = get_stats(vocab)
        if not pairs:
            break
        best = max(pairs, key=pairs.get)  # On ties, pick the pair counted first
        vocab = merge_vocab(best, vocab)
        merges.append(best)
    return merges


def apply_bpe(word, merges):
    """Split a new word into characters and apply the learned merges in the same order"""
    symbols = list(word) + ["</w>"]
    for a, b in merges:
        i = 0
        while i < len(symbols) - 1:
            if symbols[i] == a and symbols[i + 1] == b:
                symbols[i:i + 2] = [a + b]
            else:
                i += 1
    return symbols


# Same training data as Algorithm 1 in the paper (space-separated symbols of each word, and its frequency)
vocab = {"l o w </w>": 5, "l o w e r </w>": 2, "n e w e s t </w>": 6, "w i d e s t </w>": 3}
merges = learn_bpe(vocab, num_merges=5)
print(merges)  # [('e', 's'), ('es', 't'), ('est', '</w>'), ('l', 'o'), ('lo', 'w')]
print(apply_bpe("lowest", merges))  # ['low', 'est</w>']
print(apply_bpe("lower", merges))   # ['low', 'e', 'r', '</w>']

# Convert the symbols to IDs and feed them into a PyTorch embedding layer
import torch
import torch.nn as nn

symbols = sorted({s for w in vocab for s in w.split()} | {a + b for a, b in merges})
to_id = {s: i for i, s in enumerate(symbols)}  # vocabulary = initial characters + merged symbols
ids = torch.tensor([[to_id[s] for s in apply_bpe("lowest", merges)]])
embed = nn.Embedding(len(symbols), 16)
print(embed(ids).shape)  # torch.Size([1, 2, 16])

FAQ

Q. Why is it called "byte pair encoding"?
A.

Because it was originally a compression method that replaced pairs of bytes (8-bit values) that often appear next to each other in the data with an unused byte. In language processing, pairs of characters or symbols are merged instead of bytes, but the name has stuck.

Q. Can BPE be used for Japanese?
A.

Yes. However, Japanese has no spaces between words, so the text is either split into words first or processed with SentencePiece, which treats whitespace as a symbol too. Because Japanese has many distinct characters, byte-level BPE, which uses bytes as the initial symbols, is also widely used.

Q. What vocabulary size is typical?
A.

Tens of thousands is a common guideline: about 60,000–90,000 in the paper's translation experiments, about 37,000 in the Transformer paper, and about 50,000 for GPT-2. Models covering more languages tend to use larger vocabularies.

References

  1. R. Sennrich, B. Haddow, and A. Birch, "Neural Machine Translation of Rare Words with Subword Units," Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (ACL), pp. 1715–1725, 2016.
  2. P. Gage, "A New Algorithm for Data Compression," C Users Journal, 12(2), 1994.
  3. A. Radford, J. Wu, R. Child, D. Luan, D. Amodei, and I. Sutskever, "Language Models are Unsupervised Multitask Learners," OpenAI, 2019.
  4. T. Kudo, "Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates," ACL, 2018.
  5. T. Kudo and J. Richardson, "SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing," EMNLP (System Demonstrations), 2018.
  6. I. Provilkov, D. Emelianenko, and E. Voita, "BPE-Dropout: Simple and Effective Subword Regularization," ACL, 2020.