google/sentencepiece

Unsupervised text tokenizer for Neural Network-based text generation.

What it solves

Neural text models like large language models need a fixed vocabulary before training, but raw text is messy: languages have different word boundaries, and whitespace is usually dropped, making it impossible to recover the original text. SentencePiece solves this by treating input as a raw sequence of Unicode characters and learning subword units directly from that sequence. This removes the need for language-specific pre-tokenizers and makes tokenization reversible — you can always get the exact original string back.

How it works

SentencePiece works in two stages. First, it trains a tokenizer model directly from a plain text file using one of two unsupervised algorithms: Byte-Pair-Encoding (BPE) or the unigram language model. The model learns a fixed vocabulary of subword pieces (like "▁I" or "te") and how to split any text into those pieces. Second, once trained, the model can encode new text into a sequence of piece strings or integer IDs, and decode those IDs back into the original text with zero loss. Whitespace is preserved by representing it with a special symbol (▁, U+2581), so detokenization is just a simple string join. The entire model — normalization rules, vocabulary mapping, and segmentation logic — is packed into one self-contained .model file, so the same tokenization results are guaranteed across all supported languages (C++, Python, Go, etc.).

Who it’s for

SentencePiece is aimed at developers building neural text generation systems, especially large language models, that need a fixed vocabulary before training. It is also useful for multilingual applications that must handle languages without explicit word boundaries (like Chinese, Japanese, or Thai) without extra preprocessing. The project provides Python and C++ APIs, plus a lightweight C++20 runtime for mobile or edge devices.

Highlights

  • Reversible and lossless — detokenization is a simple string join that always recovers the original text, independent of language.
  • Language-independent — no need for language-specific pre-tokenizers; works on raw Unicode text.
  • Subword regularization — supports on-the-fly sampling of different segmentations (BPE-dropout and unigram sampling) to improve model robustness.
  • Fast and lightweight — written in optimized C++, with segmentation speeds around 50,000 sentences per second and a memory footprint of ~6 MB.
  • Self-contained models — the .model file includes everything, guaranteeing identical tokenization across environments.
  • Includes SentencePiece Lite — a zero-dependency C++20 runtime with mmap-based startup and a ~45 KB static library, for edge and mobile use.

Related

  • Dispatch
  • Dispatch
  • Project
  • Project
  • Dispatch