AI Logic

Tokenization

SentencePiece

Updated:

SentencePiece workflow. The left side shows training: raw sentences are normalized, whitespace is replaced with ▁, and a vocabulary is learned with BPE or Unigram into a single model file. The right side shows application: the Japanese text AI入門 深層学習を学ぶ ("Intro to AI: learn deep learning") is normalized, ▁ is inserted, it is split into subwords, and concatenating them and turning ▁ back into spaces restores the normalized text

What Is SentencePiece?

SentencePiece is a tokenizer (a tool that splits text into symbols) that learns a subword vocabulary directly from text without first splitting it into words, and treats whitespace as an ordinary symbol. It was released by Kudo and Richardson at Google in 2018. It is not a segmentation algorithm in itself but a tool that makes two algorithms, BPE and the Unigram language model, usable in a language-independent way.

Earlier subword tools assumed that text had already been split into words. English can be split on spaces, but Japanese, Chinese, and Korean require running a language-specific word segmenter (such as a morphological analyzer) first. Converting the symbols back into text (detokenization) also required language-specific rules, such as "insert spaces between words in English" and "do not insert them in Japanese."

SentencePiece treats text as just a sequence of Unicode characters, replaces whitespace with the symbol ▁ (U+2581), and learns it like any other character. This made the following possible.

  • Training without word segmentation: a subword vocabulary can be learned directly from raw Japanese text.
  • Exact restoration of the original text: simply concatenating the symbols and turning ▁ back into spaces yields the original (normalized) text.
  • Preprocessing is stored in the model file: the vocabulary and normalization rules are contained in a single file, so anyone using the same file can reproduce the same segmentation.

Four Components

SentencePiece consists of the following four components (Section 2 of the paper).

ComponentWhat it doesWhen it is used
NormalizerConverts Unicode characters with the same meaning into a canonical form (NFKC by default)Both training and segmentation
TrainerLearns a subword vocabulary from the normalized text (choose BPE or the Unigram language model)Training
EncoderNormalizes text and splits it into a sequence of subwords (and IDs)Segmentation
DecoderConverts a sequence of subwords (or IDs) back into normalized textRestoration

The left side of the figure at the top of the article shows the training flow, and the right side shows splitting and restoring. The example input is the Japanese text "AI入門 深層学習を学ぶ" (AI nyūmon / shinsō gakushū o manabu, "Intro to AI: learn deep learning"), which has a space only between the two phrases. Because the Normalizer runs inside the Encoder, the full-width "AI" in "AI入門" becomes the half-width "AI" before splitting.

The Encoder and Decoder also manage the mapping between symbols and IDs. Text can therefore be converted directly to a sequence of IDs and vice versa. Since neural networks take ID sequences as input and output, both preprocessing and postprocessing can be handled with this single tool.

Reversible Tokenization

In typical preprocessing, information is lost as soon as text is split into words. For example, splitting "Hello world." into [Hello] [world] [.] loses the fact that there was no space between world and the period. Restoring it required language-specific rules.

SentencePiece is designed so that the following equation holds (Section 3.1).

Decode(Encode(Normalize(text)))=Normalize(text)\mathrm{Decode}(\mathrm{Encode}(\mathrm{Normalize}(\mathit{text}))) = \mathrm{Normalize}(\mathit{text})

To achieve this, whitespace is replaced with ▁ before splitting, and then it is split just like ordinary characters.

  • Original text: Hello world.
  • Result of splitting: [Hello] [▁wor] [ld] [.]

The positions of spaces remain inside the symbols as ▁, so the original text can be restored simply by concatenating the symbols and replacing ▁ with spaces. Text without spaces, such as Japanese, and text mixing English and Japanese can both be restored with the same one-line operation.

detok = "".join(pieces).replace("▁", " ")

The well-known BPE implementation subword-nmt marks breaks inside a word with @@. This notation expresses "how a word was split," and the whitespace itself is not kept in the symbols. As a result, text such as that with two consecutive spaces cannot be restored.

Fast Training from Raw Text

Training without word segmentation increases the number of candidate symbol pairs, which tends to make computation heavy. SentencePiece uses the following techniques to make training from raw text practically fast (Section 3.2).

  • BPE: merged symbols are managed with a binary heap (priority queue), reducing the segmentation of a sentence of length NN from the naive O(N2)O(N^2) to O(Nlog⁡N)O(N \log N).
  • Unigram language model: both training and segmentation take time linear in the size of the input.

The paper compares the time taken for training and segmentation with a 16k vocabulary on KFTT (Japanese–English Wikipedia articles, 440,000 sentences) (Table 2; SentencePiece uses BPE).

TaskToolWord segmentationJapanese (s)English (s)
Trainingsubword-nmtYes56.954.1
TrainingSentencePieceYes10.116.8
Trainingsubword-nmtNo528.094.7
TrainingSentencePieceNo217.321.8
Segmentationsubword-nmtYes23.728.6
SegmentationSentencePieceYes8.220.3
Segmentationsubword-nmtNo216.236.1
SegmentationSentencePieceNo5.920.3

Word segmentation itself (KyTea for Japanese, Moses for English) also takes 24.6 seconds for Japanese and 15.8 seconds for English. On raw Japanese text, SentencePiece segments much faster than subword-nmt; the paper reports that it can segment about 21,000 sentences per second in English and about 74,000 in Japanese. It is fast enough to re-segment on the fly during training, which enables uses such as subword regularization.

Other Design Choices

SentencePiece includes further features for handling real-world text (Sections 3.3–3.6).

  • Specified by vocabulary size: subword-nmt specifies the "number of merges" for BPE, whereas SentencePiece specifies the final vocabulary size (--vocab_size). The number of merges is a concept specific to BPE and does not apply to the Unigram language model.
  • Reserved IDs for special tokens: IDs are reserved for unknown (<unk>), beginning of sentence (<s>), end of sentence (</s>), and padding (<pad>), and their numbers can be set with options. Tokens that convey context, such as <2ja> used in multilingual translation, can also be added.
  • Customizable normalization rules: the default is Unicode NFKC, which, for example, converts full-width alphanumerics to half-width. Custom rules can also be added in a TSV file.
  • Self-contained model file: the vocabulary, segmentation parameters, and normalization rules (compiled into a finite-state transducer) are stored in a single file, so distributing the file reproduces the same preprocessing.
  • Callable from programs: it can be used from C++, Python, and TensorFlow, so text can be segmented on the fly during training and segmentations can be resampled stochastically.

Experimental Results

The paper compares a word vocabulary (80,000 words) with SentencePiece (Unigram language model, an 8k vocabulary shared by source and target) on KFTT Japanese–English translation (Table 1, BLEU).

Source / target vocabularyJa→EnEn→Ja
Word / word (baseline)28.2420.06
SentencePiece (no word segmentation)29.5521.62
SentencePiece (word segmentation first)29.8520.86
Word / SentencePiece27.2421.41
SentencePiece / word29.1419.94

Two findings emerged.

  • Subwords improve results: SentencePiece achieved higher BLEU than the word vocabulary in both directions.
  • Word segmentation beforehand is unnecessary: for Ja→En, results were nearly the same with or without segmentation, and for En→Ja, no segmentation scored higher. The paper attributes this to word boundaries strongly constraining the final vocabulary. The effect is large when Japanese is used on the source or target side.

Practical Caveats

What gets restored is the "normalized text." The default NFKC normalization rewrites characters, for example converting full-width alphanumerics to half-width, so the Decode result is not necessarily identical to the input (e.g., "AI入門" → "AI入門"). To keep the original notation, change the normalization rules.

  • Use the same file for training and the model: the vocabulary and normalization are determined by the model file, so when using a pretrained model, use the distributed model file as is.
  • ▁ stands for a space: the ▁ attached to a symbol marks that "there was a space before this." It is also attached to the first symbol of a sentence (the paper's example: "Hello world." → ▁He ll o ▁world .).
  • Vocabulary size: the paper uses 8k for Japanese–English translation and 16k for the speed comparison. A larger vocabulary shortens sequences but enlarges the embedding matrix.
  • Languages with many characters: characters absent from the training data do not enter the vocabulary, so if every character must be handled, compare it with byte-level BPE before choosing.

Comparison with Other Tools and Methods

The table below compares subword segmentation tools from the same perspectives.

ToolSplits into words first?How word boundaries are markedCan the original text be restored?What is specifiedSegmentation algorithm
SentencePiece (this article)No (but it may)Whitespace is replaced with ▁ and included in symbolsYes (normalized text)Vocabulary sizeBPE or Unigram language model
subword-nmtYes@@ is attached inside wordsText with consecutive spaces, etc., cannot be restoredNumber of mergesBPE
BERT's WordPieceSplits on whitespace and punctuation## is attached from the second piece of a word onwardSpaces between words can be restored, but whether there was a space before punctuation, etc., is lostVocabularyWordPiece

Rough guidelines for choosing:

  • Handling languages without word boundaries, such as Japanese: use SentencePiece and train on raw text.
  • Making the model robust to segmentation variation: use subword regularization with SentencePiece's Unigram language model.
  • Using a pretrained model: use the tokenizer distributed with the model. For example, mT5 uses a SentencePiece vocabulary.

PyTorch example

Show code
python
import sentencepiece as spm

# 1) Learn the vocabulary from raw text (one sentence per line). Japanese need not be split into words either
spm.SentencePieceTrainer.train(
    input="corpus.txt",
    model_prefix="spm",          # produces spm.model and spm.vocab
    vocab_size=8000,             # the final vocabulary size, not the number of merges
    model_type="unigram",        # "bpe" is also available
    normalization_rule_name="nfkc",  # default normalization (e.g., full-width alphanumerics to half-width)
    character_coverage=0.9995,   # typical value for languages with many characters, such as Japanese
    pad_id=0, unk_id=1, bos_id=2, eos_id=3,  # IDs of special tokens
)

# 2) Split and restore (Japanese example: "Intro to AI: learn deep learning")
sp = spm.SentencePieceProcessor(model_file="spm.model")
text = "AI入門 深層学習を学ぶ"
pieces = sp.encode(text, out_type=str)  # e.g. ['▁AI', '入門', '▁深層', '学習', 'を', '学ぶ'] (depends on the vocabulary)
ids = sp.encode(text)                   # sequence of IDs
print(pieces, ids)
print(sp.decode(ids))                   # restores the normalized text: AI入門 深層学習を学ぶ
print("".join(pieces).replace("▁", " ").strip())  # joining manually gives the same result

# 3) Perturb the segmentation during training only (with the Unigram language model; subword regularization)
print(sp.encode(text, out_type=str, enable_sampling=True, alpha=0.1, nbest_size=-1))

# 4) Pass the ID sequences to PyTorch, padding to equal length with the <pad> ID
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence

batch = [torch.tensor(sp.encode(t, add_bos=True, add_eos=True)) for t in ["深層学習を学ぶ", "AI入門"]]
x = pad_sequence(batch, batch_first=True, padding_value=sp.pad_id())
embed = nn.Embedding(sp.get_piece_size(), 256, padding_idx=sp.pad_id())
print(embed(x).shape)  # (2, max length, 256)

FAQ

Q. Is SentencePiece an algorithm separate from BPE and the Unigram language model?
A.

No. SentencePiece is a tool, and it uses either BPE or the Unigram language model as its internal segmentation algorithm. What SentencePiece newly added is training from raw text without word segmentation, treating whitespace as ▁ so that the original text can be restored, and bundling preprocessing into the model file.

Q. What is `▁`? Is it different from an underscore (_)?
A.

It is a meta symbol representing whitespace: Unicode U+2581 (LOWER ONE EIGHTH BLOCK). It looks like an underscore but is a different character. This rarely used character is chosen so that it can be distinguished from genuine underscores in text.

Q. Should Japanese text be split into words with a morphological analyzer before applying SentencePiece?
A.

Not necessarily. In the paper's Japanese–English translation, results for Ja→En were nearly the same with or without segmentation, and for En→Ja, BLEU was higher without segmentation. Skipping segmentation also saves the effort of preparing a morphological analyzer.

References

  1. T. Kudo and J. Richardson, "SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing," Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing: System Demonstrations (EMNLP), 2018.
  2. T. Kudo, "Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates," ACL, 2018.
  3. R. Sennrich, B. Haddow, and A. Birch, "Neural Machine Translation of Rare Words with Subword Units," ACL, 2016.
  4. google/sentencepiece (source code and usage)
  5. L. Xue, A. Barua, N. Constant, R. Al-Rfou, S. Narang, M. Kale, A. Roberts, and C. Raffel, "ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models," Transactions of the Association for Computational Linguistics, 2022.