tinycodinglm / tok /tok-0001.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 19)
034ba67 verified
|
Raw History Blame Contribute Delete
2.16 kB
opencode trace
System You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal code examples.

You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal code examples.

User

How does SentencePiece handle whitespace and normalization? Why can it detokenize losslessly?

Assistant

SentencePiece treats the input as a raw Unicode stream — no pre-tokenization, no language-specific rules. Three ideas make this work:

  1. Whitespace is a symbol: every space becomes ▁ (U+2581) and stays inside the following piece. So Hello world segments as Hello, ▁world — joining pieces reproduces the input exactly, including multiple spaces. BPE/WordPiece implementations that split on spaces first cannot do this.
  2. Dummy prefix: by default (add_dummy_prefix=True) a ▁ is prepended, so a sentence-initial word and a mid-sentence word share the same piece (▁Hello), keeping the vocabulary small.
  3. Normalization + byte fallback: NFKC normalization is applied first (full-width A and A merge), and with byte_fallback=true any unseen character degrades to UTF-8 byte pieces instead of [UNK].

The whitespace convention in pure Python:

python
import re

def sp_pretokenize(text):
    """SentencePiece-style: whitespace sticks to the following piece."""
    return re.findall(r"\s*\S+", text)

pieces = sp_pretokenize("Hello world  \u4f60\u597d")
print(pieces)                    # ['Hello', ' world', '  \u4f60\u597d']
assert "".join(pieces) == "Hello world  \u4f60\u597d"  # lossless

Practical notes: train with character_coverage=1.0 for Latin/Cyrillic-heavy data but 0.995+ for CJK-heavy data (else rare kanji flood the vocab); keep split_digits in mind for math-heavy corpora; and always evaluate fertility per script, since SentencePiece will happily learn an English-only vocabulary that byte-falls-back everything else.