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

BPE 训练原理

2026 春季 · v26.0.3原文 p. 5–7对照 PDF ↗

2.4 BPE 分词器训练#

BPE 训练包含三个主要步骤。

初始化词表#

分词器词表在字节串 token 与整数 ID 之间建立一一映射。字节级 BPE 的初始词表就是全部字节;字节有 256 种可能值,因此初始词表大小为 256。

预分词#

理论上可以直接统计语料中相邻字节的频率,从最频繁的一对开始合并,但每次合并都重新遍历完整语料会非常昂贵。直接跨语料合并,还可能产生仅标点不同的 token,例如 “dog!” 与 “dog.”;它们语义可能很接近,却拥有完全不同的 ID。

为此,先对语料进行预分词(pre-tokenization),即一种粗粒度切分,用来帮助统计字符对。假设预词项 “text” 出现 10 次,那么其中相邻的 “t”“e” 可以一次计数 10,而不必每次回到语料中查找。在字节级 BPE 中,每个预词项都表示为 UTF-8 字节序列。

Sennrich 等人 [3] 的原始实现简单地按空白切分;基于 SentencePiece 的一些分词器,如 Llama 1、2,也采用这种方式。多数现代分词器沿用 GPT-2 [6] 的正则预分词方法。本作业使用来自 tiktoken PR #234 的等价、略易读版本:

指导书原文
>>> PAT = r"""'(?:[sdmt]|ll|ve|re)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""

原文交互示例将 “some text that i'll pre-tokenize” 切分为 “some”、“ text”、“ that”、“ i”、“'ll”、“ pre”、“-”、“tokenize”。建议交互尝试一些文本来理解行为。实际构建预词项频次映射时,应该使用 re.finditer,避免额外保存全部预分词结果;该正则需要 regex 包。

计算 BPE 合并#

将文本转成预词项、再表示为 UTF-8 字节后,就可以训练 BPE:迭代统计相邻字节对,找出频率最高的一对 (“A”, “B”),将其所有出现位置替换为新 token “AB”,再把新 token 加入词表。因此,最终词表大小为初始词表大小加上执行的合并次数。

为了效率,训练时不考虑跨预词项边界的字节对。若多个候选对频率相同,必须确定性地选择字典序较大的一对。例如 (“A”, “B”)、(“A”, “C”)、(“B”, “ZZ”)、(“BA”, “A”) 并列时,应选 (“BA”, “A”)。

原始 BPE [3] 使用词尾 token。本作业的字节级 BPE 不额外加入词尾 token,因为空白和标点也已包含在字节词表中,学到的合并会自然反映这些边界。

特殊 token#

某些字符串用于表示文档边界等元数据,例如 <|endoftext|>。编码时,它们应始终保留为单个 token,即单个整数 ID,而不能被拆开;模型也据此知道何时停止生成。因此,特殊 token 必须加入词表,并具有固定 ID。

Sennrich 等人 [3] 的算法 1 提供了一个较低效、基本遵循上述步骤的 BPE 训练实现。原指导书建议先实现并测试这一过程,以检查理解。

原文示例 bpe_example

BPE 训练示例

以下是改编自 [3] 的简化例子。语料为:

low low low low low
lower lower widest widest widest
newest newest newest newest newest newest

词表含有特殊 token <|endoftext|>。

词表。 用该特殊 token 与 256 个字节值初始化词表。

预分词。 为突出合并过程,此例只按空白切分,得到频次表:

{low: 5, lower: 2, widest: 3, newest: 6}

可用 dict[tuple[bytes, ...], int] 表示,例如 {(l,o,w): 5, …}。即使只有单个字节,在 Python 中也使用 bytes 对象;Python 没有单独的 byte 类型,就像没有单独的 char 类型。

合并。 首轮相邻字节对频次为:

{lo: 7, ow: 7, we: 8, er: 2, wi: 3, id: 3,
 de: 3, es: 9, st: 9, ne: 6, ew: 6}

(“e”, “s”) 与 (“s”, “t”) 并列,故选字典序更大的 (“s”, “t”)。合并后得到:

{(l,o,w): 5, (l,o,w,e,r): 2,
 (w,i,d,e,st): 3, (n,e,w,e,st): 6}

第二轮最频繁的是 (e, st),计数为 9,得到:

{(l,o,w): 5, (l,o,w,e,r): 2,
 (w,i,d,est): 3, (n,e,w,est): 6}

继续下去,合并序列为:

['s t', 'e st', 'o w', 'l ow', 'w est', 'n e',
 'ne west', 'w i', 'wi d', 'wid est', 'low e', 'lowe r']

若只执行 6 次合并,词表为特殊 token、256 个字节以及 st、est、ow、low、west、ne。使用该词表与合并序列,单词 newest 编码为 [ne, west]。

一起把这一章读得更好

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

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

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

2.4 BPE Tokenizer Training
The BPE tokenizer training procedure consists of three main steps.

Vocabulary initialization
The tokenizer vocabulary is a one-to-one mapping from bytestring token to integer ID. Since we’re
training a byte-level BPE tokenizer, our initial vocabulary is simply the set of all bytes. Since there are
256 possible byte values, our initial vocabulary is of size 256.

Pre-tokenization
Once you have a vocabulary, you could, in principle, count how often bytes occur next to each other in
your text and begin merging them starting with the most frequent pair of bytes. However, this is quite
computationally expensive, since we’d have to take a full pass over the corpus each time we merge. In

addition, directly merging bytes across the corpus may result in tokens that differ only in punctuation
(e.g., dog! vs. dog.). These tokens would get completely different token IDs, even though they are likely
to have high semantic similarity (since they differ only in punctuation).
To avoid this, we pre-tokenize the corpus. You can think of this as a coarse-grained tokenization over the
corpus that helps us count how often pairs of characters appear. For example, the word 'text' might be a
pre-token that appears 10 times. In this case, when we count how often the characters ‘t’ and ‘e’ appear
next to each other, we will see that the word ‘text’ has ‘t’ and ‘e’ adjacent and we can increment their
count by 10 instead of looking through the corpus. Since we’re training a byte-level BPE model, each pre-
token is represented as a sequence of UTF-8 bytes.
The original BPE implementation of R. Sennrich et al. [3] pre-tokenizes by simply splitting on whitespace
(i.e., s.split(" ")). This method is still found in tokenizers based on SentencePiece (for instance the
Llama 1 and 2 tokenizer).
Most modern tokenizers use a regex-based pre-tokenizer, a practice from GPT-2; A. Radford et al. [6].
We’ll use a slightly prettier form of the original regex, fetched from
github.com/openai/tiktoken/pull/234/files:

>>> PAT = r"""'(?:[sdmt]|ll|ve|re)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""

It may be useful to interactively split some text with this pre-tokenizer to get a better sense of its
behavior:
>>> # requires `regex` package
>>> import regex as re
>>> re.findall(PAT, "some text that i'll pre-tokenize")
['some', ' text', ' that', ' i', "'ll", ' pre', '-', 'tokenize']

When using it in your code, however, you should use re.finditer to avoid storing the pre-tokenized
words as you construct your mapping from pre-tokens to their counts.

Compute BPE merges
Now that we’ve converted our input text into pre-tokens and represented each pre-token as a sequence of
UTF-8 bytes, we can compute the BPE merges (i.e., train the BPE tokenizer). At a high level, the BPE
algorithm iteratively counts every pair of bytes and identifies the pair with the highest frequency (“A”,
“B”). Every occurrence of this most frequent pair (“A”, “B”) is then merged, i.e., replaced with a new
token “AB”. This new merged token is added to our vocabulary; as a result, the final vocabulary after
BPE training is the size of the initial vocabulary (256 in our case), plus the number of BPE merge
operations performed during training. For efficiency during BPE training, we do not consider pairs that
cross pre-token boundaries.2 When computing merges, deterministically break ties in pair frequency by
preferring the lexicographically greater pair. For example, if the pairs (“A”, “B”), (“A”, “C”), (“B”, “ZZ”),
and (“BA”, “A”) all have the highest frequency, we’d merge (“BA”, “A”):
>>> max([("A", "B"), ("A", "C"), ("B", "ZZ"), ("BA", "A")])
('BA', 'A')

Special tokens
Often, some strings (e.g., <|endoftext|>) are used to encode metadata (e.g., boundaries between
documents). When encoding text, it’s often desirable to treat some strings as “special tokens” that should


  2
    Note that the original BPE formulation R. Sennrich et al. [3] specifies the inclusion of an end-of-word token. We do not
add an end-of-word-token when training byte-level BPE models because all bytes (including whitespace and punctuation)
are included in the model’s vocabulary. Since we’re explicitly representing spaces and punctuation, the learned BPE merges
will naturally reflect these word boundaries.

never be split into multiple tokens (i.e., will always be preserved as a single token). For example, the end-
of-sequence string <|endoftext|> should always be preserved as a single token (i.e., a single integer ID),
so we know when to stop generating from the language model. These special tokens must be added to the
vocabulary, so they have a corresponding fixed token ID.
Algorithm 1 of R. Sennrich et al. [3] contains an inefficient implementation of BPE tokenizer training
(essentially following the steps that we outlined above). As a first exercise, it may be useful to implement
and test this function to check your understanding.


 Example (bpe_example): BPE training example


   Here is a stylized example from R. Sennrich et al. [3]. Consider a corpus consisting of the
   following text
   low low low low low
   lower lower widest widest widest
   newest newest newest newest newest newest

   and the vocabulary has a special token <|endoftext|>.

   Vocabulary
   We initialize our vocabulary with our special token <|endoftext|> and the 256 byte values.

   Pre-tokenization
   For simplicity and to focus on the merge procedure, we assume in this example that pre-
   tokenization simply splits on whitespace. When we pre-tokenize and count, we end up with the
   frequency table.
   {low: 5, lower: 2, widest: 3, newest: 6}

   It is convenient to represent this as a dict[tuple[bytes, ...], int], e.g. {(l,o,w): 5, …}. Note
   that even a single byte is a bytes object in Python. There is no byte type in Python to represent
   a single byte, just as there is no char type in Python to represent a single character.

   Merges
   We first look at every successive pair of bytes and sum the frequency of the words where they
   appear {lo: 7, ow: 7, we: 8, er: 2, wi: 3, id: 3, de: 3, es: 9, st: 9, ne: 6, ew: 6}. The pairs ('e', 's')
   and ('s', 't') are tied, so we take the lexicographically greater pair, ('s', 't'). We would then
   merge the pre-tokens so that we end up with {(l,o,w): 5, (l,o,w,e,r): 2, (w,i,d,e,st): 3,
   (n,e,w,e,st): 6}.

   In the second round, we see that (e, st) is the most common pair (with a count of 9) and we
   would merge into {(l,o,w): 5, (l,o,w,e,r): 2, (w,i,d,est): 3, (n,e,w,est): 6}. Continuing this,
   the sequence of merges we get in the end will be ['s t', 'e st', 'o w', 'l ow', 'w est', 'n
   e', 'ne west', 'w i', 'wi d', 'wid est', 'low e', 'lowe r'].

   If we take 6 merges, we have ['s t', 'e st', 'o w', 'l ow', 'w est', 'n e'] and our
   vocabulary elements would be [<|endoftext|>, [...256 BYTE CHARS], st, est, ow, low, west,
   ne].

   With this vocabulary and set of merges, the word newest would tokenize as [ne, west].

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

正在加载本章讨论…

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

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