配对计数与合并循环
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.