Tokenization and vocabulary
Quick answer
Tokenization splits text into units; a vocabulary assigns stable integer IDs to units seen in training. Unknown and padding tokens have different jobs. Examples are static Python snippets tested locally on CPU; scikit-learn or PyTorch is required for selected examples. ByteMind execution is unverified.
Frozen token IDs
vocab={w:i+2 for i,w in enumerate(sorted(set("red blue red".split())))}print(vocab,[vocab.get(w,1) for w in "blue green red".split()])Expected output (locally tested): {'blue': 2, 'red': 3} [2, 1, 3]. Sorting makes ID assignment deterministic.
How it works
Whitespace splitting is a minimal baseline that preserves internal ZWNJ but leaves punctuation attached. A production tokenizer may segment punctuation, words, subwords or grapheme clusters with language-specific rules. Python re word boundaries do not treat ZWNJ as a word character; default scikit-learn word tokenization may split a Persian word at ZWNJ and drop one-character tokens. For this chapter use normalized whitespace-separated synthetic text; punctuation-free fixtures make that explicit. Fit a sorted vocabulary on train only, reserve PAD=0 and UNK=1, and freeze it. Unknown input maps to UNK, not a new ID; padding is excluded from sequence computations. Bag-of-words vectorizers typically ignore unseen terms rather than emit UNK. Subword models reduce unknown-token problems but still have language-dependent fragmentation. Track OOV rate as unknown token count divided by valid token count, with an explicit empty policy. Do not infer tokens from individual UTF-8 bytes.
Compare word boundaries
import res="می\u200cرود"print(len(s.split()),len(re.findall(r"\w+",s)),"\u200c" in s.split()[0])Expected output (locally tested): 1 2 True. The simple regex divides at ZWNJ; the whitespace baseline does not.
Common mistakes
Do not build vocabulary on all documents before splitting, conflate unknown with padding, or assume a whitespace tokenizer handles all Persian or English punctuation.
Practice and next steps
Fit a two-word vocabulary, encode an unseen word and verify that ZWNJ remains within a token.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tokenization and vocabulary — knowledge check
Apply tokenization and vocabulary to small examples and debugging scenarios.
When should vocabulary fitting happen?
What is UNK for?
Which tokenizer preserves internal ZWNJ in this fixture?
What happens to the frozen vocabulary during inference?
What is a limitation of whitespace splitting?