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.
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.
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.
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']}")
"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
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.