πŸ€– AI/ML

Tokenizer

Tokenizer

An NLP preprocessing tool that splits text into tokens. Uses various algorithms such as BPE, WordPiece, and SentencePiece to convert text into a sequence of numeric IDs that a model can process.

πŸ“– Detailed Explanation

A tokenizer is the first step of natural language processing (NLP), converting raw text into a form that a model can understand. It goes through the process of text -> tokens -> token IDs, and when the model produces output, it decodes in reverse: token IDs -> tokens -> text. Each language model is tied to the specific tokenizer used during its training.

The most widely used tokenization algorithms in modern NLP are subword-based. BPE (Byte Pair Encoding) builds a vocabulary by repeatedly merging the most frequent pairs of characters. The GPT family uses it. WordPiece is used in BERT and is similar to BPE, but decides merges based on likelihood. Unigram is a method that starts with a large vocabulary and removes tokens with low probability.

SentencePiece is a language-independent tokenizer developed by Google that handles whitespace by replacing it with a special character (_). This allows languages without spaces, such as Japanese and Chinese, to be processed consistently. Many modern models, such as LLaMA and T5, have adopted SentencePiece. It is particularly effective for multilingual models.

The choice of tokenizer has a direct impact on model performance. A larger vocabulary size reduces the OOV (Out of Vocabulary) problem but increases the model size. Conversely, a smaller vocabulary splits the same text into more tokens. Recently, tiktoken (OpenAI) and the Hugging Face tokenizers library provide fast tokenization, and tokenizers, which is implemented in Rust, is tens of times faster than the traditional Python implementation.

πŸ’» Code Example

This is an example showing various tokenizer algorithms and how to use them.

from transformers import AutoTokenizer
import tiktoken

# =============================================
# 1. Hugging Face AutoTokenizer (λ‹€μ–‘ν•œ λͺ¨λΈ 지원)
# =============================================

# GPT-2 ν† ν¬λ‚˜μ΄μ € (BPE)
tokenizer_gpt2 = AutoTokenizer.from_pretrained("gpt2")

# BERT ν† ν¬λ‚˜μ΄μ € (WordPiece)
tokenizer_bert = AutoTokenizer.from_pretrained("bert-base-uncased")

# LLaMA ν† ν¬λ‚˜μ΄μ € (SentencePiece)
tokenizer_llama = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

text = "Hello, how are you doing today?"
text_ko = "μ•ˆλ…•ν•˜μ„Έμš”, 였늘 기뢄이 μ–΄λ– μ„Έμš”?"

# ν† ν¬λ‚˜μ΄μ € 비ꡐ
print("=== μ˜μ–΄ ν…μŠ€νŠΈ 토큰화 비ꡐ ===")
for name, tok in [("GPT-2", tokenizer_gpt2), ("BERT", tokenizer_bert)]:
    tokens = tok.tokenize(text)
    ids = tok.encode(text)
    print(f"{name}: {len(tokens)} 토큰")
    print(f"  토큰: {tokens}")
    print(f"  ID: {ids}")
    print()


# =============================================
# 2. tiktoken (OpenAI λͺ¨λΈμš© - 맀우 빠름)
# =============================================

# GPT-4용 ν† ν¬λ‚˜μ΄μ €
enc = tiktoken.encoding_for_model("gpt-4")

# λ˜λŠ” 인코딩 직접 μ§€μ •
enc_cl100k = tiktoken.get_encoding("cl100k_base")  # GPT-4, ChatGPT

# 토큰화
tokens = enc.encode(text_ko)
print(f"tiktoken (GPT-4): {len(tokens)} 토큰")
print(f"  토큰 ID: {tokens}")
print(f"  λ””μ½”λ”©: {enc.decode(tokens)}")

# κ°œλ³„ 토큰 확인
print("  κ°œλ³„ 토큰:")
for token_id in tokens:
    token_bytes = enc.decode_single_token_bytes(token_id)
    print(f"    {token_id} β†’ {token_bytes}")


# =============================================
# 3. μ»€μŠ€ν…€ ν† ν¬λ‚˜μ΄μ € ν•™μŠ΅ (Hugging Face tokenizers)
# =============================================
from tokenizers import Tokenizer, models, trainers, pre_tokenizers

# BPE ν† ν¬λ‚˜μ΄μ € 생성
tokenizer = Tokenizer(models.BPE(unk_token="[UNK]"))
tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()

# ν•™μŠ΅ 데이터 (μ‹€μ œλ‘œλŠ” λŒ€μš©λŸ‰ μ½”νΌμŠ€ μ‚¬μš©)
training_data = [
    "인곡지λŠ₯은 미래λ₯Ό λ°”κΏ€ κ²ƒμž…λ‹ˆλ‹€.",
    "λ¨Έμ‹ λŸ¬λ‹κ³Ό λ”₯λŸ¬λ‹μ€ 인곡지λŠ₯의 핡심 κΈ°μˆ μž…λ‹ˆλ‹€.",
    "μžμ—°μ–΄ μ²˜λ¦¬λŠ” ν…μŠ€νŠΈλ₯Ό μ΄ν•΄ν•˜λŠ” κΈ°μˆ μž…λ‹ˆλ‹€.",
]

# μž„μ‹œ νŒŒμΌμ— μ €μž₯
with open("train_data.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(training_data))

# ν† ν¬λ‚˜μ΄μ € ν•™μŠ΅
trainer = trainers.BpeTrainer(
    vocab_size=1000,
    special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]
)
tokenizer.train(["train_data.txt"], trainer)

# ν•™μŠ΅λœ ν† ν¬λ‚˜μ΄μ € ν…ŒμŠ€νŠΈ
output = tokenizer.encode("인곡지λŠ₯ 기술")
print(f"μ»€μŠ€ν…€ ν† ν¬λ‚˜μ΄μ €: {output.tokens}")


# =============================================
# 4. 특수 토큰 처리
# =============================================
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

# 특수 토큰 확인
print(f"[CLS] ID: {tokenizer.cls_token_id}")
print(f"[SEP] ID: {tokenizer.sep_token_id}")
print(f"[PAD] ID: {tokenizer.pad_token_id}")
print(f"[MASK] ID: {tokenizer.mask_token_id}")

# λ¬Έμž₯ 쌍 토큰화 (BERT μŠ€νƒ€μΌ)
encoded = tokenizer(
    "첫 번째 λ¬Έμž₯μž…λ‹ˆλ‹€.",
    "두 번째 λ¬Έμž₯μž…λ‹ˆλ‹€.",
    padding="max_length",
    max_length=32,
    truncation=True,
    return_tensors="pt"
)

print(f"input_ids: {encoded['input_ids']}")
print(f"attention_mask: {encoded['attention_mask']}")
print(f"token_type_ids: {encoded['token_type_ids']}")

πŸ—£οΈ Say It Like This in Practice

"This model uses a SentencePiece tokenizer, so its efficiency for Korean is a bit better."

β†’ Explains that SentencePiece-based tokenizers are advantageous for multilingual use

"The tokenizer's vocab size is 32k, so there probably won't be many OOV issues."

β†’ Explains that the vocabulary size is large enough, so the out-of-vocabulary (OOV) problem is minor

"If you use tiktoken, token counting is incredibly fast."

β†’ Mentions the performance advantage of the Rust-based tiktoken library

⚠️ Common Mistakes & Cautions

Mismatch between model and tokenizer

Using a tokenizer different from the model's will produce garbled results. Be sure to use the tokenizer that was trained together with the model.

Padding direction mistake

GPT-family models use left padding, and BERT-family models use right padding. The wrong padding direction causes performance degradation.

Missing special tokens

BERT requires the [CLS] and [SEP] tokens. Calling encode() directly without special tokens greatly degrades model performance.

Long text truncation (Truncation)

Text is truncated when it exceeds max_length. If important information is located toward the end, it may be lost, so choose your truncation strategy carefully.

πŸ”— Related Terms

πŸ“š Learn More