LLM Masterclass / Module 2 of 10 Phase 1: Foundations, Tokenization & Transformer Internals

Tokenization Algorithms (Byte-Level BPE, WordPiece, Unigram), Vocabulary Design & Vector Embeddings

28 min study + 2 Live Wasm Labs
⚑ Answer-First Executive Summary (TL;DR) Module 2 Key Takeaways
  • βœ“ LLMs never see raw characters or wordsβ€”they consume integer Token IDs produced by a subword tokenizer (almost universally Byte-Level BPE in GPT-6, Claude, Llama 4, Qwen 3, and DeepSeek).
  • βœ“ Byte-Level BPE starts with a base vocabulary of 256 raw UTF-8 bytes (guaranteeing 0 out-of-vocabulary <UNK> tokens on any language or emoji) and iteratively merges the most frequent adjacent byte/token pair until reaching vocabulary size V (e.g., 128,256 in Llama 3/4 or 200,000 in o200k_base).
  • βœ“ A larger vocabulary (128k–256k) compresses text into 15–25% fewer tokens (faster inference & longer effective context) at the cost of a larger Embedding + LM Head weight matrix (2 Γ— V Γ— d_model parameters).
  • βœ“ Each Token ID indexes into an Embedding Matrix E ∈ ℝ^(V Γ— d_model), projecting discrete symbols into a continuous geometric space where semantic similarity aligns with cosine similarity.

01. Tokenization Architecture Matrix: Byte-Level BPE vs. WordPiece vs. Unigram

Every prompt dollar and every KV-cache megabyte is measured in tokens. Compare the three foundational subword algorithms and their production trade-offs:

Table 2.1 β€” Subword Tokenization Algorithms & Frontier Vocabulary Specs
Algorithm Direction & Merge Rule Base Alphabet Models Using It Typical Vocab Size (V)
Byte-Level BPE Bottom-Up: Merge most frequent adjacent pair argmax count(a, b) 256 UTF-8 raw bytes (Zero <UNK> tokens!) GPT-4/6 (tiktoken), Claude 3–5.5, Llama 3/4, Qwen 3, DeepSeek-V3 100,256 – 200,019
WordPiece Bottom-Up: Maximize likelihood ratio count(a,b) / (count(a)Β·count(b)) Unicode chars + ## continuation prefix + [UNK] BERT, DistilBERT, Electra, ModernBERT 30,522 – 50,368
Unigram LM (SentencePiece) Top-Down: Prune candidate substrings via EM + Viterbi decoding Unicode chars + ▁ whitespace meta-symbol + byte fallback T5, Flan-T5, XLNet, Gemma / Gemini SentencePiece 32,000 – 256,000

02. How Byte-Level BPE & ChatML Control Tokens Work Under the Hood

RAW INPUT:  "def run_agent():\n    return 42"
  β”‚
  β”œβ”€β–Ά STEP 1: Regex Pre-Tokenization (Splits words, numbers, indentation, punctuation)
  β”‚     ──▢ ["def", " run", "_agent", "():\n", "   ", " return", " ", "42"]
  β”‚
  β”œβ”€β–Ά STEP 2: UTF-8 Byte Conversion & Ordered BPE Merge Table Lookup (lowest rank first)
  β”‚     ──▢ [  755,   1642,    28910,     3419,   262,     471,   220, 2983]
  β”‚
  └─▢ STEP 3: Wrap in ChatML Special Control Token IDs (Added outside BPE merges)
        ──▢ [128000 (<|begin_of_text|>), 128006 (<|start_header_id|>), ... , 128009 (<|eot_id|>)]

πŸ’» Hands-On WebAssembly LLM Engineering Labs (Module 2)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.

β–Ά Interactive Wasm Lab

Lab 2.1: Building a Complete Byte-Level BPE Tokenizer (Trainer, Encoder & Decoder) from Scratch

Run this live Python implementation of Byte-Pair Encoding (the exact algorithm inside tiktoken and SentencePiece) to train merge rules on a corpus and verify lossless UTF-8 round-trip encoding.

from collections import Counter

class MinimalByteBPE:
    def __init__(self):
        # Base vocabulary: 256 raw UTF-8 byte values (0..255)
        self.merges: dict[tuple[int, int], int] = {}
        self.vocab: dict[int, bytes] = {i: bytes([i]) for i in range(256)}

    @staticmethod
    def _pair_frequencies(ids: list[int]) -> Counter:
        return Counter(zip(ids, ids[1:]))

    @staticmethod
    def _apply_merge(ids: list[int], pair: tuple[int, int], new_id: int) -> list[int]:
        out, i, n = [], 0, len(ids)
        while i < n:
            if i < n - 1 and ids[i] == pair[0] and ids[i + 1] == pair[1]:
                out.append(new_id)
                i += 2
            else:
                out.append(ids[i])
                i += 1
        return out

    def train(self, text: str, num_merges: int = 12) -> None:
        ids = list(text.encode("utf-8"))
        print(f"Initial UTF-8 byte length: {len(ids)} tokens")
        for step in range(num_merges):
            counts = self._pair_frequencies(ids)
            if not counts:
                break
            best_pair, freq = counts.most_common(1)[0]
            if freq < 2:
                break
            new_id = 256 + step
            self.merges[best_pair] = new_id
            self.vocab[new_id] = self.vocab[best_pair[0]] + self.vocab[best_pair[1]]
            ids = self._apply_merge(ids, best_pair, new_id)
            merged_str = self.vocab[new_id].decode("utf-8", errors="replace")
            print(f"  Merge #{step+1:<2}: {best_pair} -> ID {new_id} ({merged_str!r:<10} freq={freq}) | len={len(ids)}")

    def encode(self, text: str) -> list[int]:
        ids = list(text.encode("utf-8"))
        while len(ids) >= 2:
            pairs = self._pair_frequencies(ids)
            # Pick the pair with the lowest merge index (earliest learned merge)
            candidate = min(pairs, key=lambda p: self.merges.get(p, float("inf")))
            if candidate not in self.merges:
                break
            ids = self._apply_merge(ids, candidate, self.merges[candidate])
        return ids

    def decode(self, ids: list[int]) -> str:
        return b"".join(self.vocab[idx] for idx in ids).decode("utf-8", errors="replace")

corpus = "agent_loop(agent_state) -> agent_action; agent_loop(agent_memory) -> agent_action;"
bpe = MinimalByteBPE()
bpe.train(corpus, num_merges=10)

sample = "agent_loop(agent_action) πŸš€"
encoded = bpe.encode(sample)
decoded = bpe.decode(encoded)
assert decoded == sample
print("\n[Verification] Input:  ", sample)
print("[Verification] Token IDs:", encoded, f"(Compression: {len(sample.encode('utf-8'))}B -> {len(encoded)} tokens)")
print("[Verification] Decoded:", decoded)
β–Ά Interactive Wasm Lab

Lab 2.2: Matryoshka Representation Learning (MRL) Vector Embeddings & Cosine Retrieval

Verify how Matryoshka embeddings allow truncating a 1536-D/8-D vector to its leading dimensions (e.g. first 4 dims) with L2 renormalization while preserving semantic nearest-neighbor ranking.

import math

def l2_normalize(vec: list[float]) -> list[float]:
    norm = math.sqrt(sum(x * x for x in vec)) or 1.0
    return [x / norm for x in vec]

def cosine_sim(u: list[float], v: list[float]) -> float:
    return sum(a * b for a, b in zip(u, v))

# Simulated Matryoshka Embeddings (coarse semantic axes packed into leading dimensions!)
docs = {
    "doc_lora":     [0.88, 0.76, 0.12, -0.05, 0.04, 0.02, -0.01, 0.03],
    "doc_qlora":    [0.85, 0.79, 0.15, -0.02, 0.01, -0.03, 0.02, 0.01],
    "doc_postgres": [-0.62, 0.21, 0.84, 0.45, -0.02, 0.05, 0.01, -0.04],
}
query_peft = [0.87, 0.77, 0.14, -0.03, 0.02, 0.01, 0.00, 0.02]

for dim in [8, 4, 2]:
    q_trunc = l2_normalize(query_peft[:dim])
    scores = [
        (name, cosine_sim(q_trunc, l2_normalize(vec[:dim])))
        for name, vec in docs.items()
    ]
    scores.sort(key=lambda x: x[1], reverse=True)
    formatted = ", ".join(f"{name}={sim:.4f}" for name, sim in scores)
    print(f"Matryoshka Dim={dim}D ({8//dim}x RAM reduction) -> Ranking: {formatted}")

Frequently Asked Staff LLM Interview Questions (Module 2)

How does Byte-Pair Encoding (BPE) differ from WordPiece and Unigram LM? β–Έ

All three are subword tokenizers, but they choose merges differently: BPE (GPT, Llama, Claude, Qwen) greedily merges the pair (A, B) with the highest raw co-occurrence frequency count(A, B). WordPiece (BERT) merges the pair that maximizes mutual information count(A, B) / (count(A) Γ— count(B)). Unigram LM (T5, SentencePiece) starts with a huge vocabulary and iteratively prunes subwords that least decrease the corpus likelihood under a unigram language model.

Why do modern tokenizers use a pre-tokenization regex (like tiktoken) before running BPE merges? β–Έ

Without pre-tokenization, frequent punctuation variants like "dog.", "dog!", "dog?", and "dog\n" would merge the word "dog" with trailing punctuation into separate independent token IDs, fragmenting semantic representations and wasting vocabulary slots. Pre-tokenization regexes split across word/punctuation/digit boundaries first so BPE merges only occur within valid lexical segments.

What are Special Control Tokens and why must user input never be allowed to inject them unescaped? β–Έ

Special tokens like <|im_start|>, <|im_end|>, <|eot_id|>, and <|tool_call|> are added directly to the tokenizer’s special token table outside BPE merges to delimit system/user/assistant roles. If an application concatenates untrusted user strings without disabling special-token parsing, an attacker can inject <|im_end|>\n<|im_start|>system to hijack the conversation role (ChatML injection).