配對計數與合併循環
Agent 輔助工程檢查
前置要求
完成第 38 天。如受阻,使用第 35 天的回退連結複習機率與 Python。
學習目標
追蹤 BPE 訓練循環 — 統計相鄰配對、將最高頻配對合併為新 ID、迭代推進 — 並透過手工推導完整重現經過驗證的合併表(包含空字串與 Unicode 位元組邊界)。
操作指引
從 'aaabdaaabac' 的位元組 ID 序列出發:[97,97,97,98,100,97,97,97,98,97,99]。必做工作:在每一輪中統計所有相鄰配對;最高頻配對獲得下一個可用空閒 ID(256,接著是 257,以此類推);頻次相同時按首次出現位置打破平手(與 Python 基於插入順序字典的 max() 行為一致)。寫出合併追蹤過程,並用 Python 簡短指令碼驗證。空字串 '' 的配對循環直接回傳空。Unicode 字串會先分解為 UTF-8 位元組,再走完全相同的合併循環。選做工作:繼續推演第四次合併並寫出新生成的詞元名稱。
自主實作與記錄
手工追蹤在 'aaabdaaabac' 上進行的 3 次合併:記錄每輪的配對計數、選中的配對以及變換後的新序列。在核對答案前預估最終詞元數與詞彙表大小。
第 1 輪:(97,97) 出現 4 次 → 分配 ID 256;序列變為 [256,97,98,100,256,97,98,97,99]。第 2 輪:(256,97) 與 (97,98) 均出現 2 次打平 — 首次出現的 (256,97) 勝出 → 分配 257。第 3 輪:(257,98) 出現 2 次 → 分配 258。
驗證追蹤:合併表 {(97,97)→256 ('aa'), (256,97)→257 ('aaa'), (257,98)→258 ('aaab')};最終 ID 序列為 [258,100,258,97,99],即對應子詞 'aaab','d','aaab','a','c' — 11 個原始位元組被壓縮為 5 個詞元(壓縮比 2.2×),詞彙表規模為 256+3=259。對空字串 '' 產生 0 詞元。
手寫推導在不查閱參考資料或使用 AI 的情況下,完整重現全部 3 次合併、先現平手打破規則、最終詞元列表以及 259 的詞彙表規模。
權威來源資源與權利證明
minbpe: Minimal Byte-Pair Encoding tokenizer (Let's build the GPT Tokenizer)
對應章節 / 時間戳: minbpe/base.py: get_stats pair counting and merge loop; minbpe/basic.py BasicTokenizer
驗證版本與日期: commit 1acefe8 (Verified: 2026-10-30)
The reference minimal implementation whose pair-count and merge loop the lesson traces by hand.
Basic Python and Day 37 bytes/code points
The lesson re-implements the merge loop locally and prints a verified merge trace.
對比候選資源與選型分析 (3)
Production BPE with Rust core and regex pre-tokenization; selected as the production contrast source rather than the primary teaching implementation.
High-quality BPE coverage but frames tokenization through library APIs; minbpe exposes the raw merge loop for hand tracing.
Industrial tokenizer trainer supporting BPE and unigram models; C++ core hides the teaching mechanics.
Neural Machine Translation of Rare Words with Subword Units
對應章節 / 時間戳: Section 3: byte-pair encoding adapted from compression to subword segmentation
驗證版本與日期: ACL 2016 (Verified: 2026-10-30)
Primary source that introduced BPE as a subword segmentation algorithm for neural sequence models.
Basic probability and text processing
The lesson teaches the complete merge algorithm with worked traces independent of the paper text.
對比候選資源與選型分析 (2)
Related likelihood-scored variant used in BERT; paywalled and less aligned with frequency-greedy teaching merges.
Strong probabilistic alternative segmentation; deferred because deterministic BPE merges are more hand-traceable at this stage.