37 / 90

Day 37: テキストからトークンへ ― Unicode、バイトエンコーディング、語彙

生テキストをトークン ID に変換する。文字・Unicode コードポイント・UTF-8 バイト列を区別し、決定的な語彙を構築し、あらゆる言語モデル基盤が消費する text_tools の train/val/test アーティファクトを再現する。すべての作業は 480 分台帳の中で行う。

モデルと訓練 480 アクティブ分(集中学習 8 時間)
01 120 分

文字からバイトへ:コードポイントと UTF-8

Agent支援エンジニアリング確認

前提条件

Day 36 を完了していること。詰まった場合は Day 35 の回復リンクで確率と Python を復習すること。

学習目標

目に見える文字、その Unicode コードポイント、その UTF-8 バイト列を区別する。測定前にバイト数を予測し、空文字列・ASCII・アクセント付き・CJK・絵文字について予測と観測の比較を記録する。

手順

文字は読者に見えるもの、コードポイントはその Unicode 番号(U+XXXX と表記)、エンコーディングはコードポイントをバイト列に変換する規則である。必須作業:予測してから python3 -c "s='猫aé😀'; print(len(s), [hex(ord(c)) for c in s], list(s.encode('utf-8')))" を実行し、各予測と比較する。任意作業:同じ文字列を UTF-16 でエンコードし、バイト数を比較する。

演習と予測記録

s='猫aé😀' と空文字列 '' について、len(s)、コードポイント、UTF-8 バイト列を予測する。次に Python で検証し、なぜバイト数がコードポイント数と異なるかを説明する。

独立習得基準

空文字列を含むすべての探索文字列で、書いた予測が観測された ord() と encode() の出力と一致し、コードポイント範囲から UTF-8 バイト数への対応規則を述べられること。

公式ソースリソースと権利証跡

linking PSF License Version 2

Python Unicode HOWTO

著者・提供機関: Python Software Foundation | オリジナル出所URL ↗

該当セクション・範囲: Sections: Definitions of Character, Code Point, and Encodings (UTF-8)

検証バージョンと日付: Python 3.12 documentation (Verified: 2026-10-30)

選定理由:

Normative reference for Python 3 code points, encodings, and variable-length UTF-8 byte behavior used in every tokenization step.

ソース前提知識:

Basic Python strings and byte literals

安全フォールバック(オフライン回復性):

The lesson defines every required Unicode concept locally and all commands run offline.

比較対象候補リソースと選定評価 (2)
Unicode Standard (unicode.org) official documentation ↗ compared_alternative [Unicode License Agreement / Terms of Use]

Exhaustive normative standard but far too deep for a first contact; the Python HOWTO teaches the same code point/encoding distinction in executable form.

Strong motivation and history but pre-Python-3 and not runnable; retained as optional background reading only.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

minbpe: Minimal Byte-Pair Encoding tokenizer (Let's build the GPT Tokenizer)

著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

該当セクション・範囲: README exercise flow and minbpe/base.py; lecture segment on Unicode code points vs raw bytes

検証バージョンと日付: commit 1acefe9 (Verified: 2026-10-30)

選定理由:

Standard teaching reference connecting Unicode code points, UTF-8 bytes, and subword token ids for GPT-style tokenizers.

ソース前提知識:

Basic Python and strings

安全フォールバック(オフライン回復性):

The lesson re-implements the same algorithms locally in pure Python with verified outputs.

比較対象候補リソースと選定評価 (3)
OpenAI tiktoken ↗ compared_alternative [MIT]

Production BPE with Rust core and regex pre-tokenization; selected as the production contrast source rather than the primary teaching implementation.

Hugging Face tokenizers + NLP course chapter 6 ↗ compared_alternative [Apache-2.0 (library) / CC BY-NC-SA? (course text varies)]

High-quality BPE coverage but frames tokenization through library APIs; minbpe exposes the raw merge loop for hand tracing.

Google SentencePiece ↗ compared_alternative [Apache-2.0]

Industrial tokenizer trainer supporting BPE and unigram models; C++ core hides the teaching mechanics.

02 120 分

語彙とトークン ID 対応表

独立習得確認(AI 支援なし)

前提条件

前の活動を完了していること。詰まった場合は記載の回復リンクを使うこと。

学習目標

すべての相異なる記号を安定した整数 ID に対応づける決定的な語彙を構築し、テキストを可逆にエンコード・デコードし、訓練時に現れなかった記号への明示的な方針を選ぶ。

手順

トークナイザには 2 つの表が必要:stoi(記号→ID)と itos(ID→記号)。必須作業:訓練テキストの相異なる記号をソート順に ID 0..V-1 で割り当て、len(vocab) を の ID として予約し、探索文字列をエンコード・デコードする。任意作業: を必要としない 256 エントリのバイトレベル語彙と比較する。

演習と予測記録

訓練テキスト 'banana' について:ソート済み文字語彙を作り、'banana' と 'cab' をエンコードし、最初の結果をデコードし、 を使って 'banana!' をエンコードする。次に 'é猫' を UTF-8 バイトとしてエンコードし、なぜバイトレベル入力が に到達しないかを述べる。

独立習得基準

任意の短い訓練テキストについて、語彙表を書き、探索文字列を手で正しくエンコード・デコードでき、いつ <unk> が必要で、いつバイトレベルの網羅がそれを不要にするか説明できること。

公式ソースリソースと権利証跡

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

minbpe: Minimal Byte-Pair Encoding tokenizer (Let's build the GPT Tokenizer)

著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

該当セクション・範囲: minbpe/base.py: vocab dict, ids<->bytes mapping, encode/decode contract

検証バージョンと日付: commit 1acefe9 (Verified: 2026-10-30)

選定理由:

Shows the exact vocab, merges, and encode/decode invariants a teaching tokenizer must satisfy.

ソース前提知識:

Basic Python dicts and lists

安全フォールバック(オフライン回復性):

All mapping exercises are re-implemented locally with verified expected ids.

比較対象候補リソースと選定評価 (3)
OpenAI tiktoken ↗ compared_alternative [MIT]

Production BPE with Rust core and regex pre-tokenization; selected as the production contrast source rather than the primary teaching implementation.

Hugging Face tokenizers + NLP course chapter 6 ↗ compared_alternative [Apache-2.0 (library) / CC BY-NC-SA? (course text varies)]

High-quality BPE coverage but frames tokenization through library APIs; minbpe exposes the raw merge loop for hand tracing.

Google SentencePiece ↗ compared_alternative [Apache-2.0]

Industrial tokenizer trainer supporting BPE and unigram models; C++ core hides the teaching mechanics.

linking MIT License

tiktoken: Fast byte-pair encoding tokenizer used by OpenAI models

著者・提供機関: OpenAI | オリジナル出所URL ↗

該当セクション・範囲: README: encoding.get_encoding("cl100k_base"), encode/decode API, special token policy

検証バージョンと日付: Verified 2026-10-30

選定理由:

Production reference that contrasts a teaching tokenizer's explicit vocab dict with industrial byte-level BPE ranks and special tokens.

ソース前提知識:

Basic Python

安全フォールバック(オフライン回復性):

The lesson's vocabulary/id exercises run entirely on a local Python dict with fixed expected values.

比較対象候補リソースと選定評価 (2)
Hugging Face tokenizers library ↗ compared_alternative [Apache-2.0]

Broad production tokenizer framework with training APIs; tiktoken is a cleaner contrast for GPT-style compatibility claims.

Google SentencePiece ↗ compared_alternative [Apache-2.0]

Widely used trainer/tokenizer for open models; treated as further production context rather than the contrast reference.

03 120 分

決定的な train/val/test 分割と出所管理

Agent支援エンジニアリング確認

前提条件

前の活動を完了していること。詰まった場合は記載の回復リンクを使うこと。

学習目標

text_tools の決定的な分割アーティファクトを再現してマニフェストを読み、下流のすべてのモデルがカウントの学習に train のみ、選択に val を使い、test には触れない状態を確認する。

手順

必須作業:python3 projects/text_tools/cli.py --input data/names.txt --split --output-dir /tmp/lm-data(既定値:seed 42、比率 0.8/0.1/0.1)を実行し、/tmp/lm-data/manifest.json を開いて split_counts、split_sha256、leakage_check を確認する。別ディレクトリに再実行し、ハッシュが一致することを確認する。任意作業:--seed 99 で繰り返し、カウントは同じでもメンバーシップが変わることを観察する。

演習と予測記録

実行前に 32,033 行コーパスの train/val/test 行数を予測し、検証する。10 行ファイルについても同じ分割を予測する。決定性と、どのインデックスも 2 つの分割に現れないことを証明するマニフェストのフィールドを述べる。

独立習得基準

アーティファクトを再生成でき、正確な分割数と、決定性・非重複を証明するマニフェストのフィールドを引用でき、カウント・語彙・マージを train でのみ学習できる理由を述べられること。

公式ソースリソースと権利証跡

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

該当セクション・範囲: README and notebook part 1: names.txt corpus, 90% train / 5% dev / 5% test split rationale

検証バージョンと日付: Verified 2026-10-30

選定理由:

Uses the same data/names.txt corpus family and demonstrates why model fitting must see only the training split while dev/test remain held out.

ソース前提知識:

Basic Python

安全フォールバック(オフライン回復性):

Local projects/text_tools/cli.py produces the deterministic splits and manifest offline.

比較対象候補リソースと選定評価 (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

著者・提供機関: Stanford University CS336 Staff | オリジナル出所URL ↗

該当セクション・範囲: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

検証バージョンと日付: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

選定理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

ソース前提知識:

Python systems programming

安全フォールバック(オフライン回復性):

Local projects/text_tools deterministic artifacts provide the complete pipeline offline.

比較対象候補リソースと選定評価 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

04 120 分

独立習得確認:バイト、ID、分割の証跡

独立習得確認(AI 支援なし)

前提条件

前の活動をすべて完了していること。詰まった場合は記載の回復リンクを使うこと。

学習目標

支援なしで、コードポイント/バイトの計算、語彙のエンコード・デコード、分割数、不正入力の方針を再現し、外した項目について正直な回復計画を記録する。

手順

この確認中は解答や AI を参照しないこと。必須作業:4 つの回答すべてを下書きログで予測してから、Python と CLI で 1 つずつ検証する。任意作業:ノイズの多いコーパスに --errors ignore を使う正当な用途を 1 つ述べる。

演習と予測記録

閉じた状態で:(a) 'é猫' のコードポイント数と UTF-8 バイト数は? (b) 語彙 {a:0,b:1,c:2} で encode('cab') は? (c) 10 行を 0.8/0.1/0.1 で分割すると各行数は? (d) 不正バイト 0xFF を含むファイルで --errors strict の終了コードは? replace ではどの文字が現れる?

独立習得基準

4 つの予測すべてが支援なしで観測出力と一致し、外した項目には修復に使う回復リンク(Day 35 復習または対応する Day 37 活動)を併記していること。

公式ソースリソースと権利証跡

linking PSF License Version 2

Python Unicode HOWTO

著者・提供機関: Python Software Foundation | オリジナル出所URL ↗

該当セクション・範囲: Sections: Encodings, UTF-8 rules, and error handling strategies

検証バージョンと日付: Python 3.12 documentation (Verified: 2026-10-30)

選定理由:

Normative reference for the strict/replace decoding behavior verified in the mastery check.

ソース前提知識:

Basic Python strings and byte literals

安全フォールバック(オフライン回復性):

All mastery-check answers are computable with a local Python interpreter.

比較対象候補リソースと選定評価 (2)
Unicode Standard (unicode.org) official documentation ↗ compared_alternative [Unicode License Agreement / Terms of Use]

Exhaustive normative standard but far too deep for a first contact; the Python HOWTO teaches the same code point/encoding distinction in executable form.

Strong motivation and history but pre-Python-3 and not runnable; retained as optional background reading only.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

著者・提供機関: Andrej Karpathy | オリジナル出所URL ↗

該当セクション・範囲: Corpus-to-tensor pipeline: stoi/itos lookup tables built from the training split only

検証バージョンと日付: Verified 2026-10-30

選定理由:

Reinforces that vocabulary tables and counts are fit on training data only, the rule assessed in this check.

ソース前提知識:

Basic Python

安全フォールバック(オフライン回復性):

The local deterministic artifacts in projects/text_tools provide all required evidence offline.

比較対象候補リソースと選定評価 (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.