{"type": "session", "harness": "opencode", "id": "i18n-0000", "name": "BPE definition and training algorithm"} {"type": "message", "message": {"role": "system", "content": "You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal Python examples."}} {"type": "message", "message": {"role": "user", "content": "What is byte-pair encoding (BPE) and how does tokenizer training work? Include a small code example."}} {"type": "message", "message": {"role": "assistant", "content": "**Byte-pair encoding (BPE)** is a subword tokenization algorithm. It starts from single characters (or bytes) and repeatedly merges the most frequent adjacent pair until the vocabulary reaches a target size. Philip Gage (1994) proposed it for compression; Sennrich et al. (2016) adapted it for neural machine translation, and it is now the basis of most LLM tokenizers (GPT-2/3/4, Llama, Mistral).\n\n**Training:**\n1. Pre-tokenize text into words, split each word into symbols, append an end-of-word marker.\n2. Count every adjacent symbol pair, weighted by word frequency.\n3. Merge the single most frequent pair everywhere (add it to the vocabulary).\n4. Repeat steps 2-3 for N merges.\n\n**Worked example** (word frequencies: low x5, lower x2, newest x6, widest x3): the pair ('e', 's') occurs 9 times (newest x6 + widest x3), more than any other pair, so the first learned token is 'es'.\n\n```python\nfrom collections import Counter\n\ndef get_stats(vocab):\n \"\"\"Count adjacent symbol pairs, weighted by word frequency.\"\"\"\n pairs = Counter()\n for word, freq in vocab.items():\n syms = word.split()\n for i in range(len(syms) - 1):\n pairs[(syms[i], syms[i + 1])] += freq\n return pairs\n\ndef merge_pair(pair, vocab):\n \"\"\"Merge one pair everywhere it occurs.\"\"\"\n return {w.replace(' '.join(pair), ''.join(pair)): f for w, f in vocab.items()}\n\nvocab = {\n 'l o w ': 5,\n 'l o w e r ': 2,\n 'n e w e s t ': 6,\n 'w i d e s t ': 3,\n}\nfor _ in range(10):\n pairs = get_stats(vocab)\n if not pairs:\n break\n best = max(pairs, key=pairs.get) # most frequent pair\n vocab = merge_pair(best, vocab)\n print(best)\n```\n\n**Production notes:** modern tokenizers use *byte-level* BPE (base vocabulary = 256 UTF-8 bytes, e.g. GPT-2), so any input is encodable and there are no unknown tokens. Vocabulary size (typically 32k-256k) trades sequence length against embedding-table size. A tokenizer trained on English-only text still *runs* on other languages (bytes always work) but splits them into many tiny pieces — see the multilingual fertility note."}}