Sentencepiece

orchestra-research/ai-research-skills/02-tokenization/sentencepiece

作者 orchestra-research773a52944ba4MIT13K 个星标收录于 2026年10月8日更新于 2026年10月8日仓库3个月前更新

Language-independent tokenizer treating text as raw Unicode. Supports BPE and Unigram algorithms. Fast (50k sentences/sec), lightweight (6MB memory), deterministic vocabulary. Used by T5, ALBERT, XLNet, mBART. Train on raw text without pre-tokenization. Use when you need multilingual support, CJK languages, or reproducible tokenization.

仅含说明AI & Agents
AI 生成的概览

指导训练和使用 SentencePiece 分词器,实现与语言无关的多语言文本分词。

功能
该技能说明如何安装和使用 SentencePiece,在原始文本上训练 BPE 或 Unigram 模型,并将文本编码或解码为子词片段或 ID。内容涵盖词表大小、字符覆盖率、用户自定义符号和子词正则化等配置,并提供性能基准和受支持模型。它产出训练好的分词器模型和分词后的文本,而不是独立应用。
适用场景
适用于构建多语言或中日韩分词器、需要可复现的确定性分词,或希望在无需语言特定预处理的原始文本上训练的场景。也适用于使用依赖 SentencePiece 的 T5、ALBERT、XLNet 或 mBART 等模型时。
运行要求
需要 sentencepiece 包,可选 transformers;C++ 构建方式需要 CMake 和编译器。训练和分词需要本地语料数据。该技能仅附带参考文档,不含脚本。

SentencePiece - Language-Independent Tokenization

Unsupervised tokenizer that works on raw text without language-specific preprocessing.

When to use SentencePiece

Use SentencePiece when:

  • Building multilingual models (no language-specific rules)
  • Working with CJK languages (Chinese, Japanese, Korean)
  • Need reproducible tokenization (deterministic vocabulary)
  • Want to train on raw text (no pre-tokenization needed)
  • Require lightweight deployment (6MB memory, 50k sentences/sec)

Performance:

  • Speed: 50,000 sentences/sec
  • Memory: ~6MB for loaded model
  • Languages: All (language-independent)

Use alternatives instead:

  • HuggingFace Tokenizers: Faster training, more flexibility
  • tiktoken: OpenAI models (GPT-3.5/4)
  • BERT WordPiece: English-centric tasks

Quick start

Installation

bash
# Pythonpip install sentencepiece
# C++ (requires CMake)git clone https://github.com/google/sentencepiece.gitcd sentencepiecemkdir build && cd buildcmake .. && make -j $(nproc)sudo make install

Train model

bash
# Command-line (BPE with 8000 vocab)spm_train --input=data.txt --model_prefix=m --vocab_size=8000 --model_type=bpe
# Python APIimport sentencepiece as spm
spm.SentencePieceTrainer.train(    input='data.txt',    model_prefix='m',    vocab_size=8000,    model_type='bpe')

Training time: ~1-2 minutes for 100MB corpus

Encode and decode

python
import sentencepiece as spm
# Load modelsp = spm.SentencePieceProcessor(model_file='m.model')
# Encode to piecespieces = sp.encode('This is a test', out_type=str)print(pieces)  # ['▁This', '▁is', '▁a', '▁test']
# Encode to IDsids = sp.encode('This is a test', out_type=int)print(ids)  # [284, 47, 11, 1243]
# Decodetext = sp.decode(ids)print(text)  # "This is a test"

Language-independent design

Whitespace as symbol (▁)

python
text = "Hello world"pieces = sp.encode(text, out_type=str)print(pieces)  # ['▁Hello', '▁world']
# Decode preserves spacesdecoded = sp.decode_pieces(pieces)print(decoded)  # "Hello world"

Key principle: Treat text as raw Unicode, whitespace = ▁ (meta symbol)

Tokenization algorithms

BPE (Byte-Pair Encoding)

python
spm.SentencePieceTrainer.train(    input='data.txt',    model_prefix='bpe_model',    vocab_size=16000,    model_type='bpe')

Used by: mBART

Unigram (default)

python
spm.SentencePieceTrainer.train(    input='data.txt',    model_prefix='unigram_model',    vocab_size=8000,    model_type='unigram')

Used by: T5, ALBERT, XLNet

Training configuration

Essential parameters

python
spm.SentencePieceTrainer.train(    input='corpus.txt',    model_prefix='m',    vocab_size=32000,    model_type='unigram',    character_coverage=0.9995,  # 1.0 for CJK    user_defined_symbols=['[SEP]', '[CLS]'],    unk_piece='<unk>',    num_threads=16)

Character coverage

Language TypeCoverageRationale
English0.9995Most common chars
CJK (Chinese)1.0All characters needed
Multilingual0.9995Balance

Encoding options

Subword regularization

python
# Sample different tokenizationsfor _ in range(3):    pieces = sp.encode('tokenization', out_type=str, enable_sampling=True, alpha=0.1)    print(pieces)
# Output (different each time):# ['▁token', 'ization']# ['▁tok', 'en', 'ization']

Use case: Data augmentation for robustness.

Common patterns

T5-style training

python
spm.SentencePieceTrainer.train(    input='c4_corpus.txt',    model_prefix='t5',    vocab_size=32000,    model_type='unigram',    user_defined_symbols=[f'<extra_id_{i}>' for i in range(100)],    unk_id=2,    eos_id=1,    pad_id=0)

Integration with transformers

python
from transformers import T5Tokenizer
# T5 uses SentencePiece internallytokenizer = T5Tokenizer.from_pretrained('t5-base')inputs = tokenizer('translate English to French: Hello', return_tensors='pt')

Performance benchmarks

Training speed

CorpusBPE (16k)Unigram (8k)
100 MB1-2 min3-4 min
1 GB10-15 min30-40 min

Tokenization speed

  • SentencePiece: 50,000 sentences/sec
  • HF Tokenizers: 200,000 sentences/sec (4× faster)

Supported models

T5 family: t5-base, t5-large (32k vocab, Unigram) ALBERT: albert-base-v2 (30k vocab, Unigram) XLNet: xlnet-base-cased (32k vocab, Unigram) mBART: facebook/mbart-large-50 (250k vocab, BPE)

References

  • Training Guide [blocked] - Detailed options, corpus preparation
  • Algorithms [blocked] - BPE vs Unigram, subword regularization

Resources

来源与署名

来源:orchestra-research/ai-research-skills位于02-tokenization/sentencepiece提交773a529

许可证: MIT

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架