Sub topic 10
SentencePiece: tokenising raw text without pre-tokenisation
This chapter assumes you know how BPE learns and applies merges, how WordPiece uses greedy longest match with ## prefixes, and what a pre-tokeniser does. You should be comfortable reading short Python programs. By the end you should be able to explain what SentencePiece changes, train a model, and avoid its most common configuration errors.
The problem SentencePiece solves
BPE and WordPiece, as used in many early systems, depend on a pre-tokenisation step. A rule-based splitter cuts text into words before any subword algorithm runs. That has three costs:
- The splitter is language-specific. Whitespace rules work poorly for Chinese, Japanese, and Thai, which do not separate words with spaces.
- The splitter loses information. After splitting on whitespace, you cannot tell whether two tokens were separated by one space, two spaces, or a newline.
- The pipeline needs a language-specific detokeniser to turn tokens back into text, and that step is usually approximate.
SentencePiece treats the input as one raw stream of Unicode characters. It does not need a word splitter. Whitespace becomes an ordinary symbol, and the model learns where to cut. The encoding can therefore be reversed exactly.
The ▁ whitespace marker
SentencePiece replaces every space with the visible character ▁ (U+2581, "lower one eighth block") before segmentation. It also adds a dummy space at the start of the text by default, so the first word is treated the same as any word that follows a space.
raw text: Hello world
after escaping: ▁Hello▁world
pieces: ▁Hello ▁worldThe marker travels inside the pieces. A piece that starts with ▁ begins a word. A piece without it continues the previous word. This is the mirror image of WordPiece, which marks continuations with ## and leaves word starts unmarked.
Decoding needs no language knowledge:
- Concatenate all pieces.
- Replace each
▁with a space. - Strip the leading space added by the dummy prefix.
Two algorithms in one library
SentencePiece is a framework, not a single algorithm. You choose the model with model_type.
| `model_type` | How the vocabulary is built | How text is segmented |
|---|---|---|
| `unigram` (default) | Start with a large seed vocabulary and repeatedly drop the pieces whose removal hurts the corpus likelihood least | Viterbi search for the highest-probability segmentation |
| `bpe` | Start from characters and merge the most frequent adjacent pair, as in the earlier BPE chapter | Apply the learned merges in order |
| `char`, `word` | Characters or whitespace-separated words | Direct lookup |
The unigram model gives each piece a probability. The probability of a segmentation is the product of its piece probabilities, and the encoder picks the best one. This allows a feature BPE lacks: sampling several segmentations of the same text during training, called subword regularisation. It acts as data augmentation and can make a model more tolerant of noisy input.
Training and using a model
The following program is self-contained. It writes a tiny corpus, trains a BPE model, and checks that encoding is reversible.
import sentencepiece as spm
sentences = [
"the cat sat on the mat",
"the dog sat on the log",
"a cat and a dog sat together",
"the mat was on the log",
]
with open("corpus.txt", "w", encoding="utf-8") as f:
for _ in range(50):
for s in sentences:
f.write(s + "\n")
spm.SentencePieceTrainer.train(
input="corpus.txt",
model_prefix="demo",
vocab_size=80,
model_type="bpe",
hard_vocab_limit=False, # tiny corpus: do not fail if 80 is unreachable
)
sp = spm.SentencePieceProcessor(model_file="demo.model")
text = "the cat sat on the log"
pieces = sp.encode(text, out_type=str)
ids = sp.encode(text, out_type=int)
print(pieces)
print(ids)
assert sp.decode(ids) == text
assert "".join(pieces).replace("\u2581", " ").lstrip(" ") == text
print(sp.encode("the cat \u2603", out_type=str))The exact pieces depend on the merges learned, but common words appear as whole pieces such as ▁the. The last line contains a snowman, which never occurred in training. The model has no piece for it, so it maps to <unk>, and decoding that id produces a placeholder instead of the original character. That is the one case where the round trip fails.
On a real corpus you would use a vocabulary of thousands of pieces, such as the vocab_size=8000 setting from the earlier example. Without hard_vocab_limit=False, training raises an error if the corpus cannot support the requested size.
What "lossless" does and does not mean
Reversibility has limits that matter in practice.
- Normalisation changes characters. The default rule,
nmt_nfkc, applies Unicode NFKC-style normalisation. For example, a full-widthAbecomesA. The decoded text matches the normalised input, not necessarily your original. Usenormalization_rule_name="identity"if you need exact characters. - Whitespace is collapsed by default.
remove_extra_whitespaces=Truestrips leading and trailing spaces and merges runs of spaces. Set it toFalsewhen whitespace carries meaning, for example in code. - Unknown characters are lost. Anything outside the vocabulary becomes
<unk>.
The fix for the last problem is byte_fallback=True. SentencePiece then adds 256 byte pieces such as <0xE2>, and any character missing from the vocabulary is encoded as its UTF-8 bytes. This gives the same no-unknown-token guarantee as byte-level BPE, but only for characters outside the vocabulary. Common characters still get ordinary pieces.
Character coverage
SentencePiece does not necessarily keep every character in the corpus. character_coverage is the fraction of characters the base alphabet must cover. The documented default is 0.9995, with 1.0 suggested for languages with small alphabets. Rare characters outside the covered set map to <unk>, or to bytes if byte_fallback is on. For Chinese or Japanese, where thousands of characters occur rarely, the lower value keeps the vocabulary from filling up with one-off symbols. For English-only data, use 1.0.
Splitting rules that remain
"No pre-tokenisation" means no language-specific word splitter. SentencePiece still applies a few simple constraints, and you can change them.
| Option | Default | Effect |
|---|---|---|
| `split_by_whitespace` | `True` | Pieces cannot span two words. The `▁` must be at the start of a piece. |
| `split_by_unicode_script` | `True` | Pieces cannot mix scripts, such as Latin and Han. |
| `split_by_number` | `True` | Digits are separated from letters. |
| `split_digits` | `False` | When `True`, every digit becomes its own piece. |
Turning off split_by_whitespace lets the model learn multi-word pieces such as ▁of▁the. This shortens sequences, but it also makes the vocabulary harder to train and less predictable.
Special tokens
SentencePiece reserves ids for control symbols. By default, <unk> is id 0, <s> is id 1, </s> is id 2, and padding is disabled with id -1. You can change these with unk_id, bos_id, eos_id, and pad_id. To add your own, use user_defined_symbols, for example user_defined_symbols=["<mask>", "<sep>"].
User-defined symbols are matched in the raw text and always become a single piece. Control symbols such as <s> are never produced from text. You add them yourself by calling sp.encode(text, add_bos=True, add_eos=True).
Common errors
- Vocabulary size too high. The error "Vocabulary size is too high" means the corpus has too few distinct pieces. Use more text, a smaller
vocab_size, orhard_vocab_limit=False. - Training on pre-tokenised text. If your input file already has spaces around punctuation, the model learns those artificial spaces. Feed it raw text.
- Mismatched models. A model trained for one language run on another yields many
<unk>ids or long byte sequences. Always ship the.modelfile with the network that was trained on it. - Assuming the first piece has no marker. With the dummy prefix, the first word begins with
▁. Code that compares pieces to a word list must account for this. - Comparing ids across models. The same piece has a different id in each trained model, so ids are meaningful only for the model that made them.
Exercise
You train a SentencePiece model with default settings. A colleague encodes "a b" (two spaces between the letters) and decodes it, and gets "a b" back. Which setting caused this, and what would you change to preserve the original text?
Show answer
The default remove_extra_whitespaces=True merges runs of spaces during normalisation, so the double space is lost before segmentation. Train with remove_extra_whitespaces=False. If you also need characters preserved exactly, add normalization_rule_name="identity", since the default nmt_nfkc rule rewrites some characters.
Exercise
A Japanese corpus contains many rare kanji. Which character_coverage value is appropriate, and what happens to characters excluded by it?
Show answer
Use a value below 1.0, such as the default 0.9995, so that very rare kanji do not occupy vocabulary slots. Excluded characters map to <unk> unless byte_fallback=True is set, in which case they are encoded as UTF-8 byte pieces and can be decoded exactly.