37 / 90

第 37 天:从文本到词元 — Unicode、字节编码与词汇表

把原始文本变成词元 ID:区分字符、Unicode 码位与 UTF-8 字节序列;构建确定性词汇表;并复现任何语言模型基线都要使用的 text_tools train/val/test 数据产物。所有工作都计入 480 分钟台账。

模型与训练 480 分钟有效学习(8 小时专注学习)
01 120 分钟

从字符到字节:码位与 UTF-8

Agent 辅助工程检查

前置要求

完成第 36 天。如受阻,使用第 35 天的回退链接复习概率与 Python。

学习目标

区分可见字符、其 Unicode 码位与其 UTF-8 字节序列;先预测字节数再测量;针对空串、ASCII、带重音字符、中日韩字符与 emoji 记录预测与观测的对照。

操作指引

字符是读者看到的东西;码位是它的 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 | 原始出处链接 ↗

对应章节 / 范围: 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 | 原始出处链接 ↗

对应章节 / 范围: 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,对文本做无损编码/解码,并为训练中从未出现的符号选定明确策略。

操作指引

分词器需要两张表: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 | 原始出处链接 ↗

对应章节 / 范围: 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 | 原始出处链接 ↗

对应章节 / 范围: 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 的确定性划分产物并阅读清单(manifest),使下游所有模型只在 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 行文件预测同样的划分。指出清单中哪些字段证明确定性、以及没有任何索引同时出现在两个划分里。

独立掌握标准

你能重新生成产物,引用精确的划分计数与证明确定性、互不相交的清单字段,并说明为什么计数、词汇表与合并表只能在 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 | 原始出处链接 ↗

对应章节 / 范围: 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 | 原始出处链接 ↗

对应章节 / 范围: 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。必做工作:先在草稿日志中写下全部四个预测答案,再用 Python 与 CLI 逐一验证。选做工作:举一个对嘈杂语料合理使用 --errors ignore 的例子。

自主演练与记录

闭卷作答:(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 下会出现哪个字符?

独立掌握标准

四个预测全部在无辅助情况下与观测输出一致;每个失误都连同用于修复的回退链接(第 35 天复习或对应的第 37 天活动)一并记录。

权威源资源与权利证明

linking PSF License Version 2

Python Unicode HOWTO

作者 / 机构: Python Software Foundation | 原始出处链接 ↗

对应章节 / 范围: 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 | 原始出处链接 ↗

对应章节 / 范围: 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.