
Source: Jonathan Kernes on medium.com
Introduction
How do you handle an unknown word in NLP? In naive systems, you might see the dreaded <unk> token whenever a new or rare word appears. Meanwhile, purely character-level tokenization can explode sequence lengths and obscure higher-level semantic information. That’s why subword tokenization has emerged as a go-to solution in modern NLP pipelines, striking a balance between word-level and character-level representations.
So far, you may have explored Byte Pair Encoding (BPE) and WordPiece, the two widely adopted subword methods. But there’s another powerful tool: SentencePiece. Developed by Google and introduced by Taku Kudo (2018), SentencePiece takes a language-agnostic view of tokenization, dispensing with the notion of “words” altogether and treating the text as a continuous stream of characters. This approach proves especially valuable for languages that lack clear word boundaries (like Japanese or Chinese), while also supporting robust domain adaptation and multilingual tasks.
- Dive into the origins and core principles of SentencePiece
- Explain how it differs from (and often complements) BPE and WordPiece
- Demonstrate its main subword algorithm, the Unigram Language Model and other available modes
- Provide practical examples of how to train and use SentencePiece, with tips on domain and multilingual scenarios
- Offer infographic suggestions for visualizing SentencePiece’s key concepts
By the end, you’ll see how SentencePiece can help you tokenize text in a universal, language-agnostic manner, and why it’s widely considered a new frontier in subword tokenization.
Visual Overview: Understanding Tokenization Methods
Before diving deep into SentencePiece, let’s visualize how different tokenization methods work:

Source: ByteByteGo
Historical Perspective & Core Principles
Origins
SentencePiece emerged from Google’s efforts to handle languages like Japanese and Korean, which don’t neatly separate words with whitespace. Traditional tokenizers that rely on spaces or dictionary-based morphological analyzers can be cumbersome or inaccurate for such writing systems. Taku Kudo and colleagues proposed a statistical approach called the Unigram Language Model, packaged in a library called “SentencePiece,” which quickly gained traction within Google’s Neural Machine Translation (NMT) projects.
Once SentencePiece was open-sourced, the broader NLP community adopted it for a wide variety of tasks, including language modeling, text classification, and domain adaptation. The key design philosophy is that all input text including whitespace should be viewed as a raw sequence of characters, with no language-specific assumptions baked into the tokenizer.
Key Innovations
- Language-Agnostic: SentencePiece avoids the notion of “word.” Instead, it introduces a special symbol (like ▁) to represent whitespace boundaries within a string of characters.
- Unigram LM: Instead of merging pairs (BPE) or incremental merges (WordPiece), SentencePiece typically uses a Unigram Language Model approach, starting with a large pool of candidate subwords and pruning those that do not contribute significantly to the overall likelihood of the training data.
- Subword Regularization: A concept allowing multiple valid segmentations during training, thus improving the robustness of NLP models to morphological or domain variations.
Why It Matters
By lifting constraints about whitespace tokenization, SentencePiece becomes ideal for multilingual or non-whitespace languages. It also centralizes the subword learning process in a single toolkit, letting you choose between Unigram or BPE modes, experiment with vocab sizes, or adopt subword regularization features.
Inside SentencePiece: Unigram LM vs. BPE Mode
Unigram Language Model
The Unigram LM approach is the cornerstone of SentencePiece. Here’s how it works:
Large Initial Subword Set: SentencePiece scans the corpus and proposes a large number of potential subwords (e.g., 100k).
Language Model Scoring: Each subword is assigned a probability based on how frequently it appears in the training corpus and its contribution to the overall likelihood.
Pruning: Subwords that don’t contribute meaningfully to the overall likelihood are removed iteratively, until the vocabulary meets the target size (e.g., 8k, 16k, 32k).
Key Difference from BPE/WordPiece: Unlike BPE and WordPiece which build vocabulary incrementally through merging, Unigram LM starts with a large candidate set and removes subwords iteratively. This allows it to explore multiple valid segmentations of the same string, making the final solution potentially more robust to varied text.
Algorithm Details: The Unigram LM uses Expectation-Maximization (EM) to iteratively refine subword probabilities and prune the vocabulary. It calculates the likelihood of each possible segmentation and removes subwords that contribute least to the overall corpus likelihood.

Source: AIML.com Research
BPE Mode
Interestingly, SentencePiece also supports a BPE-like mode. If your workflow or organization is already comfortable with BPE merges, you can switch SentencePiece to BPE while still benefiting from:
- Language-agnostic text handling (no reliance on whitespace)
- A unified environment for training and applying the tokenizer
This flexibility makes SentencePiece a one-stop shop for many subword strategies.
Subword Regularization
One unique feature is Subword Regularization, introduced by Kudo (2018). During training, SentencePiece can randomly sample from multiple possible segmentations for each sentence, teaching the model to handle morphological or domain variability more gracefully. This technique helps prevent overfitting to a single tokenization pattern and improves model robustness.
How it works: Instead of always using the most likely segmentation, SentencePiece samples from the top-k most probable segmentations according to their likelihood scores. This introduces controlled randomness that helps the model generalize better to unseen text patterns.
Comparing SentencePiece with BPE and WordPiece
Tokenization Workflow
- BPE: Iteratively merges the most frequent pairs of tokens (initially characters)
- WordPiece: Somewhat similar to BPE, but often integrated with a likelihood or partial language-model approach (e.g., in BERT)
- SentencePiece (Unigram): Starts with a large subword set and prunes subwords that don’t contribute significantly to corpus likelihood like an inverse approach to BPE’s incremental merges
Whitespace & Scripts
BPE/WordPiece typically assume you’ve split on whitespace for English or similar languages.
SentencePiece treats whitespace as a character in a raw stream, marking it with a symbol (▁) so it can handle languages without whitespace boundaries (Japanese, Chinese). This is also beneficial for multilingual corpora with diverse text segmentation rules.
Vocabulary Stability
BPE can produce re-tokenization inconsistencies if merges overlap. WordPiece can too.
Unigram LM still can yield multiple valid segmentations, but that’s often a feature (when subword regularization is enabled).
In practical usage, the differences might be subtle on large English corpora, but become more apparent in low-resource or non-Latin languages.
Real-World Usage
- Google uses SentencePiece extensively in NMT pipelines, especially for languages with complex scripts
- Many open-source frameworks (Hugging Face, Fairseq, etc.) provide easy SentencePiece integrations, reflecting its growing popularity
Hands-On with SentencePiece
Training a SentencePiece Model
import sentencepiece as spm
# Suppose you have a text file 'train_data.txt' containing your corpus
spm.SentencePieceTrainer.Train(
'--input=train_data.txt '
'--model_prefix=my_spm '
'--vocab_size=8000 '
'--model_type=unigram '
'--character_coverage=0.9995 '
'--pad_id=0 --unk_id=1 --bos_id=2 --eos_id=3'
)The model_type can be set to bpe if you want BPE merges instead of unigram.
character_coverage helps define how many characters are included for languages with large alphabets (e.g., Japanese).
Encoding/Decoding
sp = spm.SentencePieceProcessor()
sp.Load("my_spm.model")
text = "Hello, SentencePiece!"
pieces = sp.EncodeAsPieces(text)
ids = sp.EncodeAsIds(text)
print("Pieces:", pieces)
print("IDs:", ids)
recovered_text = sp.DecodePieces(pieces)
print("Recovered:", recovered_text)Notice how spaces become a special symbol like ▁ in the output subwords.
Potential Experiments
- Tweak vocab_size to see how splitting changes
- Try –model_type=unigram vs. –model_type=bpe
- Test on multiple languages or specialized domain data
Using SentencePiece in your projects often involves just a few lines of code, especially if you rely on the spm.SentencePieceTrainer CLI or the Python API.
Domain & Multilingual Considerations
Multilingual Scenarios
Many modern multilingual models (e.g., mBART, mT5) rely on SentencePiece because:
- No Whitespace Dependency: Perfect for languages that lack spaces or use them inconsistently
- Unified Vocabulary: You can train a joint subword vocabulary on multiple languages, letting the model handle shared tokens for cognates or overlapping scripts
However, a single multilingual vocab can sometimes lead to over-splitting for low-resource languages if the merges favor more common languages in the training set.
Domain Shifts
General-purpose corpora like Wikipedia might not contain domain-specific expressions (medical, legal, scientific jargon). If you plan to parse or generate text in a specialized area, consider:
- Domain Fine-Tuning: Additional training on a domain corpus (e.g., biomedical text)
- Subword Regularization: Let the model see multiple tokenization variants, making it more resilient to morphological differences
SentencePiece’s Unigram LM or BPE mode can handle new words by sub-splitting them, but domain adaptation typically yields better performance and fewer partial subwords.
Strengths, Pitfalls, and Best Practices
Strengths
- Language-Agnostic: Doesn’t assume whitespace or pre-tokenized words. Suitable for any script
- Unigram LM: Often leads to stable subword sets that maximize corpus likelihood
- Subword Regularization: A unique advantage for morphological or domain robustness
- Single Toolkit: Can do both unigram and BPE style merges versatile for different research or production needs
Pitfalls
- Complex or Large Corpora: Generating an initial set of all possible subwords can be memory-intensive for massive corpora, especially if you set vocab_size very high
- Detokenization: The ▁ marker (underscore-like) for space can cause confusion. Tools are needed to map it back to normal whitespace
- Over/Under Splitting: If vocab_size is too small, you might see excessive subword fragmentation. If it’s too large, you might store many rarely used merges
Best Practices
- Tune Vocab Size: Common values range from ~8k to 64k, depending on data size and domain complexity
- Evaluate OOD Performance: Test your tokenizer on text that might differ from the training domain to gauge subword coverage
- Consider Subword Regularization: Especially if your data is noisy or morphological variants are common
- Leverage CLI Tools: SentencePiece offers a robust command-line interface for quick experiments without writing custom code
Conclusion & Future Directions
SentencePiece stands as a new frontier in subword tokenization, offering a language-agnostic, flexible, and multilingual-friendly approach. While BPE and WordPiece have become staples in Transformer-based NLP, SentencePiece’s Unigram LM method introduces valuable features like subword regularization and fully raw-text processing. This eliminates many edge cases around whitespace or script segmentation, particularly in languages like Chinese, Japanese, or Thai.
Comparisons to BPE and WordPiece reveal that each method has pros and cons: BPE merges can be simpler to reason about, WordPiece integrates well with certain model frameworks (like BERT), and SentencePiece excels with multi-script data or domain-specific adaptation. In practice, the optimal choice often depends on your language mix, dataset size, and performance requirements.
Looking ahead, some researchers are exploring token-free or continuous representations that bypass subword dictionaries entirely. Nevertheless, SentencePiece remains a practical, proven toolkit for subword tokenization especially if you want a single approach that supports Unigram, BPE, and flexible regularization. If you’re building NLP models across diverse languages or specialized domains, give SentencePiece a try it might just simplify your tokenization pipeline and improve downstream performance.
Videos
- This video provides a deep dive into various tokenization methods such as byte pair encoding, tiktoken, sentencepiece, and their practical applications. (Total video runtime: 2 hrs 13 mins, Sentencepiece starts at 1 hr 27 mins)
- This video titled, “LLM Tokenizers Explained: BPE Encoding, WordPiece and SentencePiece”, by DataMListic, talks about all the three tokenizers that are commonly used when training large language models: (1) the byte-pair encoding tokenizer, (2) the wordpiece tokenizer and (3) the sentencepiece tokenizer. (Runtime: 5 mins)
References & Further Reading
- Kudo, T. (2018). “Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates.” ACL.
- Kudo, T. & Richardson, J. (2018). “SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing.” EMNLP (Demonstration).
- SentencePiece GitHub: https://github.com/google/sentencepiece
- Hugging Face Tokenizers: https://github.com/huggingface/tokenizers (for further integration ideas)

