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

Unicode 与子词分词

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

2 字节对编码(BPE)分词器#

作业的第一部分是训练并实现一个字节级 BPE 分词器 [3, 4]。我们把任意 Unicode 字符串表示为字节序列,在该序列上训练 BPE。后续语言建模时,再用它把文本字符串编码为 token,即整数序列。

2.1 Unicode 标准#

Unicode 是将字符映射到整数码点(code point)的文本编码标准。截至 2025 年 9 月发布的 Unicode 17.0,该标准定义了 172 种文字系统中的 159,801 个字符。

例如,字符 “s” 的码点为 115,通常写作 U+0073:U+ 是约定前缀,0073 是 115 的十六进制表示。“牛”的码点为 29275。Python 的 ord() 可以把单个 Unicode 字符转换成整数,chr() 则将整数码点转换为对应字符的字符串。原文交互示例中,ord('牛') 得到 29275,chr(29275) 得到 “牛”。

练习 unicode11 分

理解 Unicode

(a) chr(0) 返回哪个 Unicode 字符?

交付物: 一句话回答。

(b) 这个字符的字符串表示(repr())与打印出来的表示有什么区别?

交付物: 一句话回答。

(c) 当该字符出现在文本中时,会发生什么?可以在 Python 解释器中分别观察 chr(0)、print(chr(0)),以及把它插入 “this is a test” 与 “string” 之间后,直接查看字符串和打印字符串的结果,检查是否符合预期。

交付物: 一句话回答。

2.2 Unicode 编码#

Unicode 虽然定义了字符到码点的映射,但直接在码点上训练分词器并不实际:词表会非常大,约 15 万项,而且许多字符很罕见,导致分布稀疏。因此,我们使用将 Unicode 字符转换成字节序列的编码。Unicode 标准定义了 UTF-8、UTF-16、UTF-32 三种编码;UTF-8 是互联网的主流编码,原文指出超过 98% 的网页使用它。

Python 字符串的 encode() 方法可以生成 UTF-8 字节串;遍历 bytes 对象或将它传给 list() 可以得到底层字节值;decode() 则把 UTF-8 字节串转回 Unicode 字符串。

原文用 “hello! こんにちは!” 演示:字符串长 13 个字符,UTF-8 编码后有 23 个字节。一个字节不一定对应一个 Unicode 字符。 完整交互过程保留在本页英文原文中。

将码点转换为 UTF-8 字节,本质上是把有 159,801 个有效值的 21 位整数序列,转换为取值范围 0 到 255 的字节序列。256 项的字节词表更容易处理。字节级分词也无需担心词表外 token,因为任何输入文本都可以表示为 0 到 255 的整数序列。

练习 unicode23 分

Unicode 编码

(a) 为什么在 UTF-8 字节上训练分词器,而不是选择 UTF-16 或 UTF-32?可以比较不同编码对多种字符串的输出。

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

(b) 原文给出了一个错误的 decode_utf8_bytes_to_str_wrong 函数:它分别对每个字节进行 UTF-8 解码,再把结果连接起来。为什么该函数不正确?给出一个会产生错误结果的输入字节串。

查看指导书提供的错误函数与调用示例(英文原文)
指导书原文
def decode_utf8_bytes_to_str_wrong(bytestring: bytes):
    return "".join([bytes([b]).decode("utf-8") for b in bytestring])
>>> decode_utf8_bytes_to_str_wrong("hello".encode("utf-8"))
'hello'

交付物: 一个导致该函数产生错误结果的输入字节串,以及一句话的原因说明。

(c) 给出一个无法解码为任何 Unicode 字符的双字节序列。

交付物: 一个例子,以及一句话解释。

2.3 子词分词#

字节级分词缓解了词级分词器的词表外问题,却会让输入序列很长。一个 10 词句子在词级模型中可能只需 10 个 token,在字符级模型中却可能需要 50 个甚至更多,具体取决于词长。更长的序列使每一步计算更昂贵,也让数据中的长程依赖更难建模。

子词分词(subword tokenization) 是词级和字节级分词之间的折中:用更大的词表换取更好的字节序列压缩。例如,原始训练文本中经常出现的字节序列 b'the' 可以作为一个词表项,使原本 3 个 token 缩为 1 个。

怎样选择要加入词表的子词?Sennrich 等人 [3] 提出使用字节对编码(BPE;Gage [5]):反复将出现频率最高的一对字节合并,并分配一个尚未使用的新索引。这样会逐步加入有助于压缩输入序列的子词;如果一个词出现得足够多,它最终可以成为单个子词单元。

通过 BPE 构建词表的分词器通常称为 BPE 分词器。本作业实现字节级 BPE,词表项是字节或合并后的字节序列,同时兼顾词表外处理和可控的输入长度。构建其词表的过程称为“训练”BPE 分词器。

一起把这一章读得更好

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

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

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

2 Byte-Pair Encoding (BPE) Tokenizer
In the first part of the assignment, we will train and implement a byte-level byte-pair encoding (BPE)
tokenizer [R. Sennrich et al., 2016; C. Wang et al., 2019]. In particular, we will represent arbitrary
(Unicode) strings as a sequence of bytes and train our BPE tokenizer on this byte sequence. Later, we
will use this tokenizer to encode text (a string) into tokens (a sequence of integers) for language modeling.

2.1 The Unicode Standard
Unicode is a text encoding standard that maps characters to integer code points. As of Unicode 17.0
(released in September 2025), the standard defines 159,801 characters across 172 scripts. For example, the
character “s” has the code point 115 (typically notated as U+0073, where U+ is a conventional prefix and
0073 is 115 in hexadecimal), and the character “牛” has the code point 29275. In Python, you can use the
ord() function to convert a single Unicode character into its integer representation. The chr() function
converts an integer Unicode code point into a string with the corresponding character.
>>> ord('牛')
29275
>>> chr(29275)
'牛'


 Problem (unicode1): Understanding Unicode (1 point)


    (a) What Unicode character does chr(0) return?
        Deliverable: A one-sentence response.
   (b) How does this character’s string representation (__repr__()) differ from its printed
       representation?
        Deliverable: A one-sentence response.
    (c) What happens when this character occurs in text? It may be helpful to play around with the
        following in your Python interpreter and see if it matches your expectations:
        >>> chr(0)
        >>> print(chr(0))

        >>> "this is a test" + chr(0) + "string"
        >>> print("this is a test" + chr(0) + "string")

        Deliverable: A one-sentence response.


2.2 Unicode Encodings
While the Unicode standard defines a mapping from characters to code points (integers), it’s impractical
to train tokenizers directly on Unicode code points, since the vocabulary would be prohibitively large
(around 150K items) and sparse (since many characters are quite rare). Instead, we’ll use a Unicode
encoding, which converts a Unicode character into a sequence of bytes. The Unicode standard itself
defines three encodings: UTF-8, UTF-16, and UTF-32, with UTF-8 being the dominant encoding for the
Internet (more than 98% of all webpages).
To encode a Unicode string into UTF-8, we can use the encode() function in Python. To access the
underlying byte values for a Python bytes object, we can iterate over it (e.g., call list()). Finally, we can
use the decode() function to decode a UTF-8 byte string into a Unicode string.
>>> test_string = "hello! こんにちは!"
>>> utf8_encoded = test_string.encode("utf-8")
>>> print(utf8_encoded)
b'hello! \xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf!'
>>> print(type(utf8_encoded))
<class 'bytes'>
>>> # Get the byte values for the encoded string (integers from 0 to 255).
>>> list(utf8_encoded)
[104, 101, 108, 108, 111, 33, 32, 227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129,
161, 227, 129, 175, 33]
>>> # One byte does not necessarily correspond to one Unicode character!
>>> print(len(test_string))
13
>>> print(len(utf8_encoded))
23
>>> print(utf8_encoded.decode("utf-8"))
hello! こんにちは!

By converting our Unicode code points into a sequence of bytes (e.g., via the UTF-8 encoding), we are
essentially taking a sequence of code points (21-bit integers with 159,801 valid values) and transforming it
into a sequence of byte values (integers in the range 0 to 255). The 256-length byte vocabulary is much
more manageable to deal with. When using byte-level tokenization, we do not need to worry about out-of-
vocabulary tokens, since we know that any input text can be expressed as a sequence of integers from 0
to 255.


 Problem (unicode2): Unicode Encodings (3 points)


    (a) What are some reasons to prefer training our tokenizer on UTF-8 encoded bytes, rather than
        UTF-16 or UTF-32? It may be helpful to compare the output of these encodings for various
        input strings.
        Deliverable: A one-to-two sentence response.
   (b) Consider the following (incorrect) function, which is intended to decode a UTF-8 byte string
       into a Unicode string. Why is this function incorrect? Provide an example of an input byte
       string that yields incorrect results.

        def decode_utf8_bytes_to_str_wrong(bytestring: bytes):
            return "".join([bytes([b]).decode("utf-8") for b in bytestring])
        >>> decode_utf8_bytes_to_str_wrong("hello".encode("utf-8"))
        'hello'

        Deliverable: An example input byte string for which decode_utf8_bytes_to_str_wrong
        produces incorrect output, with a one-sentence explanation of why the function is incorrect.
    (c) Give a two-byte sequence that does not decode to any Unicode character(s).
        Deliverable: An example, with a one-sentence explanation.


2.3 Subword Tokenization
While byte-level tokenization can alleviate the out-of-vocabulary issues faced by word-level tokenizers,
tokenizing text into bytes results in extremely long input sequences. This slows down model training,
since a sentence with 10 words might only be 10 tokens long in a word-level language model, but could be
50 or more tokens long in a character-level model (depending on the length of the words). Processing
these longer sequences requires more computation at each step of the model. Furthermore, language
modeling on byte sequences is difficult because the longer input sequences create long-term dependencies
in the data.
Subword tokenization is a midpoint between word-level tokenizers and byte-level tokenizers. Note that a
byte-level tokenizer’s vocabulary has 256 entries (byte values are 0 to 255). A subword tokenizer trades off
a larger vocabulary size for better compression of the input byte sequence. For example, if the byte
sequence b'the' often occurs in our raw text training data, assigning it an entry in the vocabulary would
reduce this 3-token sequence to a single token.
How do we select these subword units to add to our vocabulary? R. Sennrich et al. [3] propose to use
byte-pair encoding (BPE; P. Gage [5]), a compression algorithm that iteratively replaces (“merges”) the
most frequent pair of bytes with a single, new unused index. Note that this algorithm adds subword
tokens to our vocabulary to maximize the compression of our input sequences—if a word occurs in our
input text enough times, it’ll be represented as a single subword unit.
Subword tokenizers with vocabularies constructed via BPE are often called BPE tokenizers. In this
assignment, we’ll implement a byte-level BPE tokenizer, where the vocabulary items are bytes or merged
sequences of bytes, which give us the best of both worlds in terms of out-of-vocabulary handling and
manageable input sequence lengths. The process of constructing the BPE tokenizer vocabulary is known
as “training” the BPE tokenizer.

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

正在加载本章讨论…

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

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