AI Logic

Tokenization

Byte-Level Tokenization (Token-Free)

Updated:

Byte-level BPE procedure. The left side shows training: Japanese training sentences are split into UTF-8 bytes and the most frequent byte pairs are merged eight times in order (producing symbols such as E3 81 that are only part of a character). The right side shows application: the same rules are applied to the 21 bytes of the Japanese sentence 深層学習を学ぶ ("learn deep learning"); 学習, を, and 学 are merged, 深層 remains as bytes, and ぶ is split into parts of a character

What Is Byte-Level Tokenization?

Byte-level tokenization is a method that treats text as a sequence of UTF-8 bytes rather than characters, and uses the 256 possible byte values as the smallest symbols. Characters from any language, as well as emoji and symbols, can always be represented as a sequence of bytes, so unknown tokens (unrecognized symbols) cannot occur in principle.

There are two main ways to use it.

  • Byte-level BPE: bytes are the initial symbols, and BPE merges are learned on top of them. Frequent byte sequences are merged into single symbols, so sequences do not get much longer. It was used by GPT-2 in 2019, and in the same year Wang et al. studied it in detail for machine translation (BBPE).
  • Token-free: bytes are not merged and are fed to the model one byte at a time. The vocabulary consists only of the 256 byte values and a few special tokens. ByT5 (2021) showed that this approach is practical even with a standard Transformer.

Ordinary BPE, which uses characters as the smallest symbols, cannot represent characters that are not in its vocabulary. In languages with many distinct characters, such as Japanese and Chinese, rarely used characters also take up vocabulary slots. Using bytes as the smallest symbols eliminates both problems. In exchange, a single symbol may represent only part of a character, and sequences tend to get longer.

Representing Text as UTF-8 Bytes

UTF-8 is an encoding that represents Unicode characters with 1–4 bytes. Alphanumeric characters take 1 byte, while most Japanese hiragana, katakana, and kanji take 3 bytes.

CharacterUTF-8 bytes (hex)Bytes
A411
学E5 AD A63
をE3 82 923
ぶE3 81 B63

(学 gaku, "learn/study"; を o, an object particle; ぶ bu, a hiragana syllable.) The Japanese sentence "深層学習を学ぶ" (shinsō gakushū o manabu, "learn deep learning") has 7 characters but 21 bytes in UTF-8. The GPT-2 report states that using Unicode characters (code points) as the smallest symbols would require a base vocabulary of over 130,000 just to represent every string, which is far too large compared with the 32,000–64,000 vocabularies commonly used with BPE. With bytes, the base vocabulary needs only 256 symbols.

In UTF-8, most hiragana begin with "E3 81" or "E3 82." When BPE is learned on bytes, this "first half of a character" becomes a single symbol shared among different characters. Wang et al. note that this saves vocabulary slots and allows symbols to be shared even between languages with different scripts.

Byte-Level BPE Procedure

Training byte-level BPE is the same as BPE, except that the initial symbols are bytes.

  1. Convert the training text into sequences of UTF-8 bytes. The initial vocabulary is the 256 byte values.
  2. Count pairs of adjacent symbols, merge the most frequent pair into a single symbol, and record it as a rule.
  3. Repeat step 2 until the vocabulary reaches the chosen size.
  4. To process new text, split it into bytes and apply the recorded rules in the same order.

The figure at the top of the article actually computes 8 merges on 8 kinds of Japanese sentences (機械学習を学ぶ "learn machine learning," 深層強化学習 "deep reinforcement learning," and so on). The example is kept in Japanese because it shows how characters that span several bytes are handled.

StepPair mergedCountResulting symbol
1E5 + AD19First part of 学 (part of a character)
2E5 AD + A619学
3E3 + 8112First part of の, ぶ, げ, etc. (part of a character)
4–6学 + E7, … + BF, … + 9211学習 (gakushū, "learning")
7E3 + 8210First part of を, る, etc. (part of a character)
8E3 82 + 928を

Applying these rules to "深層学習を学ぶ" (21 bytes), "学習," "を," and "学" are merged, but "深層" (shinsō, "deep"), which is rare in the training data, remains as six separate bytes, and "ぶ" splits into "E3 81" and "B6," for a total of 11 tokens. Every part is represented with known bytes, so no unknown symbol appears.

GPT-2's Refinement: No Merges Across Character Categories

According to the GPT-2 report, learning BPE directly on bytes put words fused with punctuation, such as "dog." "dog!" and "dog?", into the vocabulary as separate symbols, wasting the limited vocabulary slots. GPT-2 therefore prevents merges across character categories (letters, digits, punctuation, etc.). Spaces are an exception: they may be joined with the following word, which improves compression efficiency. The GPT-2 vocabulary has 50,257 entries.

Handling Symbols That Are Parts of Characters

Byte-level BPE symbols may be parts of characters, or mixtures of complete characters and partial ones. Wang et al. describe two problems this causes and how to address them.

  • Symbol meaning becomes ambiguous: "E3 81" alone does not tell which hiragana it begins. They therefore propose passing the symbol embeddings through a layer that mixes them with neighboring symbols before they enter the model (a depthwise convolution or a bidirectional GRU). Accuracy improved for every vocabulary, with the bidirectional GRU being especially effective.
  • Outputs that are not valid characters: any character can be represented as a byte sequence, but conversely, not every byte sequence forms valid characters. A model partway through training may repeat the same byte too many times. A dynamic programming algorithm is therefore used to recover as many valid characters as possible from the output byte sequence.
f(k)=max⁡t=1,2,3,4{f(k−t)+g(k−t+1,k)}f(k) = \max_{t = 1, 2, 3, 4} \bigl\{ f(k - t) + g(k - t + 1, k) \bigr\}

Here f(k)f(k) is the maximum number of characters that can be recovered from the first kk bytes, and g(i,j)g(i, j) is 1 if bytes ii through jj form a single valid character and 0 otherwise. In UTF-8, the trailing bytes of a multi-byte character cannot form a valid character on their own, so this recovery is uniquely determined. In the paper's experiments, a fully trained model rarely produced invalid output, and none was observed in an evaluation of 165,000 sentences.

How many symbols are partial characters varies greatly by language (Table 3). For English–German translation, about 4–7% of the vocabulary, but 35–51% for Japanese–English and 23–44% for 58 languages→English. The more distinct characters a language has, the more its rare characters are decomposed into byte sequences.

Token-Free: Using Bytes Directly

There is also an approach that feeds bytes to the model one at a time without merging them. Because the tokenization step itself disappears, it is called "token-free."

ByT5 (2021) is a model based on the multilingual mT5 with the following changes.

  • The SentencePiece vocabulary is dropped, and UTF-8 bytes are fed in directly with no preprocessing. The vocabulary consists only of the 256 byte values and three special tokens (padding, end of sequence, unknown).
  • The span length masked in the fill-in-the-blank pretraining is increased to an average of 20 bytes.
  • The encoder is three times as deep as the decoder (mT5 uses equal depths).

Because the vocabulary is small, the parameters previously spent on the vocabulary can be reallocated to the Transformer layers. However, sequences become longer, so inference is slower. ByT5 reports that, compared with mT5, it was about as fast to 2.6 times slower on tasks with short words, 3.7–6.4 times slower on document summarization, and 6.4–9.5 times slower on sentence classification (XNLI).

The GPT-2 report (2019) noted that byte-level language models of the time fell short of word-level models on large datasets. Byte-level BPE was used as an intermediate approach to obtain both the generality of bytes and the efficiency of word-level units.

Experimental Results

Wang et al. compare character-level BPE (hereafter BPE) with byte-level BPE (hereafter BBPE) on translation (BLEU; "+" denotes embeddings contextualized with a bidirectional GRU).

English→German (Table 5): besides English and German characters, the training data contains about 3,400 distinct characters from misaligned sentences and mixed-language sentences. In BPE, these rare characters use up vocabulary slots.

ModelVocabularyBLEUParameters
Transformer baseBBPE 2K+26.9847M
Transformer baseBBPE 4K+27.0847M
Transformer baseBPE 32K+27.4162M
Transformer bigBBPE 2K+28.78183M
Transformer bigBPE 32K+28.77215M

BBPE reached nearly the same BLEU as BPE with a vocabulary 1/8 to 1/16 the size and fewer parameters.

Japanese→English (Table 6, evaluated on KFTT, TED, and JESC combined): the Japanese–English data contains 7,900 distinct characters, but the top 2,400 account for 99.99% of the training data.

ModelByte+BBPE 4K+Char+BPE 16K+
Transformer base16.2716.8016.4317.19
Transformer big17.4619.5818.3319.14

BPE is slightly better with the small model, but BBPE scored highest with the large model.

Transfer to unseen characters (Table 8): when a BBPE model trained on 58 languages→English was transferred to Sinhala→English, whose script does not overlap at all, it scored 0.9–1.8 points higher than training from scratch. Because the vocabulary contains every byte, the model can be moved to a new language without rebuilding the vocabulary.

Practical Caveats

One token is not necessarily one character. Byte-level BPE tokens can be cut in the middle of a character. If generated text is converted to characters and displayed one token at a time, intermediate bytes may not form characters and may appear as garbled text. When displaying, buffer the bytes until they form complete characters before converting.

  • Japanese tends to produce long sequences: most Japanese characters are 3 bytes, so parts not in the vocabulary can take up to 3 tokens per character. The same content may use more tokens than English.
  • Token-free models are computationally expensive: using bytes directly makes sequences even longer. In ByT5, the slowdown at inference grew with the length of the input text.
  • Use the same tokenizer as the model: the GPT-2 vocabulary is defined together with its handling of spaces and its preprocessing that splits by character category. When using a pretrained model, use the distributed tokenizer as is.

Comparison with Other Methods

The table below compares methods from the same perspectives, focusing on the difference in the smallest symbol.

MethodSmallest symbolInitial vocabularyUnknown tokensSequence lengthMain uses
Character-level BPECharacterCharacters in the training data (thousands or more for some languages)Characters outside the vocabulary cannot be representedShortMachine translation, the original Transformer
Byte-level BPE (this article)Byte256NoneShort (slightly longer than character-level BPE)The GPT family from GPT-2 onward
Token-free (this article)Byte256 + special tokensNoneLong (1–4 times the number of characters)ByT5
Unigram language model (SentencePiece)CharacterCharacters in the training dataCharacters outside the vocabulary cannot be representedShortAvailable in SentencePiece

Rough guidelines for choosing:

  • Handle text with many languages, symbols, and emoji without unknown tokens: use byte-level BPE.
  • Keep the vocabulary small for a language with many distinct characters: use byte-level BPE and let rare characters decompose into bytes.
  • Eliminate tokenization preprocessing and gain robustness to spelling variants and typos (if slower inference is acceptable): consider a token-free model.

PyTorch example

Show code
python
# 1) Relationship between a string and its UTF-8 bytes (Japanese example: "learn deep learning")
text = "深層学習を学ぶ"
b = text.encode("utf-8")
print(len(text), len(b))                  # 7 21
print(" ".join(f"{x:02X}" for x in b))    # E6 B7 B1 E5 B1 A4 E5 AD A6 ...
print(b[:2].decode("utf-8", errors="replace"))  # cutting mid-character does not yield a valid character (a replacement character appears)

# 2) Train byte-level BPE with Hugging Face tokenizers
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers

tokenizer = Tokenizer(models.BPE())
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)  # convert to bytes before splitting
tokenizer.decoder = decoders.ByteLevel()                                    # convert bytes back to characters
trainer = trainers.BpeTrainer(
    vocab_size=8000,
    special_tokens=["<|endoftext|>"],
    initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),  # use the 256 byte values as the initial vocabulary
)
texts = ["機械学習を学ぶ", "深層強化学習"]  # in practice, pass a large amount of text
tokenizer.train_from_iterator(texts, trainer=trainer)
enc = tokenizer.encode("深層学習を学ぶ")
print(enc.tokens, enc.ids)       # tokens are shown with bytes mapped to printable characters
print(tokenizer.decode(enc.ids))  # 深層学習を学ぶ

# 3) Convert to IDs with the pretrained GPT-2 tokenizer and feed them into a PyTorch embedding layer
import torch
import torch.nn as nn
from transformers import AutoTokenizer

gpt2_tok = AutoTokenizer.from_pretrained("gpt2")  # vocabulary size 50,257
ids = gpt2_tok("深層学習を学ぶ", return_tensors="pt")["input_ids"]
print(ids.shape)  # a Japanese character often becomes several tokens
embed = nn.Embedding(len(gpt2_tok), 768)
x = embed(ids)    # (1, sequence length, 768)

# 4) Token-free (same idea as ByT5): use the byte values directly as IDs
PAD, EOS, UNK = 0, 1, 2                      # reserve the first 3 IDs for special tokens
def bytes_to_ids(s):
    return [x + 3 for x in s.encode("utf-8")] + [EOS]  # shift bytes 0–255 to IDs 3–258
byte_embed = nn.Embedding(256 + 3, 512)
y = byte_embed(torch.tensor([bytes_to_ids(text)]))  # (1, 22, 512)

FAQ

Q. What is the difference between byte-level BPE and character-level BPE?
A.

Only the initial symbols differ. Character-level BPE starts from the characters in the training data, so it cannot represent characters outside its vocabulary. Byte-level BPE starts from the 256 byte values, so it can represent any string. The merge procedure is the same. In exchange, byte-level BPE symbols can be cut in the middle of a character.

Q. Why do GPT models use so many tokens for Japanese?
A.

Most Japanese characters are 3 bytes in UTF-8, and a vocabulary learned mainly from English data contains only a few Japanese byte sequences. Parts not in the vocabulary are split into 2–3 tokens per character. A vocabulary learned from data containing plenty of Japanese merges frequently used characters and words into single tokens.

Q. Do "token-free" models really skip tokenization?
A.

It means there is no step that splits text into words or subwords. In ByT5, text is simply converted to UTF-8 bytes, and those 256 values (plus three special tokens) are fed to the model directly as IDs. No vocabulary needs to be learned and the same preprocessing works for every language, but sequences become longer, so inference is slower.

References

  1. A. Radford, J. Wu, R. Child, D. Luan, D. Amodei, and I. Sutskever, "Language Models are Unsupervised Multitask Learners," OpenAI, 2019.
  2. C. Wang, K. Cho, and J. Gu, "Neural Machine Translation with Byte-Level Subwords," Proceedings of the AAAI Conference on Artificial Intelligence, 2020.
  3. L. Xue, A. Barua, N. Constant, R. Al-Rfou, S. Narang, M. Kale, A. Roberts, and C. Raffel, "ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models," Transactions of the Association for Computational Linguistics, 2022.
  4. R. Sennrich, B. Haddow, and A. Birch, "Neural Machine Translation of Rare Words with Subword Units," ACL, 2016.