Sub topic 10
SentencePiece: tokenising raw text without pre-tokenisation
SentencePiece is a subword tokeniser that learns directly from raw text. It does not require a separate word-splitting step. This chapter assumes basic Python, dictionaries, loops, token concepts, and frequency counts.
Why avoid pre-tokenisation?
Many tokenisers first split text into words using spaces and punctuation. That approach works well for English, but it requires language-specific rules. It also creates problems for languages where spaces do not separate words, such as Japanese or Chinese.
SentencePiece treats the input as a sequence of Unicode characters. It learns pieces from the original text, including how whitespace appears. This makes the same training process usable across many languages.
A visible whitespace marker, written as ▁, represents a space. For example, the text:
Hello worldmight become:
▁Hello ▁worldThe marker is part of the piece representation. It lets the decoder restore spaces without needing a separate word-boundary rule.
Training and encoding
SentencePiece can train either a BPE model or a unigram language model. BPE repeatedly merges frequent pieces. A unigram model starts with many possible pieces and removes pieces while preserving a good probability model for the training text.
The model stores a vocabulary and tokenisation rules. At inference time, it converts new raw text into pieces or integer IDs.
The following example creates a small corpus, trains a unigram model, and encodes and decodes a sentence.
from pathlib import Path
import sentencepiece as spm
corpus_path = Path("corpus.txt")
corpus_path.write_text(
"Hello world\n"
"Hello SentencePiece\n"
"Tokenisers split text into useful pieces\n",
encoding="utf-8",
)
spm.SentencePieceTrainer.train(
input=str(corpus_path),
model_prefix="demo",
vocab_size=64,
model_type="unigram",
character_coverage=1.0,
hard_vocab_limit=False,
)
processor = spm.SentencePieceProcessor(model_file="demo.model")
text = "Hello world"
pieces = processor.encode(text, out_type=str)
ids = processor.encode(text, out_type=int)
decoded = processor.decode(ids)
print("pieces:", pieces)
print("ids:", ids)
print("decoded:", decoded)Install the package before running the example:
# Run this in a terminal, not inside the Python program:
# python -m pip install sentencepieceThe exact pieces depend on the corpus and vocabulary size. The decoded text should match the original text, including its spaces.
| Operation | Input | Output |
|---|---|---|
| Encode as pieces | `Hello world` | pieces containing `▁Hello` and `▁world` |
| Encode as IDs | `Hello world` | integer vocabulary IDs |
| Decode | integer IDs | `Hello world` |
How the representation stays reversible
SentencePiece first replaces spaces with the whitespace marker and then applies its learned segmentation. Because the marker remains in the piece sequence, decoding can reconstruct the original spacing.
For example, a possible segmentation is:
▁Sentence Piecewhere ▁Sentence begins after a space and Piece continues the same word. The marker does not mean that every piece is a complete word. It marks a boundary in the original text.
Punctuation, repeated spaces, and unusual Unicode characters are handled as model input rather than being discarded by a word pre-tokeniser. Exact behaviour depends on normalisation settings and the model configuration.
When SentencePiece is useful
SentencePiece is a strong choice when:
- the project supports several languages with different word-boundary rules;
- raw text must be processed consistently during training and inference;
- whitespace and punctuation need a reversible representation;
- you want one library that supports both BPE and unigram models.
It does not automatically solve vocabulary coverage or sequence-length problems. Those depend on the training data, vocabulary size, character coverage, and model type.
Exercise
Why does SentencePiece use the ▁ marker?
Show answer
It records where whitespace occurred, so the decoder can reconstruct spaces without running a separate word-tokenisation rule.