File size: 2,697 Bytes
034ba67
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "tok-0000", "name": "BPE vs Unigram vs WordPiece comparison"}
{"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": "What is the difference between BPE, Unigram and WordPiece tokenization? When is each used?"}}
{"type": "message", "message": {"role": "assistant", "content": "All three are subword algorithms, but they learn the vocabulary differently and segment differently.\n\n**BPE (byte-pair encoding):** bottom-up. Start from characters/bytes, greedily merge the most frequent pair. Segmentation applies merges in learned order. Deterministic, simple, the default for GPT-2/3/4, Llama, Mistral.\n\n**WordPiece:** also bottom-up, but merges the pair that most improves *likelihood* (count divided by product of individual counts), not raw frequency. Segmentation is greedy longest-match-first with `##` continuation markers. Used by BERT and derivatives.\n\n**Unigram:** top-down. Start from a large vocabulary and prune tokens whose removal hurts total likelihood least (EM training). Segmentation picks the most probable split (Viterbi), and can *sample* alternative segmentations (subword regularization). Used by T5, mT5, ALBERT via SentencePiece.\n\n| | BPE | WordPiece | Unigram |\n|---|---|---|---|\n| direction | bottom-up | bottom-up | top-down |\n| merge score | frequency | likelihood gain | likelihood loss on removal |\n| segment | merge rules | longest match | best-probability split |\n| sampling | no | no | yes |\n\nWordPiece-style segmentation in a few lines:\n\n```python\ndef wordpiece_segment(word, vocab):\n    \"\"\"Greedy longest-match-first, ## marks continuations.\"\"\"\n    tokens, i = [], 0\n    while i < len(word):\n        end, cur = len(word), None\n        while end > i:\n            piece = word[i:end] if i == 0 else \"##\" + word[i:end]\n            if piece in vocab:\n                cur = piece\n                break\n            end -= 1\n        if cur is None:\n            return [\"[UNK]\"]\n        tokens.append(cur)\n        i = end\n    return tokens\n\nvocab = {\"un\", \"##aff\", \"##able\", \"low\", \"##er\", \"##est\", \"[UNK]\"}\nprint(wordpiece_segment(\"unaffable\", vocab))  # ['un', '##aff', '##able']\nprint(wordpiece_segment(\"lowest\", vocab))     # ['low', '##est']\nprint(wordpiece_segment(\"zzz\", vocab))        # ['[UNK]']\n```\n\nRule of thumb: BPE for decoder LLMs, WordPiece if you continue a BERT-style stack, Unigram when you need segmentation sampling or strong multilingual coverage."}}