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
{"type": "session", "harness": "opencode", "id": "tok-0001", "name": "SentencePiece concepts and whitespace handling"}
{"type": "message", "message": {"role": "system", "content": "You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal code examples."}}
{"type": "message", "message": {"role": "user", "content": "How does SentencePiece handle whitespace and normalization? Why can it detokenize losslessly?"}}
{"type": "message", "message": {"role": "assistant", "content": "SentencePiece treats the input as a raw Unicode stream — no pre-tokenization, no language-specific rules. Three ideas make this work:\n\n1. **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.\n2. **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.\n3. **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]`.\n\nThe whitespace convention in pure Python:\n\n```python\nimport re\n\ndef sp_pretokenize(text):\n \"\"\"SentencePiece-style: whitespace sticks to the following piece.\"\"\"\n return re.findall(r\"\\s*\\S+\", text)\n\npieces = sp_pretokenize(\"Hello world \\u4f60\\u597d\")\nprint(pieces) # ['Hello', ' world', ' \\u4f60\\u597d']\nassert \"\".join(pieces) == \"Hello world \\u4f60\\u597d\" # lossless\n```\n\nPractical 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."}}