SentencePiece

On this page 7

SentencePiece is an open-source subword tokenizer and detokenizer that learns a fixed vocabulary directly from raw, untokenized text and converts any input string into a sequence of integer token IDs. In language models, it is the component that decides how text becomes tokens, and it is used by many widely deployed model families, including T5, mT5, ALBERT, XLNet and several generations of Llama and Gemma.

Its defining design choice is to treat the input as a plain stream of Unicode characters, with whitespace encoded as an ordinary symbol. Because it needs no language-specific pre-tokenizer, the same pipeline works for English, Japanese, Thai or source code, which made it a standard building block of multilingual artificial intelligence systems.

How SentencePiece encodes text

SentencePiece encodes text by normalizing the string, replacing spaces with the meta symbol ▁ (U+2581), and then segmenting the result into pieces from a learned vocabulary. Because whitespace survives as a visible symbol, decoding is lossless and reversible: concatenating the pieces and turning ▁ back into spaces restores the normalized original exactly.

The library bundles training and inference into one self-contained model file. That single `.model` file stores the vocabulary, the piece scores, the normalization rules and the special token definitions, so a tokenizer trained on one machine reproduces identical segmentation everywhere it is loaded.

The following table lists the main stages of the encoding pipeline and what each contributes.

StageWhat happensWhy it matters
NormalizationNFKC rules unify equivalent charactersConsistent input across sources
Whitespace escapingSpaces become the ▁ symbolLossless detokenization
SegmentationText is split into vocabulary piecesBounded vocabulary size
ID mappingEach piece maps to an integerModel-ready input
Byte fallbackUnknown characters become UTF-8 bytesNo out-of-vocabulary failures
Stages of the SentencePiece pipeline

Segmentation algorithms inside SentencePiece

SentencePiece is a framework rather than a single algorithm, and it supports two subword training methods plus two simple baselines. The unigram language model is the default: it starts from a large candidate vocabulary and iteratively prunes pieces whose removal least reduces the corpus likelihood. The byte-pair encoding (BPE) mode works in the opposite direction, merging the most frequent adjacent symbol pairs until the target vocabulary size is reached.

The unigram mode assigns each piece a log-probability score, so a word can have several valid segmentations ranked by probability. This property enables subword regularization, a training technique that samples alternative segmentations to make a model more robust to spelling variation and noise.

Model typeTraining directionTypical use
UnigramPrunes a large seed vocabularyDefault; supports sampling
BPEMerges frequent pairs upwardLlama-style decoder models
CharOne piece per characterBaselines, small alphabets
WordWhitespace-separated wordsLegacy comparisons
Model types supported by SentencePiece

SentencePiece compared with other tokenizers

SentencePiece differs from other tokenizers mainly in where pre-tokenization happens. Classic WordPiece setups, as used in BERT, first split text on spaces and punctuation with language-specific rules, while byte-level BPE in the GPT-2 lineage operates on UTF-8 bytes after a regex pre-split. SentencePiece skips the pre-split entirely and learns boundaries, including word boundaries, from data.

The comparison below summarizes the practical differences engineers usually weigh when choosing a tokenizer for a new model.

PropertySentencePieceWordPiece (BERT)Byte-level BPE
Pre-tokenizationNone requiredWhitespace and punctuation rulesRegex pre-split
Base unitsUnicode charactersCharactersUTF-8 bytes
Whitespace handlingEncoded as ▁Discarded, prefix ## marksEncoded as a byte
ReversibilityLosslessPartly lossyLossless
CJK and Thai textHandled nativelyNeeds extra rulesHandled, often long sequences
SentencePiece versus common alternatives

In practice, the line between these tools has blurred. SentencePiece with byte fallback enabled behaves much like byte-level BPE for rare characters, while keeping readable character-level pieces for common text.

Training and configuring a SentencePiece model

Training a SentencePiece model requires a text corpus and a handful of parameters, and the vocabulary size is the most consequential choice. Smaller vocabularies produce longer token sequences and higher inference cost; larger vocabularies shorten sequences but enlarge the embedding matrix and leave rare pieces undertrained.

ParameterTypical settingEffect
vocab_size8,000 to 256,000Sequence length versus embedding size
model_typeunigram or bpeSegmentation algorithm
character_coverage0.9995 for CJK, 1.0 otherwiseShare of characters kept as pieces
byte_fallbacktrue for modern LLMsRemoves unknown tokens
split_digitstrue in many recent modelsMore consistent arithmetic
input_sentence_sizeMillions of sentencesMemory use during training
Key training parameters and their effects

Monolingual models often work well with 16,000 to 32,000 pieces, whereas multilingual models such as mT5 or Gemma use 250,000 or more to give every script reasonable coverage. The training corpus should mirror the deployment data, because the tokenizer is frozen after pretraining and cannot be changed without retraining or adapting the embedding layer.

Limitations and common mistakes

SentencePiece is robust, but several recurring errors appear in production systems. Most of them stem from a mismatch between the tokenizer used in training and the one used at inference time.

SymptomLikely causeFix
Garbled output textWrong or mismatched .model fileShip the tokenizer with the weights
Frequent unknown tokensByte fallback disabledRetrain with byte_fallback
Very long sequences in one languageScript underrepresented in corpusRebalance the training sample
Leading space errorsIgnoring the ▁ prefixUse the library decoder, not string joins
Typical problems and how to fix them
  • Tokenization fairness is a real concern: languages with little training data can need two to four times more tokens for the same meaning.
  • Normalization changes text: NFKC can alter full-width characters or ligatures, which matters for exact string matching.
  • Glitch tokens can arise when rare pieces appear in the vocabulary but almost never in the model training data.

In everyday language

A language model cannot read letters. It reads numbers. SentencePiece is the translator that cuts text into small pieces and gives each piece a number.

Think of a box of word fragments. Common words get their own fragment. Rare words are built from several smaller ones. Spaces count as a fragment too, so nothing is lost when the text is put back together. Because the tool does not need to know where words begin, it works for almost any language.

Seen in the real world

A research team building a translation model for English, Czech, Japanese and Swahili trains one SentencePiece tokenizer on a balanced sample of 20 million sentences. They choose the unigram model with 64,000 pieces, a character coverage of 0.9995 and byte fallback enabled, so emoji and rare symbols never produce unknown tokens.

Before training the full model, they measure tokens per sentence in each language. Swahili initially needs about 40 percent more tokens than English, so they upsample Swahili text and retrain the tokenizer. The final vocabulary brings the gap under 15 percent, which lowers inference cost and gives the smaller language a fairer share of the context window.