tinycodinglm / tok /tok-0000.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 19)
034ba67 verified
|
Raw History Blame Contribute Delete
2.7 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

What is the difference between BPE, Unigram and WordPiece tokenization? When is each used?

Assistant

All three are subword algorithms, but they learn the vocabulary differently and segment differently.

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.

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.

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.

BPE WordPiece Unigram
direction bottom-up bottom-up top-down
merge score frequency likelihood gain likelihood loss on removal
segment merge rules longest match best-probability split
sampling no no yes

WordPiece-style segmentation in a few lines:

python
def wordpiece_segment(word, vocab):
    """Greedy longest-match-first, ## marks continuations."""
    tokens, i = [], 0
    while i < len(word):
        end, cur = len(word), None
        while end > i:
            piece = word[i:end] if i == 0 else "##" + word[i:end]
            if piece in vocab:
                cur = piece
                break
            end -= 1
        if cur is None:
            return ["[UNK]"]
        tokens.append(cur)
        i = end
    return tokens

vocab = {"un", "##aff", "##able", "low", "##er", "##est", "[UNK]"}
print(wordpiece_segment("unaffable", vocab))  # ['un', '##aff', '##able']
print(wordpiece_segment("lowest", vocab))     # ['low', '##est']
print(wordpiece_segment("zzz", vocab))        # ['[UNK]']

Rule of thumb: BPE for decoder LLMs, WordPiece if you continue a BERT-style stack, Unigram when you need segmentation sampling or strong multilingual coverage.