ペアのカウントとマージループ
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 バイト列に分解され、まったく同じマージループに従います。任意の作業:4 回目のマージまで進め、生成されるトークンを特定してください。
演習と予測記録
'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.