🤖 AI/ML

SentencePiece

SentencePiece

A language-independent subword tokenization library. Supports BPE and Unigram algorithms. Used in BERT, T5, LLaMA, and others.

📖 Detailed Explanation

SentencePiece is a language-independent subword tokenization library developed by Google. It splits text into small meaningful units (subwords) so that models can process it efficiently. Its key feature is that it can be trained directly on raw text without "pre-tokenization."

It was published in the 2018 paper "SentencePiece: A simple and language independent subword tokenizer." Existing BPE (Byte Pair Encoding) and WordPiece were optimized for whitespace-based languages (English), but SentencePiece processes Korean, Japanese, and Chinese, which have no spaces, in the same way.

Two algorithms are supported. BPE repeatedly merges the most frequent pairs of characters, and Unigram LM finds the optimal segmentation based on probabilities. For example, "인공지능" can be split into ["▁인공", "지능"] or ["▁인", "공", "지", "능"], and ▁ indicates the position of a space.

Major LLMs such as T5, ALBERT, XLNet, LLaMA, and Gemma use SentencePiece. A vocabulary size of 32K to 100K is typical, and the larger the vocabulary, the higher the compression rate, but the larger the embedding table. It is an almost essential preprocessing tool for Korean NLP.

💻 Code Example

# SentencePiece 토큰화 예제
import sentencepiece as spm

# 1. 모델 학습 (BPE 알고리즘, 32K 어휘)
spm.SentencePieceTrainer.train(
    input='corpus.txt',           # 학습 텍스트 파일
    model_prefix='tokenizer',     # 출력 파일명
    vocab_size=32000,             # 어휘 크기
    model_type='bpe',             # 'bpe' 또는 'unigram'
    character_coverage=0.9995,    # 한국어는 0.9995 권장
    pad_id=0, unk_id=1, bos_id=2, eos_id=3
)

# 2. 학습된 모델 로드
sp = spm.SentencePieceProcessor()
sp.load('tokenizer.model')

# 3. 토큰화 (텍스트 → 토큰)
text = "인공지능이 세상을 바꾸고 있습니다."
tokens = sp.encode_as_pieces(text)
print(tokens)  # ['▁인공', '지능', '이', '▁세상', '을', '▁바꾸', '고', '▁있습니다', '.']

# 4. 토큰 → ID 변환
ids = sp.encode_as_ids(text)
print(ids)  # [1234, 5678, 23, 9012, ...]

# 5. ID → 텍스트 복원
decoded = sp.decode(ids)
print(decoded)  # "인공지능이 세상을 바꾸고 있습니다."

# 6. Hugging Face Transformers와 함께 사용
from transformers import T5Tokenizer
tokenizer = T5Tokenizer.from_pretrained('t5-base')
# T5Tokenizer는 내부적으로 SentencePiece 사용

🗣️ Say It Like This in Practice

💬 In a Korean LLM Development Meeting
"We train the Korean tokenizer with SentencePiece Unigram. If you set character_coverage to 0.9995, it covers even Hangul jamo, and a vocabulary size of 32K is enough. Unigram captures morpheme boundaries better than BPE."
💬 In an Interview
"The key point of SentencePiece is that it is language-independent. Because it trains directly on raw text without whitespace-based pre-tokenization, it can process agglutinative languages like Korean and Japanese in the same way as English. Most LLMs, such as LLaMA and T5, use it."
💬 In a Tokenizer Selection Discussion
"OpenAI uses tiktoken (BPE-based), and Google uses SentencePiece. If you want to train your own, SentencePiece is convenient, and for multilingual models, Unigram mode performs well. Choose a vocabulary size between 32K and 64K, taking into account the trade-off between compression rate and model size."

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

⚠️ Common Mistakes & Cautions

❌
Domain mismatch between training data and inference data

If you use a tokenizer trained on news for code or medical text, OOV (out-of-vocabulary) words surge. Train a tokenizer for each domain or use a mixed corpus.

❌
Setting the vocabulary size too small

If vocab_size is small, long words are split into many tokens and the sequence length increases. We recommend at least 32K for Korean and 64K or more for multilingual use.

✅
The right way

Train on a corpus similar to your actual service data, and set character_coverage to 0.9995 or higher. Compare BPE and Unigram through experiments, but for multilingual use, try Unigram first.

🔗 Related Terms

📚 Learn More