Sub topic 3
SentencePiece: tokenising raw text without pre-tokenisation
Prerequisites
This chapter assumes you can write Python, know how BPE merges and WordPiece's ## prefix work, and understand that a model reads integer token IDs. You need the sentencepiece package and a plain-text file, corpus.txt, with one sentence per line.
Raw text without pre-tokenisation
BPE and WordPiece usually split text on whitespace first (pre-tokenisation), then apply subword rules inside each word. SentencePiece skips that step. It reads the raw character stream and treats the space as an ordinary symbol. Each space becomes the marker ▁ (U+2581), so "Hello world" yields the pieces ▁Hello and ▁world. Because every space is kept, decoding is reversible.
import sentencepiece as spm
# corpus.txt: one sentence per line of raw, untokenised text
spm.SentencePieceTrainer.train(
input="corpus.txt",
model_prefix="demo",
vocab_size=8000,
model_type="unigram", # or "bpe"
)
sp = spm.SentencePieceProcessor(model_file="demo.model")
pieces = sp.encode("Hello world", out_type=str)
ids = sp.encode("Hello world", out_type=int)
print(pieces)
print(sp.decode(ids)) # Hello worldSpecial tokens and whitespace markers
Special tokens such as <unk>, <s>, </s>, and <pad> get reserved IDs. Pass them to the trainer with unk_id, bos_id, eos_id, and pad_id.
WordPiece marks word-internal pieces with ##. SentencePiece marks word starts with ▁ instead. Compare ▁un with aff for "unaff".
> Note: ▁ is a real piece, so a lone ▁ can appear in the vocabulary. Do not strip it when you post-process output.
Choosing a vocabulary size
A larger vocabulary gives shorter sequences but a bigger embedding table, and rare entries receive few training updates. A smaller vocabulary gives longer sequences and more compute per sentence. Sizes between 8,000 and 32,000 are common for single-language models. A size that is too large for your corpus fails to train, so check the corpus size first.
Pitfalls
- Multilingual text: A vocabulary trained mostly on English splits other scripts into single characters or byte fallback, which lengthens their sequences. Balance the corpus and set
character_coveragedeliberately. - Numbers: Digits can merge into arbitrary chunks, so
1234might split as▁123and4. Setsplit_digits=Trueto force one token per digit. - Train/inference mismatch: Serving with a different
.modelfile or normalisation rules changes the IDs. Ship the exact.modelfile used for training.
Comparing the three approaches and choosing one
| Approach | Builds vocabulary by | Needs pre-tokenisation | Unknown-character handling |
|---|---|---|---|
| BPE | Merging the most frequent adjacent pair | Yes, in classic form | Byte-level BPE avoids unknowns |
| WordPiece | Merging pairs scored by likelihood | Yes | A word with no match becomes `[UNK]` |
| SentencePiece (unigram or BPE) | Pruning a large seed vocabulary, or merging pairs on raw text | No | Byte fallback is optional |
- Choose WordPiece when you must match an existing BERT-style model.
- Choose SentencePiece for multilingual or whitespace-unreliable text.
- Choose byte-level BPE when unknown tokens must never occur.
Exercise
Why can SentencePiece decode its own output back to the exact original text?
Show answer
Each space is kept as the ▁ symbol inside the pieces, so no character is dropped or altered during encoding, and decoding simply maps the pieces back.