sentencepiece README

The project's README from github.com/google/sentencepiece. As one markdown file: README.md.

SentencePiece

Build C++ Build Wheels GitHub Issues PyPI - Python Version PyPI version PyPi downloads Contributions welcome License SLSA 3 Documentation

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 Thai.

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 Benchmark (SentencePiece vs. Hugging Face Fast)

Benchmark Setup

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:


License

SentencePiece is licensed under the Apache 2.0 License.

sentencepiece (google/sentencepiece)

Searching Database…

这是什么?SentencePiece 是一个快速、轻量的无监督文本分词与还原工具,专为 LLM 等神经网络文本生成系统设计,这类系统的词表大小在训练前就已固定。它以子词单元的形式实现了 BPE 和 unigram 语言模型,并且可以直接从原始句子中训练。
这是 Python 库,还是独立的命令行工具?两者都是:它的核心是一个 C++ 库,通过易用的 Python 模块提供接口,同时还带有命令行界面,用于训练和运行分词器。同一个 .model 文件可以在 C++、Python 或 Go 中使用。
我该怎么把它跑起来?用 pip 安装 Python 模块,然后基于原始句子训练一个模型,再用它把文本编码成 tokens/IDs,并解码回原始字符串。
用 Python 之外,还需要别的东西吗?如果只用 Python 流程,只需 pip install 即可。若要从源码构建 C++ 库或命令行工具,则需要改用 CMake 或 Bazel。
这是谷歌官方的产品吗?不是。README 明确说明它不是谷歌的官方产品,因此其支持和路线图遵循一般开源项目的惯例,而非官方背书。
分词时如何处理空白字符?它用元符号 ▁(U+2581)来转义空白,并将其保留在 token 序列中,因此还原时只需简单无损地拼接字符串,而不必依赖与语言相关的启发式规则。
同一个分词模型能否在 C++、Python 和 Go 之间复用?可以。生成的每个 .model 文件都是自包含的,包含全部归一化规则、词表映射和切分逻辑,因此在任何语言的绑定中都能保证分词结果完全一致。
什么是子词正则化?它指在训练过程中,对同一输入动态采样不同的子词切分方式(unigram 使用 Subword Regularization,BPE 使用 BPE-Dropout)。这样可以扩充训练数据,并使模型对拼写噪声更加稳健。
哪些语言最能从 SentencePiece 中受益?没有明确词边界的语言受益最大,例如中文、日语和泰语。SentencePiece 直接从原始文本训练,无需 Moses、MeCab、KyTea 等特定语言的预分词器。
Creator
google
Size
47.2 MB
Stars
12.1K
Age
9y
Commits · 90 Days