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

编码、解码与分词实验

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

2.6 BPE 分词器:编码与解码#

上一部分训练得到了词表与 BPE 合并列表。现在实现一个分词器,加载这些结果,在文本与整数 token ID 之间进行编码和解码。

2.6.1 文本编码#

编码过程与词表训练相呼应,主要有两个步骤:

  1. 预分词。 和训练时一样,把输入切分为预词项,再表示为 UTF-8 字节序列。各预词项独立处理,不允许跨边界合并。
  2. 应用合并。 按训练时的创建顺序,把学到的合并应用到各预词项上。
原文示例 bpe_encoding

BPE 编码示例

设输入为 “the cat ate”,词表为:

{0: b' ', 1: b'a', 2: b'c', 3: b'e', 4: b'h', 5: b't',
 6: b'th', 7: b' c', 8: b' a', 9: b'the', 10: b' at'}

学到的合并为:

[(b't', b'h'), (b' ', b'c'), (b' ', b'a'),
 (b'th', b'e'), (b' a', b't')]

预分词结果是 “the”、“ cat”、“ ate”。

第一个预词项最初是 [b't', b'h', b'e']。第一个适用的合并 (b't', b'h') 将其变为 [b'th', b'e'];随后适用的 (b'th', b'e') 将其变为 [b'the']。整个预词项已合并为一个 token,不再有可用合并,对应整数序列 [9]。

同样,“ cat” 合并为 [b' c', b'a', b't'],对应 [7, 1, 5];“ ate” 合并为 [b' at', b'e'],对应 [10, 3]。

最终编码结果是 [9, 7, 1, 5, 10, 3]。

特殊 token#

编码时,分词器必须正确处理构造函数接收的用户自定义特殊 token。

内存方面的考虑#

如果要处理无法全部装入内存的大型文本文件或其他数据流,需要将其切成可管理的块,逐块处理,使内存复杂度保持常数,而不是随文本大小线性增长。

与此同时,必须确保 token 不会跨越分块边界,否则结果会与一次性在内存中处理完整序列的朴素方法不同。

2.6.2 文本解码#

把整数 token ID 序列转回文本时,逐个查词表得到字节序列,拼接后再解码为 Unicode 字符串。

输入 ID 不保证能够拼成有效 Unicode,因为用户可能传入任意 ID 序列。如果出现无效字节,应该替换为 Unicode 官方替换字符 U+FFFD。bytes.decode 的 errors 参数控制错误处理;errors='replace' 会自动加入替换标记。原文附有替换字符说明。

练习 tokenizer15 分

实现分词器

交付物: 实现一个 Tokenizer 类,根据词表和合并列表将文本编码为整数 ID,并将 ID 解码为文本。支持用户提供的特殊 token;如果尚不在词表中,应追加到词表。

建议接口如下。这里列的是原指导书的接口要求,不包含实现。

方法 参数与返回 要求
init vocab: dict[int, bytes]、merges: list[tuple[bytes, bytes]]、special_tokens: list[str] | None = None 从词表、合并列表和可选特殊 token 构造分词器。
from_files vocab_filepath: str、merges_filepath: str,以及可选特殊 token 类方法,从训练程序保存的同格式词表、合并文件构造并返回分词器。
encode text: str → list[int] 将输入文本编码成 token ID 序列。
encode_iterable iterable: Iterable[str] → Iterator[int] 接收字符串可迭代对象,例如文件句柄;返回惰性产出 token ID 的生成器,用于低内存处理大型文件。
decode ids: list[int] → str 将 token ID 序列解码为文本。

实现 adapters.get_tokenizer 后,运行 uv run pytest tests/test_tokenizer.py,应通过全部测试。

2.7 实验#

练习 tokenizer_experiments4 分

分词器实验

(a) 从 TinyStories 和 OpenWebText 各抽取 10 篇文档,用各自训练好的分词器(词表大小分别为 10K、32K)编码为整数 ID。每个分词器的压缩率(bytes/token)是多少?

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

(b) 如果用 TinyStories 分词器处理 OpenWebText 样本,会发生什么?比较压缩率,和/或从定性角度描述现象。

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

(c) 估算分词器的吞吐量,例如每秒处理多少字节。处理有 825 GB 文本的 Pile 数据集需要多久?

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

(d) 用 TinyStories、OpenWebText 分词器分别编码各自的训练集和开发集,得到供后续训练使用的整数 token ID 序列。建议保存为 uint16 类型的 NumPy 数组。为什么 uint16 合适?

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

一起把这一章读得更好

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

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

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

2.6 BPE Tokenizer: Encoding and Decoding
In the previous part of the assignment, we implemented a function to train a BPE tokenizer on input text
to obtain a tokenizer vocabulary and a list of BPE merges. Now, we will implement a BPE tokenizer that
loads a provided vocabulary and list of merges and uses them to encode and decode text to/from token
IDs.

2.6.1 Encoding text
The process of encoding text by BPE mirrors how we train the BPE vocabulary. There are a few major
steps.
Step 1: Pre-tokenize. We first pre-tokenize the sequence and represent each pre-token as a sequence of
UTF-8 bytes, just as we did in BPE training. We will be merging these bytes within each pre-token into
vocabulary elements, handling each pre-token independently (no merges across pre-token boundaries).
Step 2: Apply the merges. We then take the sequence of vocabulary element merges created during
BPE training, and apply it to our pre-tokens in the same order of creation.


 Example (bpe_encoding): BPE encoding example


   For example, suppose our input string is 'the cat ate', our vocabulary is {0: b' ', 1: b'a', 2:
   b'c', 3: b'e', 4: b'h', 5: b't', 6: b'th', 7: b' c', 8: b' a', 9: b'the', 10: b' at'}, and
   our learned merges are [(b't', b'h'), (b' ', b'c'), (b' ', b'a'), (b'th', b'e'), (b' a',

    b't')]. First, our pre-tokenizer would split this string into ['the', ' cat', ' ate']. Then, we’ll
    look at each pre-token and apply the BPE merges.
    The first pre-token 'the' is initially represented as [b't', b'h', b'e']. Looking at our list of
    merges, we identify the first applicable merge to be (b't', b'h'), and use that to transform the
    pre-token into [b'th', b'e']. Then, we go back to the list of merges and identify the next
    applicable merge to be (b'th', b'e'), which transforms the pre-token into [b'the']. Finally,
    looking back at the list of merges, we see that there are no more that apply to the string (since
    the entire pre-token has been merged into a single token), so we are done applying the BPE
    merges. The corresponding integer sequence is [9].
    Repeating this process for the remaining pre-tokens, we see that the pre-token ' cat' is
    represented as [b' c', b'a', b't'] after applying the BPE merges, which becomes the integer
    sequence [7, 1, 5]. The final pre-token ' ate' is [b' at', b'e'] after applying the BPE merges,
    which becomes the integer sequence [10, 3]. Thus, the final result of encoding our input string is
    [9, 7, 1, 5, 10, 3].



Special tokens
Your tokenizer should be able to properly handle user-defined special tokens when encoding text
(provided when constructing the tokenizer).

Memory considerations
Suppose we want to tokenize a large text file that we cannot fit in memory. To efficiently tokenize this
large file (or any other stream of data), we need to break it up into manageable chunks and process each
chunk in turn, so that the memory complexity is constant as opposed to linear in the size of the text. In
doing so, we need to make sure that a token doesn’t cross chunk boundaries, else we’ll get a different
tokenization than the naïve method of tokenizing the entire sequence in-memory.

2.6.2 Decoding text
To decode a sequence of integer token IDs back to raw text, we can simply look up each ID’s
corresponding entries in the vocabulary (a byte sequence), concatenate them together, and then decode
the bytes to a Unicode string. Note that input IDs are not guaranteed to map to valid Unicode strings
(since a user could input any sequence of integer IDs). In the case that the input token IDs do not
produce a valid Unicode string, you should replace the malformed bytes with the official Unicode
replacement character U+FFFD.3 The errors argument of bytes.decode controls how Unicode decoding
errors are handled, and using errors='replace' will automatically replace malformed data with the
replacement marker.


 Problem (tokenizer): Implementing the tokenizer (15 points)


    Deliverable: Implement a Tokenizer class that, given a vocabulary and a list of merges, encodes
    text into integer IDs and decodes integer IDs into text. Your tokenizer should also support user-
    provided special tokens (appending them to the vocabulary if they aren’t already there). We
    recommend the following interface:




  3
    See en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character for more information about the Unicode
replacement character.

  def __init__(self, vocab, merges, special_tokens=None) Construct a tokenizer from a given
      vocabulary, list of merges, and (optionally) a list of special tokens. This function should accept
      the following parameters:
   vocab: dict[int, bytes]

   merges: list[tuple[bytes, bytes]]

   special_tokens: list[str] | None = None

  def from_files(cls, vocab_filepath, merges_filepath, special_tokens=None) Class method
      that constructs and returns a Tokenizer from a serialized vocabulary and list of merges (in the
      same format that your BPE training code output) and (optionally) a list of special tokens.
      This method should accept the following additional parameters:
   vocab_filepath: str

   merges_filepath: str

   special_tokens: list[str] | None = None

  def encode(self, text: str) -> list[int] Encode an input text into a sequence of token IDs.

  def encode_iterable(self, iterable: Iterable[str]) -> Iterator[int] Given an iterable of
      strings (e.g., a Python file handle), return a generator that lazily yields token IDs. This is
      required for memory-efficient tokenization of large files that we cannot directly load into
      memory.
  def decode(self, ids: list[int]) -> str Decode a sequence of token IDs into text.

  To test your Tokenizer against our provided tests, you will first need to implement the test
  adapter at [adapters.get_tokenizer] . Then, run uv run pytest tests/test_tokenizer.py. Your
  implementation should be able to pass all tests.


2.7 Experiments

 Problem (tokenizer_experiments): Experiments with tokenizers (4 points)


   (a) Sample 10 documents from TinyStories and OpenWebText. Using your previously-trained
       TinyStories and OpenWebText tokenizers (10K and 32K vocabulary size, respectively),
       encode these sampled documents into integer IDs. What is each tokenizer’s compression ratio
       (bytes/token)?
      Deliverable: A one-to-two sentence response.
  (b) What happens if you tokenize your OpenWebText sample with the TinyStories tokenizer?
      Compare the compression ratio and/or qualitatively describe what happens.
      Deliverable: A one-to-two sentence response.
   (c) Estimate the throughput of your tokenizer (e.g., in bytes/second). How long would it take to
       tokenize the Pile dataset (825GB of text)?
      Deliverable: A one-to-two sentence response.
  (d) Using your TinyStories and OpenWebText tokenizers, encode the respective training and
      development datasets into a sequence of integer token IDs. We’ll use this later to train our

        language model. We recommend serializing the token IDs as a NumPy array of datatype
        uint16. Why is uint16 an appropriate choice?

        Deliverable: A one-to-two sentence response.

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

正在加载本章讨论…

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

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