๐Ÿงญ Roadmap
Difficultyโญโญโญ / 5 โฑ Read time60 minutes tokenizationsentencepiecemultilingual

๐ŸŒ 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

  1. Language-Agnostic - No preprocessing needed
  2. Reversible - Perfect text reconstruction
  3. Flexible - Supports BPE, Unigram algorithms
  4. Production-Ready - Fast C++ implementation
  5. 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
๐Ÿ“š Further Reading

Next: 01.d Multilingual - Learn about multilingual tokenization challenges