Sub topic 6
Byte-level BPE and why it never needs an unknown token
This chapter assumes you know how BPE learns merges and how it applies them to new text. It also assumes you are comfortable with Python's str and bytes types and have a rough idea of what UTF-8 is. Here we change one thing about BPE, the starting alphabet, and see why that removes the out-of-vocabulary problem.
The problem with a character-level base alphabet
Standard BPE starts from characters. Every word becomes a sequence of characters, and merges build larger pieces from them. The base vocabulary is the set of characters seen in training.
Unicode defines well over 100,000 characters. Three things can go wrong:
- If you put every Unicode character in the base vocabulary, most of the vocabulary slots go to symbols that almost never occur. Rare CJK characters, historic scripts and many emoji are examples.
- If you keep only the characters seen in training, any other character at inference time has no symbol. The tokeniser must emit an unknown token such as
[UNK], and the information is lost. - If you keep only common characters and map the rest to
[UNK], you keep the same loss and also have to choose a cutoff.
Byte-level BPE avoids this choice by changing the alphabet.
The idea: start from bytes
Every string can be encoded as UTF-8, which is a sequence of bytes. Each byte is an integer from 0 to 255. Byte-level BPE runs the usual BPE algorithm on those bytes instead of characters.
- The base vocabulary is exactly 256 symbols, one per possible byte value.
- Any string, in any language, including text with unusual symbols, is a sequence of those 256 symbols.
- Merges build longer pieces from byte sequences, just as they do from characters.
Since every possible input is covered by the base alphabet, the encoder cannot fail to find a symbol. The unknown token is unnecessary for ordinary text. The worst case for a rare input is that it is split into single bytes.
UTF-8 uses 1 byte for ASCII characters, 2 bytes for many accented Latin, Greek and Cyrillic characters, 3 bytes for most CJK characters, and 4 bytes for emoji and rare characters. So é is two base symbols, and a rare emoji is four, before any merges apply.
Making bytes printable
Merge files and vocabulary files are usually text, so each of the 256 bytes needs a visible character. Bytes such as 0x0A (newline) or 0x00 would be hard to read and could be mangled by text tools.
GPT-2's tokeniser maps each byte to a printable Unicode character:
- Bytes that already correspond to printable characters (
!to~,¡to¬,®toÿ) map to themselves. - The remaining bytes, including space, newline and control characters, are assigned characters starting at code point 256.
This is why GPT-2 style vocabularies show Ġ where you expect a space. The space byte 0x20 is the 33rd byte that cannot map to itself, so it receives code point 256 + 32 = 288, which is Ġ. This is a cosmetic mapping. It is a reversible one-to-one relabelling of the bytes and does not change how the algorithm works.
A runnable implementation
The code below builds the byte-to-character table, converts text to base symbols, applies an ordered merge list, and decodes back. The merges are written by hand so the trace is easy to follow. In a real tokeniser they come from training, as in the BPE training chapter.
def bytes_to_unicode():
# Printable bytes map to themselves; the rest go to code points 256+.
bs = (list(range(ord("!"), ord("~") + 1))
+ list(range(ord("¡"), ord("¬") + 1))
+ list(range(ord("®"), ord("ÿ") + 1)))
cs = bs[:]
n = 0
for b in range(256):
if b not in bs:
bs.append(b)
cs.append(256 + n)
n += 1
return dict(zip(bs, map(chr, cs)))
byte_to_char = bytes_to_unicode()
char_to_byte = {c: b for b, c in byte_to_char.items()}
assert len(byte_to_char) == 256 and len(char_to_byte) == 256
def to_symbols(text):
return [byte_to_char[b] for b in text.encode("utf-8")]
def apply_merges(symbols, merges):
rank = {pair: i for i, pair in enumerate(merges)}
symbols = list(symbols)
while len(symbols) > 1:
pairs = [(symbols[i], symbols[i + 1]) for i in range(len(symbols) - 1)]
best = min(pairs, key=lambda p: rank.get(p, float("inf")))
if best not in rank:
break
out = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == best:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
symbols = out
return symbols
def decode(pieces):
data = bytes(char_to_byte[c] for piece in pieces for c in piece)
return data.decode("utf-8", errors="replace")
# "é" is the two bytes 0xC3 0xA9, shown as the characters "Ã" and "©".
merges = [("Ã", "©"), ("f", "é"), ("c", "a")]
tokens = apply_merges(to_symbols("café"), merges)
print(tokens) # ['ca', 'fé']
print(decode(tokens)) # café
emoji = to_symbols("😀")
print(len(emoji)) # 4 base symbols, no merges apply
assert decode(apply_merges(emoji, merges)) == "😀"The trace for café goes as follows:
- The UTF-8 bytes are
63 61 66 C3 A9. They become the base symbolsc a f à ©. - Merge rank 0 joins
Ãand©, givingc a f é. - Merge rank 1 joins
fandé, givingc a fé. - Merge rank 2 joins
canda, givingca fé.
The emoji has no merges, so it stays as four single-byte symbols. Decoding still reproduces it exactly.
What it does and does not guarantee
The table below separates what byte-level BPE removes from what remains.
| Concern | Character-level BPE | Byte-level BPE |
|---|---|---|
| Base vocabulary size | Thousands of characters, depends on data | Exactly 256 |
| Unseen character at inference | `[UNK]` or error | Split into bytes |
| Round trip text to ids to text | Lossy if `[UNK]` appears | Exact for any valid UTF-8 |
| Tokens for rare scripts | Often one per character | Often 2 to 4 per character |
| Visible pieces | Readable characters | May be partial characters |
Edge cases and gotchas
Pieces can split a character
Merges are learned from byte frequencies. A merge can join the first byte of one character with the last byte of the previous one, or stop partway through a multi-byte character. A single token can therefore be an invalid UTF-8 fragment.
This matters when you stream generated tokens one at a time and decode each one separately. The first two bytes of a three-byte character decode to garbage or a replacement character. Decode the accumulated bytes and only emit text once they form complete characters.
Pre-tokenisation still matters
GPT-2 style tokenisers first split text with a regular expression into chunks such as words, numbers and punctuation runs. BPE merges are then applied inside each chunk only. Without this step, the most frequent pairs would join across word boundaries and across character classes, for example a word's last letter and a following comma. The byte-level change affects the alphabet, not this step.
Unicode normalisation is still your decision
Byte-level BPE is faithful to whatever bytes you give it. é can be written as one code point (U+00E9) or as e plus a combining accent (U+0065 U+0301). These have different bytes, so they tokenise differently. If you want them treated the same, normalise (for example to NFC) before tokenising, and do it identically in training and inference.
Sequence length grows for some languages
The 256-symbol base and the learned merges are both shaped by the training corpus. If the corpus was mostly English, English words get long merged tokens while Thai or Hindi text stays near the byte level. The same sentence content can then take several times more tokens. This affects context-window usage, cost and speed, and it is a main topic of the vocabulary size and multilingual pitfalls chapters.
Special tokens are separate
Tokens such as <|endoftext|> are not made of bytes by merging. They are added to the vocabulary as whole entries and matched before BPE is applied. If a user's text happens to contain the same string, your library may or may not treat it as the special token. Check the setting that controls this, because it can be a prompt-injection issue.
Related approach: byte fallback
SentencePiece offers a different way to reach the same guarantee. With byte_fallback=True, the vocabulary adds 256 byte tokens such as <0x0A>. The model works with characters or pieces as usual, and uses byte tokens only for characters it has no piece for. Common text stays readable and compact, and rare characters still never become unknown. The trade-off is that the vocabulary mixes two kinds of unit, whereas byte-level BPE is uniform.
Summary of the decision
Choose byte-level BPE when you must handle arbitrary, messy input, such as web text, code, user messages and many languages, and you want a guarantee that encoding never fails. Accept the cost: pieces are not always readable, and languages underrepresented in training use more tokens.
Exercise
Using the byte-to-character table above, the character "ñ" is U+00F1. (a) How many base symbols does it become in byte-level BPE, and why? (b) Why can a byte-level tokeniser still decode a token stream into text containing a replacement character even though it never emits an unknown token?
Show answer
(a) UTF-8 encodes U+00F1 as the two bytes C3 B1, so it becomes two base symbols (shown as "Ã" and "±"). (b) A token can hold only part of a multi-byte character, and a token sequence cut off mid-character, or merged across a character boundary, produces bytes that are not valid UTF-8. Decoding them with errors="replace" gives the replacement character. The tokeniser never lacked a symbol for any input byte, so no unknown token was needed, but not every sequence of ids is valid UTF-8.
Exercise
A tokeniser's merge list is [("a", "b"), ("ab", "c")] and the base symbols are single characters. Apply the merges, in order, to "cabc" and then to "abcab". Give the final tokens for each.
Show answer
For "cabc", the symbols are c a b c. Merge 0 joins a and b, giving c ab c. Merge 1 needs "ab" followed by "c", which is present, giving c abc. Final tokens: ["c", "abc"]. For "abcab", the symbols are a b c a b. Merge 0 joins both "a b" pairs, giving ab c ab. Merge 1 joins the first "ab" with "c", giving abc ab. Final tokens: ["abc", "ab"].