SentencePiece: what survives the round trip?
SentencePiece
Train real tokenizer models and inspect normalization, whitespace, unknown IDs and serialized model reuse.
sentencepieceThe text came back—but did the spaces?
Type AI lab: the first letter is a fullwidth A, and there are two spaces before lab. Now encode it and decode its integer IDs. Our default SentencePiece model returns AI lab, with an ASCII A and one space. The tokenizer has not randomly damaged the message. Its configured normalizer deliberately made those inputs equivalent.
This distinction is central to SentencePiece. It is a toolkit for normalization, vocabulary learning, segmentation, ID conversion and decoding. It can use BPE or a Unigram model; “SentencePiece versus BPE” is therefore not a comparison between two algorithms at the same layer. The 2018 system paper separates the Normalizer, Trainer, Encoder and Decoder and defines its lossless property over normalized text.
A character-list baseline would preserve this seven-character input without learning anything. Why add a tokenizer? Reusable subwords can reduce sequence length, while a fixed vocabulary provides the integer IDs needed by embedding tables. The engineering question is what information you are willing to normalize away and whether training and serving use precisely the same model.
Normalization, pieces and IDs are separate contracts
Write for text normalization, for segmentation under model , and for the model’s piece-to-ID map. A useful conceptual pipeline is
Here means normalized surface text. Internally, the implementation also escapes spaces as ▁ (U+2581) and may insert a dummy leading space. The Python processor.normalize() result exposes that internal marked representation; it is not the human-readable output of decoding. For covered text with compatible marker handling, the intended round trip is
This is not a promise for arbitrary unseen characters or reserved marker strings. Nor does it imply recovery of the original . If normalization maps two inputs to one result, no decoder receiving only that result can know which input was supplied:
The pinned normalization documentation describes nmt_nfkc, extra-whitespace removal and the dummy prefix. The paper’s footnote 3 also warns that its normalization is not a complete implementation of Unicode NFKC reordering. Do not substitute an arbitrary Unicode library call and assume it matches a saved SentencePiece model.
The space marker lets segmentation retain boundaries in its pieces. It is not a start-of-word label with independent semantic content. A dummy prefix makes a word at the beginning look more like the same word after a space; the official decoder handles that convention. A bare join-and-replace recipe can leave an unwanted initial space and does not implement all special-token behavior.
Integer IDs belong to a particular model. For each ordinary known vocabulary piece , the model provides the inverse mapping
This says nothing about equal IDs across independently trained models. Special symbols such as unknown, beginning-of-sequence and end-of-sequence have separate roles. The example leaves their default reservations in place but does not automatically add BOS/EOS to the encoded samples.
One simple measurement compares the number of characters with the number of model tokens:
For the raw seven-character example, default Unigram produces two tokens, so ; after normalization there are only six characters, giving . State which numerator you use. This is a length ratio, not a translation score or a direct latency measurement.
Finally, character coverage is measured on training characters. Even keeping every observed character only establishes
With byte fallback disabled, a new character may become the unknown ID. The Python string-piece output can still display its surface spelling; that does not mean the integer ID sequence preserves it.
Train, serialize, reload, and compare
Install the pinned package with python -m pip install sentencepiece==0.2.1. The official Python package documentation describes training from a sentence iterator into an in-memory model and loading from its serialized bytes. This program uses the real library, not a replacement tokenizer written to imitate its output.
The corpus contains twelve authored teaching sentences, repeated four times: 48 training records, not 48 independent examples. We train default Unigram, Unigram with identity character normalization and preserved extra spaces, and BPE. Sampling of training sentences is disabled and training uses one thread. Each model requests a vocabulary of at most 48 entries because hard_vocab_limit=False. The results below were checked with Python 3.12 and SentencePiece 0.2.1.
"""Train real SentencePiece 0.2.1 models on an explicitly synthetic corpus."""
import io
import json
import sentencepiece as spm
CORPUS = ["AI lab", "AI labs", "a small lab", "a small model", "models learn",
"AI 学习", "模型学习", "学习模型", "AI lab", "AI lab", "lab AI", "模型 lab"]
def train(model_type="unigram", preserve=False):
if model_type not in {"unigram", "bpe"}:
raise ValueError("Choose unigram or bpe")
model = io.BytesIO()
spm.SentencePieceTrainer.train(
sentence_iterator=iter(CORPUS * 4), model_writer=model,
model_type=model_type, vocab_size=48, character_coverage=1.0,
normalization_rule_name="identity" if preserve else "nmt_nfkc",
remove_extra_whitespaces=not preserve, add_dummy_prefix=True,
shuffle_input_sentence=False, input_sentence_size=0, num_threads=1,
hard_vocab_limit=False, byte_fallback=False, minloglevel=2)
return spm.SentencePieceProcessor(model_proto=model.getvalue()), model.getvalue()
def inspect(processor, text):
ids = processor.encode(text, out_type=int)
return dict(text=text, normalized=processor.normalize(text),
pieces=processor.encode(text, out_type=str), ids=ids,
decoded=processor.decode(ids),
unknowns=sum(i == processor.unk_id() for i in ids))
def demo():
if spm.__version__ != "0.2.1":
raise RuntimeError("This example was verified with sentencepiece==0.2.1")
rows = {}
for name, kind, preserve in [("unigram", "unigram", False),
("identity", "unigram", True),
("bpe", "bpe", False)]:
processor, model = train(kind, preserve)
restored = spm.SentencePieceProcessor(model_proto=model)
row = inspect(processor, "AI lab")
row.update(vocabulary=processor.get_piece_size(),
reloaded_ids_equal=restored.encode("AI lab") == row["ids"])
rows[name] = row
processor, _ = train()
return dict(version=spm.__version__, training_sentences=len(CORPUS) * 4,
models=rows, unseen=inspect(processor, "AI 雪"),
character_baseline=list("AI lab"))
if __name__ == "__main__":
print(json.dumps(demo(), ensure_ascii=False, indent=2))
Default Unigram returns ['▁AI', '▁lab'], IDs [4, 3], and AI lab. Its learned vocabulary has 28 entries. The identity configuration returns the original AI lab and uses five pieces with a vocabulary of 29 entries. BPE also returns the normalized text in two pieces, but its IDs are [7, 5] and its vocabulary has 48 entries. These IDs describe this run, not permanent IDs for the words AI or lab.
Reloading each serialized model preserves its IDs for the test string. The model contains the vocabulary and normalization settings needed by the processor; shipping only a text vocabulary would omit parts of the pipeline. For AI 雪, the default model encounters one unknown ID. Its decoded IDs do not restore 雪, even though the string-piece list displays that character.
The identity configuration changes both normalization_rule_name and remove_extra_whitespaces. Changing only the former does not disable whitespace removal. The tests also cover leading and trailing ordinary spaces for the identity configuration, an empty input and a reloaded model. They do not claim all Unicode or all special-symbol inputs are reversible.
A deployable tokenizer needs more than a vocabulary file
Keep the model artifact, library version, normalization flags, special-token policy and a small set of round-trip fixtures together. Model IDs are coupled to a language model’s embedding rows: retraining a tokenizer and retaining the old embedding table silently changes meanings. Check artifact identity before serving, then test inputs with spaces, non-ASCII text and unknown characters.
The non-AI baseline is still useful. A character or byte representation may be acceptable when preserving exact source text matters more than sequence length. If normalization is required for matching, retain the raw source separately when your application must reproduce it. Neither a tokenizer nor a decoder can infer distinctions that preprocessing erased.
Costs depend on the selected algorithm. The system paper describes heap-based BPE segmentation with an bound, unlike a repeated full scan. For a Unigram lattice with candidate edges, dynamic programming can score paths in time; constructing the lattice and vocabulary size also matter. This small example measures behavior, not throughput, and does not establish the README’s performance claims. Test the actual workload and batch size before drawing a cost conclusion.
Check the boundary between text and IDs
- Is SentencePiece another name for Unigram tokenization?
Answer: No. It is a toolkit that can train and apply different model types. Normalization, whitespace handling and ID management remain pipeline concerns whether the selected segmentation algorithm is Unigram or BPE.
- Why is the default example’s raw-character-per-token ratio 3.5, but its normalized-character-per-token ratio 3?
Answer: The raw string has seven characters and the normalized string has six because two spaces become one. Both use two output tokens in this run, so the numerators differ: versus .
- Why does
identityalone not guarantee exact preservation of ordinary spaces?
Answer: Character normalization and extra-whitespace removal are separate settings. Disable the latter as well, then test the desired input class. Unknown IDs and special markers can still prevent a universal raw-text round-trip guarantee.
- A model displays
雪in its string pieces but emits the unknown integer ID. Can a server that stores only those IDs recover the character?
Answer: No. Several unknown surfaces can share that ID. Keep the original surface separately or use a suitable coverage/fallback scheme; the displayed string pieces do not make the ID representation lossless.
Use the paper to qualify the quick-start promise
The system paper supplies the normalized-text contract, component separation, whitespace representation and normalization caveat. The fixed normalization documentation explains the settings we test, while the versioned Python package page supplies the real API used here. Broad README wording about recovering “the original string” must be read with those conditions. The encyclopedia’s experiment verifies a tiny configured pipeline, not a multilingual quality benchmark. Read BPE for merge ranks and Unigram tokenization for the probability model behind the alternative segmenter.
Make a prediction, then check
Does character_coverage=1.0 guarantee coverage of every Unicode character?
Learning objectives
- Trace raw text through normalization, segmentation and model-local IDs.
- Test normalized-text recovery and identify unknown-character and whitespace losses.
- Package and reload a real trained model while keeping preprocessing settings fixed.
Prerequisites & connections
Explore related knowledge →References
- SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
Taku Kudo; John Richardson · 2018 - SentencePiece normalization and whitespace options at fixed commit
SentencePiece contributors · 2026 - SentencePiece 0.2.1 Python package
Taku Kudo and SentencePiece contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked SentencePiece sections 2 and 3.1–3.5, fixed normalization docs/proto options and versioned Python API. Six paired equations and four explained exercises; actual official 0.2.1 library trains three tiny models, verifies normalized versus raw recovery, model-local IDs, unknown characters and serialized reload. No all-Unicode reversibility or throughput claim; local macOS execution only.
- Single AI author checked SentencePiece sections 2 and 3.1–3.5, fixed normalization docs/proto options and versioned Python API. Six paired equations and four explained exercises; actual official 0.2.1 library trains three tiny models, verifies normalized versus raw recovery, model-local IDs, unknown characters and serialized reload. No all-Unicode reversibility or throughput claim; local macOS execution only.
- Four computed SVG variants per topic; 10 numeric/geometry tests and 24 responsive cases passed. Eight Chinese-mobile/English-desktop figure screenshots actually viewed. Full article acceptance recorded separately.
Source locations checked:
- SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing · Read sections 2 and 3.1–3.4 with PDF2/3 actually viewed; additionally read section 3.5 text lines221–253 on self-contained model vocabulary, compiled normalization and Protocol Buffers. No throughput reproduction.
- SentencePiece normalization and whitespace options at fixed commit · Read normalization documentation through whitespace handling, model proto lines 235–250 and README API/packaging sections. Apache 2.0 header inspected. Library 0.2.1 behavior checked separately; README performance and raw-losslessness claims not adopted.
- SentencePiece 0.2.1 Python package · Read Python API encoding, in-memory training and release date (2025-08-12). Installed the official CPython 3.12 macOS ARM64 wheel into the project environment; no source build.
Related topics