CS336.wiki
CS336 中文实验手册/训练与生成
反馈与讨论
ASSIGNMENT 01 / 5.1–5.2

数据加载与检查点

2026 春季 · v26.0.3原文 p. 34–36对照 PDF ↗

5 训练循环#

接下来把已完成的分词数据、模型与优化器组合起来。

5.1 数据加载器#

经过分词的数据是一条 token 序列 x=(x1,…,xn)x=(x_1,\ldots,x_n)。尽管源数据由不同文档、网页或代码文件组成,常见做法是将其拼成单个序列,并在文档间加入 <|endoftext|> 一类分隔符。

数据加载器把它转换为批次流:每个批次有 BB 条长度为 mm 的输入序列,配上同样长度的下一 token 目标。例如 B=1,m=3B=1,m=3 时,一个可能的批次是:

([x2,x3,x4],[x3,x4,x5]) ([x_2,x_3,x_4],[x_3,x_4,x_5])

这种加载方式简化了训练:

  • 任意 1≤i≤n−m1\le i\le n-m 都给出有效训练片段,易于采样。
  • 序列等长,无需填充,可提高硬件利用率,也有助于增大批次。
  • 抽样不必把整个数据集装入内存,容易处理大型语料。
练习 data_loading2 分

实现数据加载

交付物: 编写函数,接收整数 token ID 的 NumPy 数组、batch_size、context_length 和 PyTorch 设备字符串,例如 cpu 或 cuda:0。

返回输入序列与下一 token 目标两个张量。二者形状都是 (batch_size, context_length),包含 token ID,并放在指定设备上。

实现 adapters.run_get_batch,运行 uv run pytest -k test_get_batch。

低资源提示

CPU 或 Apple Silicon 上的数据加载

数据和模型必须放在正确且相同的设备上:CPU 使用 cpu;Apple Silicon 的 M 系列芯片使用 mps。

可参阅 PyTorch MPS 文档、MPS 说明、Apple Metal Performance Shaders。

数据集无法装入内存时#

Unix 的 mmap 把磁盘文件映射到虚拟内存,仅在访问相应地址时惰性加载内容,让程序可以“假装”整个数据集都在内存中。

NumPy 对应的接口是 np.memmap;如果文件原先通过 np.save 保存,也可以给 np.load 设置 mmap_mode='r'。返回的数组式对象会在访问元素时按需加载。

训练采样时务必采用内存映射模式,并指定与保存文件一致的 dtype。建议明确检查映射结果是否正确,例如是否存在超出词表大小的值。

5.2 检查点#

除加载数据,还需要保存训练中的模型。作业超时、机器故障等可能导致中断,需要恢复;即使一切正常,也可能希望分析训练动态,或比较不同训练阶段的生成结果。

检查点应包含恢复训练所需的全部状态:

  1. 模型权重。
  2. AdamW 等有状态优化器的状态,例如矩估计。
  3. 中断时的迭代次数,用于恢复学习率调度。

每个 nn.Module 和 torch.optim.Optimizer 都提供 state_dict(),以及对应的 load_state_dict()。torch.save 可以把含有张量与整数等对象的字典保存到路径或类文件对象;torch.load 可以再读回来。

练习 checkpointing1 分

实现模型检查点

实现保存与加载检查点的两个函数。

接口 参数 行为
save_checkpoint model、optimizer、iteration、out 保存模型、优化器、迭代次数的状态。可用各自的 state_dict 与 torch.save。格式可以自由选择,只要之后能恢复。
load_checkpoint src、model、optimizer 从路径或类文件对象读取,恢复模型与优化器,并返回保存的迭代次数。可用 torch.load 和 load_state_dict。

其中模型类型为 torch.nn.Module,优化器为 torch.optim.Optimizer,迭代次数为 int。out 与 src 支持 str、os.PathLike、typing.BinaryIO 或 typing.IO[bytes]。

实现 adapters.run_save_checkpoint 与 adapters.run_load_checkpoint,通过 uv run pytest -k test_checkpointing。

一起把这一章读得更好

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

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

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

5 Training loop
We will now finally put together the major components we’ve built so far: the tokenized data, the model,
and the optimizer.

5.1 Data Loader
The tokenized data (e.g., that you prepared in tokenizer_experiments) is a single sequence of tokens 𝑥 =
(𝑥1 , …, 𝑥𝑛 ). Even though the source data might consist of separate documents (e.g., different web pages,
or source code files), a common practice is to concatenate all of those into a single sequence of tokens,
adding a delimiter between them (such as the <|endoftext|> token).
A data loader turns this into a stream of batches, where each batch consists of 𝐵 sequences of length 𝑚,
paired with the corresponding next tokens, also with length 𝑚. For example, for 𝐵 = 1, 𝑚 = 3,
([𝑥2 , 𝑥3 , 𝑥4 ], [𝑥3 , 𝑥4 , 𝑥5 ]) would be one potential batch.
Loading data in this way simplifies training for a number of reasons. First, any 1 ≤ 𝑖 ≤ 𝑛 − 𝑚 gives a
valid training sequence, so sampling training sequences is trivial. Since all training sequences have the
same length, there’s no need to pad input sequences, which improves hardware utilization (also by
increasing batch size 𝐵). Finally, we also don’t need to load the full dataset to sample training data,
making it easy to handle large datasets that might not otherwise fit in memory.


 Problem (data_loading): Implement data loading (2 points)


   Deliverable: Write a function that takes a numpy array 𝑥 (integer array with token IDs), a
   batch_size, a context_length and a PyTorch device string (e.g., 'cpu' or 'cuda:0'), and returns
   a pair of tensors: the sampled input sequences and the corresponding next-token targets. Both

   tensors should have shape (batch_size, context_length) containing token IDs, and both should
   be placed on the requested device. To test your implementation against our provided tests, you
   will first need to implement the test adapter at [adapters.run_get_batch] . Then, run uv run
   pytest -k test_get_batch to test your implementation.


     Low-Resource Tip: Data loading on CPU or Apple Silicon


       If you are planning to train your LM on CPU or Apple Silicon, you need to move your
       data to the correct device (and similarly, you should use the same device for your model
       later on).
       If you are on CPU, you can use the 'cpu' device string, and on Apple Silicon (M* chips),
       you can use the 'mps' device string.
       For more on MPS, check out these resources:
       • https://docs.pytorch.org/docs/stable/mps.html
       • https://docs.pytorch.org/docs/stable/notes/mps.html
       • https://developer.apple.com/documentation/metalperformanceshaders



What if the dataset is too big to load into memory? We can use a Unix system call named mmap which
maps a file on disk to virtual memory, and lazily loads the file contents when that memory location is
accessed. Thus, you can “pretend” you have the entire dataset in memory. Numpy implements this
through np.memmap (or the flag mmap_mode='r' to np.load, if you originally saved the array with np.save),
which will return a numpy array-like object that loads the entries on-demand as you access them. When
sampling from your dataset (i.e., a numpy array) during training, be sure to load the
dataset in memory-mapped mode (via np.memmap or the flag mmap_mode='r' to np.load, depending on
how you saved the array). Make sure you also specify a dtype that matches the array that you’re loading.
It may be helpful to explicitly verify that the memory-mapped data looks correct (e.g., doesn’t contain
values beyond the expected vocabulary size).

5.2 Checkpointing
In addition to loading data, we will also need to save models as we train. When running jobs, we often
want to be able to resume a training run that stopped midway through (e.g., due to your job timing out,
machine failure, etc). Even when all goes well, we might also want to later have access to intermediate
models (e.g., to study training dynamics post-hoc, take samples from models at different stages of
training, etc).
A checkpoint should have all the states that we need to resume training. We of course want to be able to
restore model weights at a minimum. If using a stateful optimizer (such as AdamW), we will also need to
save the optimizer’s state (e.g., in the case of AdamW, the moment estimates). Finally, to resume the
learning rate schedule, we will need to know the iteration number we stopped at. PyTorch makes it easy
to save all of these: every nn.Module has a state_dict() method that returns a dictionary with all
learnable weights; we can restore these weights later with the sister method load_state_dict(). The same
goes for any torch.optim.Optimizer. Finally, torch.save(obj, dest) can dump an object (e.g., a
dictionary containing tensors as some values, but also regular Python objects like integers) to a file (path)
or file-like object, which can then be loaded back into memory with torch.load(src).

 Problem (checkpointing): Implement model checkpointing (1 point)


    Implement the following two functions to load and save checkpoints:
    def save_checkpoint(model, optimizer, iteration, out) should dump all the state from the
       model, optimizer and iteration into the file-like object out. You can use the state_dict
       method of both the model and the optimizer to get their relevant states and use
       torch.save(obj, out) to dump obj into out (PyTorch supports either a path or a file-like
       object here). A typical choice is to have obj be a dictionary, but you can use whatever format
       you want as long as you can load your checkpoint later.
    This function expects the following parameters:
     model: torch.nn.Module

     optimizer: torch.optim.Optimizer

     iteration: int

     out: str | os.PathLike | typing.BinaryIO | typing.IO[bytes]

    def load_checkpoint(src, model, optimizer) should load a checkpoint from src (path or file-like
       object), and then recover the model and optimizer states from that checkpoint. Your function
       should return the iteration number that was saved to the checkpoint. You can use
       torch.load(src) to recover what you saved in your save_checkpoint implementation, and the
       load_state_dict method in both the model and optimizer to return them to their previous
       states.
    This function expects the following parameters:
     src: str | os.PathLike | typing.BinaryIO | typing.IO[bytes]

     model: torch.nn.Module

     optimizer: torch.optim.Optimizer

    Implement the [adapters.run_save_checkpoint] and [adapters.run_load_checkpoint] adapters,
    and make sure they pass uv run pytest -k test_checkpointing.

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

正在加载本章讨论…

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

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