CS336.wiki
CS336 中文实验手册/字节级 BPE 分词器
反馈与讨论
ASSIGNMENT 01 / 2.5

训练分词器

2026 春季 · v26.0.3原文 p. 8–10对照 PDF ↗

2.5 BPE 训练实验#

先在 TinyStories 上训练字节级 BPE。下载方式见第 1 节。开始之前,建议浏览数据,了解语料内容。

并行预分词#

预分词通常是主要瓶颈。可以用内置的 multiprocessing 库加速。原指导书建议并行预分词时对语料分块,并确保分块边界位于特殊 token 的开头。

允许直接使用课程提供的 pretokenization_example.py 中用于确定分块边界的起始代码,再把各块分配给不同进程。

这种分块总是有效,因为本来就不希望跨文档边界合并。在本作业中,可以一直这样划分,不必处理超大语料完全没有 <|endoftext|> 的边缘情况。

预分词前移除特殊 token#

在用正则表达式进行预分词之前,应从语料或并行处理的分块中剔除特殊 token。务必按照特殊 token 进行切分,使合并不能跨越它划定的文本区域。例如:

[Doc 1]<|endoftext|>[Doc 2]

应分别预分词 [Doc 1] 与 [Doc 2],禁止跨文档边界合并。特殊 token 是训练中的硬分段边界,但不应参与合并频次统计。

原文指出,可以用 re.split 配合以 "|".join(special_tokens) 构成的分隔表达式,并谨慎使用 re.escape,因为特殊 token 中可能包含竖线。测试 test_train_bpe_special_tokens 会检查该行为。

优化合并步骤#

上页的朴素实现每次合并都遍历所有字节对以找出最高频候选,因此速度慢。但每次合并后,只有与被合并对发生重叠的字节对频次会改变。可以索引全部字节对的计数,并增量更新,而不必每次显式遍历所有字节对重新统计。这样可显著加速。不过,BPE 训练中的合并部分在 Python 中无法并行化。

低资源提示

性能分析

使用 cProfile、py-spy 等工具找出实现瓶颈,把优化精力放在那里。

低资源提示

缩小规模

不要一开始就在整个 TinyStories 上训练。先使用小型“调试数据集”,例如约 2.2 万篇文档的验证集,而不是约 212 万篇文档的完整数据。

更小的数据集、更小的模型等,是加快开发的一般策略。调试规模必须认真选择:要足够大,使主要瓶颈与完整配置一致,优化才能迁移;又不能大到每次运行都很久。

练习 train_bpe15 分

BPE 分词器训练

交付物: 编写一个函数,接收文本文件路径,训练字节级 BPE 分词器。至少支持以下输入:

输入 类型 含义
input_path str BPE 训练文本文件的路径。
vocab_size int 正整数,定义最终词表大小上限,包括初始字节、合并生成的词项和全部特殊 token。
special_tokens list[str] 要加入词表的特殊字符串。训练时将其视为禁止跨越的硬边界,不纳入合并统计。

返回:

输出 类型 含义
vocab dict[int, bytes] 从整数 token ID 映射到 token 字节串的词表。
merges list[tuple[bytes, bytes]] 按创建顺序排列的合并;每项表示第一个 token 与第二个 token 合并。

实现适配器 adapters.run_train_bpe,再运行 uv run pytest tests/test_train_bpe.py,应通过全部测试。

你也可以选择用 C++ 或 Rust 等系统语言实现关键部分,但可能耗费很多时间。C++ 可考虑 cppyy、nanobind,Rust 可考虑 PyO3。若这样做,请注意哪些操作复制内存、哪些直接读取 Python 内存,并留下构建说明,或保证仅凭 pyproject.toml 就能构建。

多数正则引擎对 GPT-2 正则支持不佳,支持的也多半很慢。课程确认 Oniguruma 速度尚可,支持负向前瞻;不过 Python 的 regex 包甚至更快。

练习 train_bpe_tinystories2 分

在 TinyStories 上训练 BPE

(a) 在 TinyStories 上训练字节级 BPE,最大词表为 10,000,将 <|endoftext|> 加为特殊 token。把词表与合并序列保存到磁盘,以便检查。训练花了多少时间和内存?词表中最长的 token 是什么?是否合理?

资源要求: 不使用 GPU,时间 ≤ 30 分钟,内存 ≤ 30 GB。

原文提示: 通过并行预分词,并利用以下两点,应该能把 BPE 训练时间降到 2 分钟以内:数据文件用 <|endoftext|> 分隔文档;BPE 合并之前,该 token 会被单独处理。

交付物: 一至两句话回答。

(b) 对代码进行性能分析。分词器训练的哪一部分最耗时?

交付物: 一至两句话回答。

接下来在 OpenWebText 上训练。和之前一样,建议先浏览数据集以了解内容。

练习 train_bpe_expts_owt2 分

在 OpenWebText 上训练 BPE

(a) 在 OpenWebText 上训练字节级 BPE,最大词表为 32,000。保存词表与合并序列。最长的 token 是什么?是否合理?

资源要求: 不使用 GPU,时间 ≤ 12 小时,内存 ≤ 100 GB。

交付物: 一至两句话回答。

(b) 对比在 TinyStories 与 OpenWebText 上训练得到的分词器。

交付物: 一至两句话回答。

一起把这一章读得更好

发现翻译、公式或排版错误?欢迎反馈。概念疑问和学习心得,也可以在本章讨论中交流。

直接选中正文,点击旁边的「反馈这处错误」,即可在页内填写并提交,无需登录。
English original 展开本章英文原文 PDF 文本提取

下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。

2.5 Experimenting with BPE Tokenizer Training
Let’s train a byte-level BPE tokenizer on the TinyStories dataset. Instructions to find / download the
dataset can be found in Section 1. Before you start, we recommend taking a look at the TinyStories
dataset to get a sense of what’s in the data.

Parallelizing pre-tokenization
You will find that a major bottleneck is the pre-tokenization step. You can speed up pre-tokenization by
parallelizing your code with the built-in library multiprocessing. Concretely, we recommend that in
parallel implementations of pre-tokenization, you chunk the corpus while ensuring your chunk boundaries
occur at the beginning of a special token. You are free to use the starter code at the following link
verbatim to obtain chunk boundaries, which you can then use to distribute work across your processes:
  https://github.com/stanford-cs336/assignment1-basics/blob/main/cs336_basics/pretokenization_example.py

This chunking will always be valid, since we never want to merge across document boundaries. For the
purposes of the assignment, you can always split in this way. Don’t worry about the edge case of receiving
a very large corpus that does not contain <|endoftext|>.

Removing special tokens before pre-tokenization
Before running pre-tokenization with the regex pattern (using re.finditer), you should strip out all
special tokens from your corpus (or your chunk, if using a parallel implementation). Make sure that you
split on your special tokens, so that no merging can occur across the text they delimit. For example, if
you have a corpus (or chunk) like [Doc 1]<|endoftext|>[Doc 2], you should split on the special token <|
endoftext|>, and pre-tokenize [Doc 1] and [Doc 2] separately, so that no merging can occur across the
document boundary. In other words, special tokens define hard segmentation boundaries during training,
but they should not themselves contribute to merge counts. This can be done using re.split with
"|".join(special_tokens) as the delimiter (with careful use of re.escape since | may occur in the special
tokens). The test test_train_bpe_special_tokens will test for this.

Optimizing the merging step
The naïve implementation of BPE training in the stylized example above is slow because for every merge,
it iterates over all byte pairs to identify the most frequent pair. However, the only pair counts that change
after each merge are those that overlap with the merged pair. Thus, BPE training speed can be improved
by indexing the counts of all pairs and incrementally updating these counts, rather than explicitly
iterating over each pair of bytes to count pair frequencies. You can get significant speedups with this
caching procedure, though we note that the merging part of BPE training is not parallelizable in Python.


 Low-Resource Tip: Profiling


   You should use profiling tools like cProfile or py-spy to identify the bottlenecks in your
   implementation, and focus on optimizing those.



 Low-Resource Tip: "Downscaling"


   Instead of jumping to training your tokenizer on the full TinyStories dataset, we recommend you
   first train on a small subset of the data: a “debug dataset”. For example, you could train your
   tokenizer on the TinyStories validation set instead, which is 22K documents instead of 2.12M.
   This illustrates a general strategy of downscaling whenever possible to speed up development: for

 example, using smaller datasets, smaller model sizes, etc. Choosing the size of the debug dataset
 or hyperparameter config requires careful consideration: you want your debug set to be large
 enough to have the same bottlenecks as the full configuration (so that the optimizations you make
 will generalize), but not so big that it takes forever to run.



Problem (train_bpe): BPE Tokenizer Training (15 points)


 Deliverable: Write a function that, given a path to an input text file, trains a (byte-level) BPE
 tokenizer. Your BPE training function should handle (at least) the following input parameters:
 Input
   input_path: str   Path to a text file with BPE tokenizer training data.
   vocab_size: int    A positive integer that defines the maximum final vocabulary size (including
   the initial byte vocabulary, vocabulary items produced from merging, and any special tokens).
   special_tokens: list[str]   A list of strings to add to the vocabulary. During training, treat
   them as hard boundaries that prevent merges across their spans, but do not include them when
   computing merge statistics.
 Your BPE training function should return the resulting vocabulary and merges:
 Output
   vocab: dict[int, bytes]   The tokenizer vocabulary, a mapping from int (token ID in the
   vocabulary) to bytes (token bytes).
   merges: list[tuple[bytes, bytes]]    A list of BPE merges produced from training. Each list
   item is a tuple of bytes (<token1>, <token2>), representing that <token1> was merged with
   <token2>. The merges should be ordered by order of creation.

 To test your BPE training function against our provided tests, you will first need to implement
 the test adapter at [adapters.run_train_bpe] . Then, run uv run pytest tests/
 test_train_bpe.py. Your implementation should be able to pass all tests. Optionally (this could
 be a large time-investment), you can implement the key parts of your training method using some
 systems language, for instance C++ (consider cppyy or nanobind) or Rust (using PyO3). If you do
 this, be aware of which operations require copying vs reading directly from Python memory, and
 make sure to leave build instructions, or make sure it builds using only pyproject.toml. Also note
 that the GPT-2 regex is not well-supported in most regex engines and will be too slow in most
 that do. We have verified that Oniguruma is reasonably fast and supports negative lookahead, but
 the regex package in Python is, if anything, even faster.



Problem (train_bpe_tinystories): BPE Training on TinyStories (2 points)


  (a) Train a byte-level BPE tokenizer on the TinyStories dataset, using a maximum vocabulary
      size of 10,000. Make sure to add the TinyStories <|endoftext|> special token to the
      vocabulary. Serialize the resulting vocabulary and merges to disk for further inspection. How
      much time and memory did training take? What is the longest token in the vocabulary? Does
      it make sense?
      Resource requirements: ≤ 30 minutes (no GPUs), ≤ 30 GB RAM

       Hint You should be able to get under 2 minutes for BPE training using multiprocessing
       during pre-tokenization and the following two facts:
        (a) The <|endoftext|> token delimits documents in the data files.
       (b) The <|endoftext|> token is handled as a special case before the BPE merges are applied.
       Deliverable: A one-to-two sentence response.
   (b) Profile your code. What part of the tokenizer training process takes the most time?
       Deliverable: A one-to-two sentence response.


Next, we’ll try training a byte-level BPE tokenizer on the OpenWebText dataset. As before, we
recommend taking a look at the dataset to better understand its contents.


 Problem (train_bpe_expts_owt): BPE Training on OpenWebText (2 points)


   (a) Train a byte-level BPE tokenizer on the OpenWebText dataset, using a maximum vocabulary
       size of 32,000. Serialize the resulting vocabulary and merges to disk for further inspection.
       What is the longest token in the vocabulary? Does it make sense?
       Resource requirements: ≤ 12 hours (no GPUs), ≤ 100 GB RAM
       Deliverable: A one-to-two sentence response.
   (b) Compare and contrast the tokenizer that you get training on TinyStories versus
       OpenWebText.
       Deliverable: A one-to-two sentence response.

关于这一章的疑问、理解与心得,都可以在这里交流。阅读无需登录;发表评论或回复时使用 GitHub 账号。

正在加载本章讨论…

欢迎交流概念与阅读疑问,请勿发布作业完整实现或题目答案。

输入中文、英文术语或题号,例如 RoPE、检查点、train_bpe。