🤖 AI/ML

BPE

Byte Pair Encoding

An algorithm that tokenizes text into subword units. Used in the GPT series.

📖 Detailed Explanation

BPE (Byte Pair Encoding) is an algorithm that tokenizes text into subword units. It builds a vocabulary by repeatedly merging frequently occurring character pairs, and because it can represent both whole words and subword combinations, it effectively solves the OOV (Out-of-Vocabulary) problem.

It was originally developed by Philip Gage in 1994 for data compression, but after Sennrich et al. applied it to Neural Machine Translation in 2015, it became established as the standard tokenization method in the NLP field. Since then, most pretrained models, including the GPT series and BERT, have adopted BPE variants.

The core of the algorithm is frequency-based merging. It starts with every character as an individual token, finds the most frequent pair of adjacent tokens, and merges it into a new token. If this process is repeated until the desired vocabulary size is reached, frequently used words are represented as a single token and rare words as combinations of subwords.

In practice, BPE is particularly useful for multilingual models and code generation. Because new languages and technical terms are decomposed into existing subwords, completely unknown words do not occur. The GPT tokenizer uses about 50,000 BPE tokens, and an English word is broken down into 1.3 tokens on average.

💻 Code Example

# BPE 토크나이저 학습 및 사용 예제
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import Whitespace

# 1. BPE 토크나이저 생성
tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
tokenizer.pre_tokenizer = Whitespace()

# 2. 학습 데이터 준비
corpus = [
    "인공지능이 세상을 바꾸고 있습니다.",
    "머신러닝과 딥러닝은 인공지능의 핵심 기술입니다.",
    "자연어처리는 인공지능의 중요한 분야입니다.",
    "GPT는 자연어처리 모델의 대표적인 예입니다."
]

# 3. BPE 학습
trainer = BpeTrainer(
    vocab_size=1000,           # 어휘 크기
    special_tokens=["[UNK]", "[PAD]", "[CLS]", "[SEP]"],
    min_frequency=2            # 최소 빈도
)

# 파일에서 학습하는 것이 일반적이지만 예시로 직접 학습
tokenizer.train_from_iterator(corpus, trainer=trainer)

# 4. 토큰화 결과 확인
text = "인공지능은 미래의 핵심 기술이다"
output = tokenizer.encode(text)

print(f"원문: {text}")
print(f"토큰: {output.tokens}")
print(f"토큰 ID: {output.ids}")

# 5. Hugging Face GPT-2 토크나이저 사용 예
from transformers import GPT2Tokenizer

gpt2_tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

english_text = "Artificial intelligence is transforming the world."
tokens = gpt2_tokenizer.tokenize(english_text)
ids = gpt2_tokenizer.encode(english_text)

print(f"\nGPT-2 토큰화:")
print(f"원문: {english_text}")
print(f"토큰: {tokens}")
print(f"토큰 수: {len(tokens)}")

🗣️ Examples of Practical Conversations

In a discussion on LLM cost optimization

"Since API costs are billed per token, we need to understand how BPE breaks text down. English is efficient, but Korean needs 2-3 times as many tokens to express the same meaning. Let's consider using a Korean-specialized tokenizer or prompt compression techniques."

While developing a custom tokenizer

"If we use the default BPE on medical domain data, technical terms get broken down excessively. For example, if 'acetaminophen' is split into 5-6 tokens, it is hard to grasp its meaning. Try training BPE anew on a domain corpus, or consider SentencePiece's unigram model."

In a technical interview

"The difference between BPE and WordPiece is the merge criterion. BPE selects the most frequent pair, while WordPiece selects the pair that maximizes likelihood. SentencePiece can learn directly from raw text in a language-independent way, so it is better suited to multilingual models."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Mismatch Between Token Count and Semantic Units

Because BPE is frequency-based, token boundaries do not match semantic units. 'unhappiness' may be split into 'unhapp' and 'iness' rather than 'un' and 'happiness', so caution is needed in tasks where morphological analysis is important.

2
Choosing the Vocabulary Size

If the vocabulary is too small, all words are broken into small pieces and sequences become long; if it is too large, there are many rare tokens and training becomes difficult. In general, 30K-50K is appropriate, and adjustment is needed depending on the domain.

3
Multilingual Imbalance

BPE trained on an English-centric corpus tokenizes other languages inefficiently. Korean, Chinese, and Japanese use 2-4 times more tokens than English, so balanced training data is essential for multilingual services.

🔗 Related Terms

📚 Learn More