CS336.wiki
CS336 中文实验手册/开始之前
反馈与讨论
ASSIGNMENT 01 / 1

作业概览

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

1 作业概览#

在这份作业中,你将从零构建训练一个标准 Transformer 语言模型(language model,LM)所需的全部组件,并训练一些模型。

需要实现的内容#

  1. 字节对编码(byte-pair encoding,BPE)分词器,见第 2 节。
  2. Transformer 语言模型,见第 3 节。
  3. 交叉熵损失函数和 AdamW 优化器,见第 4 节。
  4. 支持保存、加载模型与优化器状态的训练循环,见第 5 节。

需要运行的内容#

  1. 在 TinyStories 数据集上训练 BPE 分词器。
  2. 用训练好的分词器将数据集编码成整数 ID 序列。
  3. 在 TinyStories 上训练 Transformer 语言模型。
  4. 用训练好的模型生成样本,并评估困惑度(perplexity)。
  5. 在 OpenWebText 上训练模型,将得到的困惑度提交到排行榜。

允许使用什么#

本作业要求从零构建每个组件。除下列项目外,不得使用 torch.nn、torch.nn.functional 或 torch.optim 中的任何定义:

  • torch.nn.Parameter。
  • torch.nn 中的容器类,例如 Module、ModuleList、Sequential 等。完整容器列表见 PyTorch 文档。
  • torch.optim.Optimizer 基类。

你可以使用 PyTorch 中的其他定义。如果不确定某个函数或类是否允许使用,请在课程 Slack 上提问。拿不准时,请考虑它是否违背作业“从零实现”的精神。

关于 AI 工具的声明#

AI 已能完全自主地解决作业的许多部分,这会妨碍你深入接触和学习课程内容。

允许使用 AI 回答高层次的概念问题,或提供函数签名、库 API 等底层编程文档。不允许用 AI 实现任何作业的任何部分,包括编码代理(例如 Cursor Agents、Codex、Claude Code)和 AI 自动补全(例如 Cursor Tab、GitHub Copilot)。使用 AI 代理时,务必让它遵循仓库提供的 AGENTS.md;使用聊天机器人时,也应把该提示词放入对话。

强烈建议做作业时关闭 IDE 中的 AI 自动补全;非 AI 的函数名补全等功能完全可以使用。往届同学反馈,关闭 AI 自动补全后更容易深入学习材料。完整规定见课程 AI 政策。

代码结构#

作业代码及本指导书位于 stanford-cs336/assignment1-basics。请克隆该仓库。若有更新,课程会通知你拉取最新版本。

路径 用途
cs336_basics/* 编写实现的地方。这里几乎没有代码,你可以自由组织自己的从零实现。
adapters.py 课程要求实现的功能接口。每个适配器(如 run_scaled_dot_product_attention)只应调用你的实现,不应包含实质逻辑。
test_*.py 必须通过的测试,通过适配器调用你的代码。不要修改测试文件。

如何提交#

运行仓库提供的 make_submission.sh 生成提交压缩包。如果有不希望打包的大型数据文件或检查点,请把它们加入脚本中的排除列表。

向 Gradescope 提交:

  • writeup.pdf:全部书面问题的回答,请使用排版工具制作。
  • code.zip:你编写的全部代码。

排行榜通过向 assignment1-basics-leaderboard 提交 PR 参加,具体说明见该仓库的 README。

数据集从哪里获取#

本作业使用经过预处理的 TinyStories [1] 和 OpenWebText [2],二者均为单个大型纯文本文件。

如果你是正式选课学生,下载说明见课程的计算资源指南。如果你在家自学,请使用作业仓库 README 中提供的下载命令。

低资源提示

贯穿课程的建议

指导书会用提示框介绍 GPU 较少或没有 GPU 时的做法,例如缩小数据集、缩小模型,或在 Mac 集成 GPU、CPU 上运行训练。即使有课程服务器可用,这些建议也有助于加快迭代、节约时间,建议阅读。

低资源提示

在 Apple Silicon 或 CPU 上完成作业 1

课程工作人员的参考实现能在配备 36 GB 内存的 Apple M4 Max 上训练出较流畅的语言模型:Metal GPU(MPS)不到 5 分钟,CPU 约 30 分钟。暂时不理解这些术语也没关系:只要笔记本较新,实现正确且高效,就可以训练一个能较流畅地生成简单儿童故事的小模型。后文会说明 CPU、MPS 对应的配置调整。

这些时间是原指导书报告的特定运行结果,不是对所有硬件和训练配置的保证。

一起把这一章读得更好

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

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

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

1 Assignment Overview
In this assignment, you will build all the components needed to train a standard Transformer language
model (LM) from scratch and train some models.

What you will implement
1. Byte-pair encoding (BPE) tokenizer (Section 2)
2. Transformer language model (LM) (Section 3)
3. The cross-entropy loss function and the AdamW optimizer (Section 4)
4. The training loop, with support for serializing and loading model and optimizer state (Section 5)

What you will run
1. BPE tokenizer training on the TinyStories dataset.
2. Trained tokenizer encoding on the dataset to convert it into a sequence of integer IDs.
3. Transformer LM training on the TinyStories dataset.
4. Sample generation and evaluation of perplexity using the trained Transformer LM.
5. Model training on OpenWebText, and submit your attained perplexities to a leaderboard.

What you can use
We expect you to build each component from scratch. In particular, you may not use any definitions from
torch.nn, torch.nn.functional, or torch.optim except for the following:

• torch.nn.Parameter
• Container classes in torch.nn (e.g., Module, ModuleList, Sequential, etc.).1
• The torch.optim.Optimizer base class
You may use any other PyTorch definitions. If you would like to use a function or class and are not sure
whether it is permitted, feel free to ask on Slack. When in doubt, consider if using it compromises the
“from-scratch” ethos of the assignment.

Statement on AI tools
AI can solve many parts of the assignments fully autonomously. This makes it harder to deeply engage
with, and learn from, the course material.
The use of AI tools is permitted for answering high-level conceptual questions, or for providing low-level
programming documentation like function signatures and library APIs. However, AI tools are not
permitted for implementing any part of any assignment. This includes both coding agents (e.g., Cursor
Agents, Codex, Claude Code) and AI autocomplete (e.g., Cursor Tab, GitHub Copilot). When using an
AI agent, make sure it uses the AGENTS.md file provided. The prompt should also be included when
using chatbots.

 1
     See pytorch.org/docs/stable/nn.html#containers for a full list.

We strongly encourage you to disable AI autocomplete (e.g., Cursor Tab, GitHub Copilot) in your IDE
when completing assignments (though non-AI autocomplete, e.g., autocompleting function names is
totally fine). Previous students have highlighted that disabling AI autocomplete made it easier to engage
deeply with the material.
For the full AI Policy, see this document.

What the code looks like
The assignment code, as well as this writeup, are available on GitHub at:
                              github.com/stanford-cs336/assignment1-basics

Please git clone the repository. If there are any updates, we will notify you so you can git pull to get
the latest.
1. cs336_basics/*: This is where you write your code. Note that there’s no code in here—you can do
   whatever you want from scratch!
2. adapters.py: There is a set of functionality that your code must have. For each piece of functionality
   (e.g., scaled dot product attention), fill out its implementation (e.g.,
   run_scaled_dot_product_attention) by simply invoking your code. Note: your changes to adapters.py
   should not contain any substantive logic; this is glue code.
3. test_*.py: This contains all the tests that you must pass (e.g., test_scaled_dot_product_attention),
   which will invoke the hooks defined in adapters.py. Don’t edit the test files.

How to submit
In order to submit, run make_submission.sh to construct a submission zip file. Make sure to add any
additional files to the list of exclusions in the script if you have large data files or checkpoints you don’t
want to include in your submission zip.
You will submit the following files to Gradescope:
• writeup.pdf: Answer all the written questions. Please typeset your responses.
• code.zip: Contains all the code you’ve written.
To submit to the leaderboard, submit a PR to:
                       github.com/stanford-cs336/assignment1-basics-leaderboard

See the README.md in the leaderboard repository for detailed submission instructions.

Where to get datasets
This assignment will use two pre-processed datasets: TinyStories [R. Eldan et al., 2023] and
OpenWebText [A. Gokaslan et al., 2019]. Both datasets are single, large plaintext files.
If you are doing the assignment with the class, you can find instructions for downloading the dataset in
the compute guide.
If you are following along at home, you can download these files with the commands inside the README.md.


 Low-Resource Tip: Init


    Throughout the course’s assignment handouts, we will give advice for working through parts of
    the assignment with fewer or no GPU resources. For example, we will sometimes suggest
    downscaling your dataset or model size, or explain how to run training code on a Mac

   integrated GPU or CPU. You’ll find these “low-resource tips” in a blue box (like this one). Even if
   you are an enrolled Stanford student with access to the course machines, these tips may help you
   iterate faster and save time, so we recommend reading them!



 Low-Resource Tip: Assignment 1 on Apple Silicon or CPU


   With the staff solution code, we can train an LM to generate reasonably fluent text on an Apple
   M4 Max chip with 36 GB RAM, in under 5 minutes on Metal GPU (MPS) and about 30 minutes
   using the CPU. If these words don’t mean much to you, don’t worry! Just know that if you have a
   reasonably up-to-date laptop and your implementation is correct and efficient, you will be able to
   train a small LM that generates simple children’s stories with decent fluency.
   Later in the assignment, we will explain what changes to make if you are on CPU or MPS.

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

正在加载本章讨论…

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

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