sentencepiece
Unsupervised text tokenizer for Neural Network-based text generation.
Top Related Projects
💥 Fast State-of-the-Art Tokenizers optimized for Research and Production
Unsupervised Word Segmentation for Neural Machine Translation and Text Generation
Facebook AI Research Sequence-to-Sequence Toolkit written in Python.
Quick Overview
SentencePiece is an unsupervised text tokenizer and detokenizer developed by Google. It implements subword units like Byte-Pair-Encoding (BPE) and unigram language model, allowing for language-independent tokenization of text for Natural Language Processing tasks.
Pros
- Language-independent: Works with any language without modification
- Subword tokenization: Handles out-of-vocabulary words effectively
- Reversible tokenization: Can reconstruct the original text from tokenized input
- Efficient: Implemented in C++ with Python and other language bindings
Cons
- Learning curve: Requires understanding of subword tokenization concepts
- Configuration complexity: Many parameters to tune for optimal performance
- Limited pre-trained models: Users often need to train their own models
- Resource-intensive: Training large models can be computationally expensive
Code Examples
- Training a SentencePiece model:
import sentencepiece as spm
spm.SentencePieceTrainer.train('--input=input.txt --model_prefix=m --vocab_size=8000')
- Tokenizing text using a trained model:
sp = spm.SentencePieceProcessor()
sp.load('m.model')
tokens = sp.encode('Hello, world!', out_type=str)
print(tokens)
- Detokenizing text:
original_text = sp.decode(tokens)
print(original_text)
- Using SentencePiece with TensorFlow:
import tensorflow as tf
import tensorflow_text as text
tokenizer = text.SentencepieceTokenizer(model=tf.io.gfile.GFile('m.model', 'rb').read())
tokens = tokenizer.tokenize(['Hello, world!'])
Getting Started
To get started with SentencePiece:
-
Install the library:
pip install sentencepiece -
Prepare your input text file (e.g.,
input.txt) -
Train a model:
import sentencepiece as spm spm.SentencePieceTrainer.train('--input=input.txt --model_prefix=m --vocab_size=8000') -
Use the trained model:
sp = spm.SentencePieceProcessor() sp.load('m.model') tokens = sp.encode('Your text here', out_type=str)
Competitor Comparisons
💥 Fast State-of-the-Art Tokenizers optimized for Research and Production
Pros of tokenizers
- Supports a wider range of tokenization algorithms and techniques
- Offers faster tokenization speeds, especially for large datasets
- Provides a more flexible and customizable API
Cons of tokenizers
- Larger library size and potentially more complex setup
- Less focus on specific Asian language support compared to SentencePiece
Code comparison
SentencePiece:
import sentencepiece as spm
sp = spm.SentencePieceProcessor()
sp.Load("model.model")
encoded = sp.EncodeAsPieces("Hello world")
tokenizers:
from tokenizers import Tokenizer
tokenizer = Tokenizer.from_file("tokenizer.json")
encoded = tokenizer.encode("Hello world")
Both libraries offer straightforward APIs for tokenization, but tokenizers provides more flexibility in terms of customization and algorithm selection. SentencePiece is particularly strong in handling Asian languages, while tokenizers excels in speed and versatility across various tokenization methods.
The choice between the two depends on specific project requirements, such as language support, tokenization speed, and the need for customization. Both libraries are actively maintained and widely used in the NLP community.
Unsupervised Word Segmentation for Neural Machine Translation and Text Generation
Pros of subword-nmt
- Simpler implementation, easier to understand and modify
- Faster training on smaller datasets
- More flexible with custom vocabularies and rare word handling
Cons of subword-nmt
- Less efficient for large-scale production use
- Limited language support compared to SentencePiece
- Lacks advanced features like regularization and sampling
Code Comparison
subword-nmt:
import re, collections
def get_stats(vocab):
pairs = collections.defaultdict(int)
for word, freq in vocab.items():
symbols = word.split()
for i in range(len(symbols)-1):
pairs[symbols[i],symbols[i+1]] += freq
return pairs
SentencePiece:
class SentencePieceProcessor {
public:
virtual bool Load(const std::string& filename);
virtual bool LoadOrDie(const std::string& filename);
virtual std::vector<std::string> Encode(const std::string& input) const;
virtual int GetPieceSize() const;
virtual const std::string& IdToPiece(int id) const;
};
Both repositories provide subword tokenization for natural language processing tasks. subword-nmt offers a more straightforward approach, making it suitable for smaller projects and experimentation. SentencePiece, developed by Google, is more robust and efficient for large-scale applications, supporting a wider range of languages and advanced features. The code snippets illustrate the difference in implementation complexity, with subword-nmt using Python and SentencePiece using C++.
Facebook AI Research Sequence-to-Sequence Toolkit written in Python.
Pros of fairseq
- Broader scope: Fairseq is a complete sequence-to-sequence modeling toolkit, while SentencePiece focuses solely on tokenization
- More advanced features: Includes state-of-the-art models for various NLP tasks, not just tokenization
- Active development: Regularly updated with new models and features
Cons of fairseq
- Steeper learning curve: More complex to use due to its broader scope and advanced features
- Heavier resource requirements: Requires more computational power and memory for training and inference
- Less specialized: May not be as optimized for tokenization-specific tasks as SentencePiece
Code comparison
SentencePiece:
import sentencepiece as spm
sp = spm.SentencePieceProcessor()
sp.load('model.model')
pieces = sp.encode('This is a test.', out_type=str)
Fairseq:
from fairseq.data.encoders.sentencepiece_bpe import SentencepieceBPE
bpe = SentencepieceBPE(args)
tokens = bpe.encode('This is a test.')
Both libraries offer tokenization functionality, but Fairseq's implementation is part of a larger toolkit with additional features and complexities.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
SentencePiece
SentencePiece is a fast, lightweight, and unsupervised text tokenizer and detokenizer designed for neural network-based text generation systems (such as Large Language Models) where the vocabulary size is fixed prior to training.
It implements subword unitsâincluding Byte-Pair-Encoding (BPE) [Sennrich et al.] and the unigram language model [Kudo.]âwith the ability to train directly from raw sentences. By treating input text as a raw sequence of Unicode characters, SentencePiece enables a purely end-to-end, language-independent pipeline that completely eliminates the need for language-specific pre- or post-processing.
This is not an official Google product.
Quick Start (Python)
SentencePiece provides an easy-to-use Python module. Install it via pip:
pip install sentencepiece
Basic Example
Here is how to train a model, encode text into tokens/IDs, and decode them back to the original string:
import sentencepiece as spm
# 1. Train a model directly from a raw text file.
# (No pre-tokenization or language-specific preprocessing required!)
spm.SentencePieceTrainer.train(
input='data/botchan.txt',
model_prefix='m',
vocab_size=1000
)
# 2. Load the trained model.
sp = spm.SentencePieceProcessor(model_file='m.model')
# 3. Encode raw text into subword pieces (strings) or vocabulary IDs (integers).
text = "I saw a girl with a telescope."
pieces = sp.encode(text, out_type=str)
ids = sp.encode(text, out_type=int)
print(f"Pieces: {pieces}")
# Output: ['âI', 'âsaw', 'âa', 'âgirl', 'âwith', 'âa', 'â', 'te', 'le', 's', 'c', 'o', 'pe', '.']
print(f"IDs: {ids}")
# Output: [9, 459, 11, 939, 44, 11, 4, 142, 82, 8, 28, 21, 132, 6]
# 4. Decode IDs or pieces back into the original text.
# The reconstruction is completely lossless and reversible!
print(sp.decode(ids))
# Output: "I saw a girl with a telescope."
print(sp.decode(pieces))
# Output: "I saw a girl with a telescope."
Why SentencePiece?
1. Reversible & Lossless Tokenization (Whitespace as a Basic Symbol)
Traditional tokenizers drop whitespace information (e.g., treating Tokenize("World.") identically to Tokenize("World .")), making detokenization ambiguous and language-dependent.
SentencePiece treats the input text as a raw sequence of Unicode characters. It escapes whitespaces with a meta-symbol â (U+2581) and includes it in the tokenization. This design ensures that detokenization is a simple, lossless string join operation, entirely independent of the language:
# Lossless detokenization
original_text = "".join(pieces).replace("â", " ")
2. Purely Data-Driven & Language-Independent
SentencePiece trains tokenization and detokenization models directly from raw sentences. It does not require language-specific pre-tokenizers (such as Moses, MeCab, or KyTea). This makes it highly effective for languages without explicit word boundaries, such as Chinese, Japanese, and Korean.
3. Subword Regularization & BPE-Dropout
To improve the robustness and accuracy of translation and language models, SentencePiece supports on-the-fly subword sampling during training. By sampling different segmentations for the same input text (Subword Regularization for Unigram, BPE-Dropout for BPE), it virtually augments your training data and makes the model more resilient to spelling variations and noise.
# Sample different segmentations on-the-fly
for _ in range(3):
print(sp.encode('New York', out_type=str, enable_sampling=True, alpha=0.1, nbest_size=-1))
# May output:
# ['â', 'N', 'e', 'w', 'âYork']
# ['âNew', 'âYork']
# ['âNew', 'âY', 'o', 'r', 'k']
4. Fast, Lightweight, and Self-Contained
- Performance: Written in highly optimized C++. Segmentation speed is around 50,000 sentences per second, with a memory footprint of only ~6MB.
- Self-Contained: The generated
.modelfile contains the entire normalization rules, vocabulary mapping, and segmentation model. You are guaranteed to get the exact same tokenization results in any environment (C++, Python, Go, etc.) as long as you use the same model file.
Performance Benchmark (SentencePiece vs. Hugging Face Fast)
Benchmark Setup
- Environment: 24-core CPU, Python 3.13.
- Dataset: Balanced raw multilingual text from FLORES-200 (parallel sentences in English, Chinese, Japanese, and Thai; 11.29 MB, 60,720 lines). CJK and Thai texts are raw and do not contain artificial space delimiters.
- Batch Request Size: The entire dataset (60,720 sentences) is fed as a single batch request (a single Python
list[str]) in one call. - Metric: Encoding throughput in MB/s (higher is better).
1. Unigram Model: T5-base (32k vocab)
| Tokenizer | 1 Thread | 2 Threads | 4 Threads | 8 Threads | 16 Threads | 24 Threads |
|---|---|---|---|---|---|---|
| SentencePiece | 27.41 | 43.83 | 71.62 | 102.08 | 123.33 | 127.60 |
| Hugging Face Fast | 3.78 | 7.15 | 12.45 | 20.33 | 27.00 | 31.49 |
2. BPE Model: Gemma 3 (256k vocab)
| Tokenizer | 1 Thread | 2 Threads | 4 Threads | 8 Threads | 16 Threads | 24 Threads |
|---|---|---|---|---|---|---|
| SentencePiece | 7.44 | 12.82 | 23.03 | 36.66 | 48.65 | 52.43 |
| Hugging Face Fast | 3.66 | 6.37 | 10.45 | 15.54 | 21.05 | 20.48 |
Why performance does not scale linearly:
While the core tokenization (C++ or Rust) runs in parallel, the final step of converting the native results (C++ vector of vectors or Rust vector of vectors) into Python objects (list[list[int]] or list[Encoding]) is sequential and must be done on Python's main thread (GIL-locked). At high thread counts, this single-threaded serialization step becomes the dominant bottleneck, capping the scaling performance.
For the detailed analysis and single-thread reference comparison, see Performance Benchmark Details.
To run these benchmarks yourself, see the reproduction instructions and scripts.
Documentation & Resources
For detailed guides, API references, and advanced usage, please refer to the following resources:
- Command Line Interface (CLI) & Build Guide
- C++ API Reference
- Python API Reference & Python Module Directory
- Python Tokenizer Comparison Cheat Sheet
- Performance Benchmark Details
- Performance Benchmark Code & Reproduction Guide
- Training Options Reference
- Text Normalization & Custom Rules
- Special Symbols & Control Tokens
- Vocabulary Piece Constraints
- Model Protobuf Schema
- Docker Deployment Guide
- NLCodec BPE Trainer (Contrib)
License
SentencePiece is licensed under the Apache 2.0 License.
Top Related Projects
💥 Fast State-of-the-Art Tokenizers optimized for Research and Production
Unsupervised Word Segmentation for Neural Machine Translation and Text Generation
Facebook AI Research Sequence-to-Sequence Toolkit written in Python.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot