Byte-level BPE tokenizer

×

UTF-8 bytes are mapped to reversible Unicode symbols, then adjacent symbols are merged by the rank of their pair into vocabulary tokens.

Why

Any string. The authors want a general language model to compute the probability of any string, and to generate any string. Lowercasing, tokenization and out-of-vocabulary tokens, which large language models of the time applied first, restrict the strings a model can handle. UTF-8 bytes cover every string, yet byte-level models trailed word-level ones, on the One Billion Word Benchmark and in the authors’ own attempts on WebText. GPT-2 paper §2.2, p. 4

BPE on bytes. Byte Pair Encoding sits between characters and words: frequent symbol sequences become word-level tokens, infrequent ones fall back to character-level pieces. Reference implementations often work on Unicode code points, and covering all of Unicode would take a base vocabulary of over 130,000 before any merge, against the 32,000 to 64,000 tokens usual for BPE. On bytes the base vocabulary is 256. GPT-2 paper §2.2, p. 4

Categories. Applied directly to bytes, BPE’s greedy, frequency-based merges gave a common word such as dog many versions, as in dog. dog! dog?, which the authors call a sub-optimal allocation of limited vocabulary slots and model capacity. So merges never cross character categories. Spaces are the exception, which the authors say improves compression significantly with little fragmentation of words across tokens. GPT-2 paper §2.2, p. 4

Since the model can assign a probability to any Unicode string, the authors can evaluate it on any dataset regardless of pre-processing, tokenization or vocabulary size. GPT-2 paper §2.2, p. 4

out
[B batch, T positions]
Explanation

The encoder splits text with a regular expression, converts each piece to UTF-8 bytes and maps each byte to a reversible Unicode symbol; BPE then merges adjacent symbols by rank, and each resulting piece is looked up in the vocabulary (encoder.py 96–101). The family vocabulary contains 50,257 available token IDs.

The byte alphabet covers every UTF-8 string, so any text encodes without an unknown token. This example illustrates the transformation.

1 · text2 · 14 UTF-8 bytes3 · ranked merges for “tokenizing”tokenizing ✧brighter = above 127tokenizing(e,n) → entokenizing(t,o) → totokenizing(to,k) → toktokenizing(tok,en) → tokentokenizing…until no ranked pair is left
Illustrative merges for “tokenizing”; the space and ✧ are omitted from the merge rows. Highlighted pieces are combined by the rule below each row. Ranked merges can produce word fragments or whole words; the checkpoint’s vocabulary and ranks determine its tokens.
Sources

In codeEncoder.encode(text)

Open pinned code ↗

Direct evidence

The pinned configuration supplies the family vocabulary size.

config.json $ ↗ · openai-community/gpt2 @ 607a30d783df

Original Python encoder shipped with the released checkpoints.

encoder.py 96–101 ↗ · openai/gpt-2 @ 9b63575ef427

Excerpt
    def encode(self, text):
        bpe_tokens = []
        for token in re.findall(self.pat, text):
            token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
            bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
        return bpe_tokens

The maintained tokenizer configures byte-level pre-tokenization and decoding with the released vocabulary and merges.

tokenization_gpt2.py 107–120 ↗ · huggingface/transformers @ 71c6f699ac9b

Excerpt
        self._vocab = vocab if vocab is not None else {}
        self._merges = merges or []
        self._tokenizer = Tokenizer(
            BPE(
                vocab=self._vocab,
                merges=self._merges,
                dropout=None,
                continuing_subword_prefix="",
                end_of_word_suffix="",
                fuse_unk=False,
            )
        )
        self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
        self._tokenizer.decoder = decoders.ByteLevel()