๐ SentencePiece - Language-Agnostic Tokenization
Used by: T5, XLNet, ALBERT, mT5, LLaMA, and most multilingual models
๐ฏ Why SentencePiece?
The Problem with Traditional Tokenizers
English: "Hello world" โ ["Hello", "world"] โ
(spaces separate words)
Chinese: "ไฝ ๅฅฝไธ็" โ ["ไฝ ๅฅฝไธ็"] โ (no spaces!)
Japanese: "ใใใซใกใฏไธ็" โ ["ใใใซใกใฏไธ็"] โ (no spaces!)
Traditional tokenizers need language-specific rules.
SentencePiece: Treats everything as raw bytes โ Works for ALL languages!
SentencePiece Advantages
- Language-Agnostic - No preprocessing needed
- Reversible - Perfect text reconstruction
- Flexible - Supports BPE, Unigram algorithms
- Production-Ready - Fast C++ implementation
- Multilingual - Single model for all languages
๐ฌ How SentencePiece Works
Core Principles
1. Treat input as raw byte sequence
2. Add โ character to mark word boundaries
3. Train subword model (BPE or Unigram)
4. Tokenize without preprocessing
Visual Example
Traditional:
"Hello world" โ Pre-tokenize โ ["Hello", "world"] โ Tokenize
SentencePiece:
"Hello world" โ "โHelloโworld" โ ["โHello", "โworld"]
(โ = space marker)
๐ป SentencePiece in Practice
Training a Model
import sentencepiece as spm
# Train model
spm.SentencePieceTrainer.train(
input='corpus.txt',
model_prefix='m',
vocab_size=1000,
model_type='bpe', # or 'unigram'
character_coverage=0.9995,
)
Using the Model
import sentencepiece as spm
sp = spm.SentencePieceProcessor()
sp.load('m.model')
text = "Hello world! ไฝ ๅฅฝไธ็"
tokens = sp.encode_as_pieces(text)
ids = sp.encode_as_ids(text)
print(f"Tokens: {tokens}")
print(f"IDs: {ids}")
๐ฏ SentencePiece vs Others
| Feature | BPE | WordPiece | SentencePiece |
|---|---|---|---|
| Preprocessing | Required | Required | None |
| Languages | English-focused | English-focused | All languages |
| Reversible | No | No | Yes |
| Speed | Fast | Medium | Very Fast |
๐ Related Concepts
- 01.a BPE - BPE algorithm
- 01.b WordPiece - WordPiece algorithm
- 01.d Multilingual - Multilingual challenges
๐ Further Reading
- ๐ SentencePiece Paper
- ๐ง SentencePiece GitHub
Next: 01.d Multilingual - Learn about multilingual tokenization challenges
