CS336.wiki
CS336 中文实验手册/实验与消融
反馈与讨论
ASSIGNMENT 01 / 7.2

TinyStories 训练与调优

2026 春季 · v26.0.3原文 p. 39–42对照 PDF ↗

7.2 TinyStories#

首先使用很简单的 TinyStories 数据 [1],模型训练较快,也能观察有趣现象。获取方式见第 1 节。

原文示例 tinystories_example

TinyStories 数据样例

从前,有个叫 Ben 的小男孩,喜欢探索周围的世界。他见过很多奇妙的东西,比如商店里陈列的漂亮花瓶。一天,他在店里发现了一个很特别的花瓶,惊叹道:“哇,这个花瓶真漂亮!我可以买它吗?”店主微笑着说:“当然!你可以带回家,让朋友们看看它有多棒!”Ben 骄傲地把花瓶带回家,叫来朋友们展示。大家都觉得它很漂亮,不敢相信 Ben 这么幸运。这就是 Ben 在商店里找到一个漂亮花瓶的故事!

以上为语料示例的中文翻译;实际数据仍是英文。英文原文保留在本页末尾。

7.2.1 超参数调优#

下面给出一些起点;其他配置需要你寻找有效取值。

超参数 起始值与说明
词表大小 10,000。常见词表为几万至几十万,可以尝试变化并观察词表与模型行为。
上下文长度 256。TinyStories 可能不需要长序列,后面的 OpenWebText 可以尝试不同长度,观察每步时间与最终困惑度。
d_model 512,小于许多小型 Transformer 论文使用的 768,有助于提速。
d_ff 1344,约为 83dmodel\frac83d_{\mathrm{model}},且为 64 的倍数。
RoPE 的 Θ\Theta 10,000。
层数、头数 4 层、16 头。非嵌入参数约 12.5M;若绑定 token embedding 与 LM head,总参数约 17.6M,不绑定时约 22.7M,属于很小的 Transformer。
总处理 token 数 327,680,000;批次大小 × 总步数 × 上下文长度应大致等于它。

还需要试验:学习率、学习率预热、AdamW 的 β1,β2,ε\beta_1,\beta_2,\varepsilon、权重衰减。典型配置可参考 Kingma 等人 [22]。

7.2.2 组合起来#

准备好已训练的 BPE,编码训练数据,再用自己的训练循环运行。

原文性能参考: 正确且高效的实现,采用上述配置,在一张 B200 上约需 20–30 分钟。如果明显更慢,检查数据加载、检查点、验证损失是否成为瓶颈,以及运算是否正确批处理。

7.2.3 调试模型架构的技巧#

建议熟悉 IDE 内置调试器,如 VSCode、Zed 的调试器,比大量打印更省时间。使用文本编辑器时可以考虑 ipdb。

  • 开发神经网络常先在单个小批次上过拟合;实现正确时,应该能较快把训练损失降到接近零。
  • 在不同组件中设置断点,检查中间张量形状是否符合预期。
  • 监测激活、权重、梯度范数,确认没有爆炸或消失。
练习 learning_rate3 分 · 2 B200 小时

调整学习率

学习率是最重要的超参数之一。以已训练的基础模型为起点,完成:

(a) 对学习率做超参数扫描,报告最终损失;若发散则注明。

交付物: 多个学习率对应的学习曲线,并解释搜索策略。

交付物: TinyStories 每 token 验证损失不高于 1.45 的模型。

(b) 常见经验认为最佳学习率位于“稳定性的边缘”。研究开始发散的学习率与最佳学习率之间的关系。

交付物: 随学习率增大的学习曲线,至少包含一次发散运行,并分析它与收敛速度的关系。

低资源提示

在 CPU 或 Apple Silicon 上训练

如果在 cpu 或 mps 上运行,可将总处理 token 数降到约 40,000,000,验证损失目标从 1.45 放宽到 2.00。这已足以生成相对流畅的文本。

课程参考实现在 M4 Max、36 GB 内存上采用:

32×5000×256=40,960,000 tokens 32\times5000\times256=40,960,000\ \text{tokens}

CPU 耗时 1 小时 22 分钟,MPS 耗时 36 分钟;第 5000 步验证损失为 1.80。

原文补充建议:

  • 若总共训练 NN 步,把余弦学习率的退火终点设在第 NN 步,使其恰好达到最小学习率。
  • 在 MPS 上不要像 CUDA 那样启用 TF32,即不要设置 torch.set_float32_matmul_precision('high')。课程在 PyTorch 2.9.0 上观察到 MPS 后端可能静默使用错误内核,造成训练不稳。
  • 可用 torch.compile 加速。在 CPU 上使用默认编译;MPS 可使用 backend="aot_eager" 适度优化反向传播。原文指出,截至 PyTorch 2.9.0,MPS 不支持 Inductor 编译。

这些是 v26.0.3 指导书记录的版本特定现象,阅读时应结合自己的运行环境。

批次大小#

较大批次可通过更大的矩阵乘法提高 GPU 效率,但是否总是越大越好?接下来用实验观察。

练习 batch_size_experiment1 分 · 1 B200 小时

改变批次大小

将批次大小从 1 一直变化到 GPU 显存上限。至少尝试若干中间值,包括 64、128 等典型值。

交付物: 不同批次大小的学习曲线,必要时重新优化学习率。

交付物: 用几句话讨论批次大小对训练的影响。

生成文本#

现在使用解码器检查模型生成质量。至少应达到下列原文样例的水平。

原文示例 ts_generate_example

TinyStories 语言模型的生成示例

从前,有个漂亮女孩叫 Lily。她喜欢吃口香糖,尤其是那块大的黑色口香糖。一天,妈妈请她帮忙做晚饭。Lily 很兴奋,因为她喜欢帮妈妈。妈妈煮了一大锅汤,Lily 开心地说:“谢谢妈妈!我爱你。”她帮妈妈把汤倒进大碗里。晚饭后,妈妈又做了一些美味的汤。Lily 很喜欢,说:“谢谢妈妈!这汤真好喝!”妈妈笑着说:“你喜欢就好,Lily。”她们做完饭,又继续一起做饭。故事结束。

译文保留了原示例的重复和情节不连贯之处;模型实际生成的是英文。

低资源提示

CPU 或 Apple Silicon 上的生成结果

使用只处理约 40M token 的低资源配置时,生成内容仍像英语,但通常不如上面的示例流畅。原文例子的大意如下,保留了不连贯表达:

“从前,有个叫 Sue 的小女孩。Sue 有一颗非常喜欢的牙齿。那是他最好的头。一天 Sue 出门散步,遇见一只瓢虫!她们成了好朋友,一起在小路上玩。

‘嘿,Polly!我们出去吧!’Tim 说。Sue 看着天空,发现很难找到一种跳舞闪耀的方法。她笑了,同意帮助说话!

Sue 看着天空移动,那个是什么。她”

对应英文样例保留在本页原文中。

练习 generate1 分

生成文本

用解码器和训练好的检查点报告模型生成文本。可能需要调节温度、top-p 等参数以获得流畅输出。

交付物: 至少 256 个 token 的文本,或在首次出现 <|endoftext|> 时结束;简要评论流畅度,并指出至少两个影响生成质量的因素。

一起把这一章读得更好

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

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

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

7.2 TinyStories
We are going to start with a very simple dataset (TinyStories; R. Eldan et al. [1]) where models will train
quickly, and we can see some interesting behaviors. The instructions for getting this dataset are in
Section 1. An example of what this dataset looks like is below.


 Example (tinystories_example): One example from TinyStories


    Once upon a time there was a little boy named Ben. Ben loved to explore the world around him.
    He saw many amazing things, like beautiful vases that were on display in a store. One day, Ben
    was walking through the store when he came across a very special vase. When Ben saw it he was
    amazed! He said, “Wow, that is a really amazing vase! Can I buy it?” The shopkeeper smiled and
    said, “Of course you can. You can take it home and show all your friends how amazing it is!” So
    Ben took the vase home and he was so proud of it! He called his friends over and showed them
    the amazing vase. All his friends thought the vase was beautiful and couldn’t believe how lucky
    Ben was. And that’s how Ben found an amazing vase in the store!


7.2.1 Hyperparameter tuning
We will tell you some very basic hyperparameters to start with and ask you to find some settings for
others that work well.
Vocab size 10000. Typical vocabulary sizes are in the tens to hundreds of thousands. You should vary
this and see how the vocabulary and model behavior change.
Context length 256. Simple datasets such as TinyStories might not need long sequence lengths, but for
the later OpenWebText data, you may want to vary this. Try varying this and seeing the impact on both
the per-iteration runtime and the final perplexity.
d_model 512. This is slightly smaller than the 768 dimensions used in many small Transformer papers, but
this will make things faster.
d_ff 1344. This is roughly 83 𝑑model while being a multiple of 64, which is good for GPU performance.

RoPE theta parameter Θ 10000.
Number of layers and heads 4 layers, 16 heads. Together, this will give about 17M non-embedding
parameters which is a fairly small Transformer.
Total tokens processed 327,680,000 (your batch size × total step count × context length should equal
roughly this value).
You should do some trial and error to find good defaults for the following other hyperparameters:
learning rate, learning rate warmup, other AdamW hyperparameters (𝛽1 , 𝛽2 , 𝜀), and weight decay. You
can find some typical choices of such hyperparameters in D. P. Kingma et al. [22].

7.2.2 Putting it together
Now you can put everything together by getting a trained BPE tokenizer, tokenizing the training dataset,
and running this in the training loop that you wrote. Important note: If your implementation is correct
and efficient, the above hyperparameters should result in a roughly 20–30 minute runtime on 1 B200

GPU. If you have runtimes that are much longer, please check and make sure your dataloading,
checkpointing, or validation loss code is not bottlenecking your runtimes and that your implementation is
properly batched.

7.2.3 Tips and tricks for debugging model architectures
We highly recommend getting comfortable with your IDE’s built-in debugger (e.g., VSCode/Zed), which
will save you time compared to debugging with print statements. If you use a text editor, you can use
something like ipdb. A few other good practices when debugging model architectures are:
• A common first step when developing any neural net architecture is to overfit to a single minibatch. If
  your implementation is correct, you should be able to quickly drive the training loss to near-zero.
• Set debug breakpoints in various model components, and inspect the shapes of intermediate tensors to
  make sure they match your expectations.
• Monitor the norms of activations, model weights, and gradients to make sure they are not exploding or
  vanishing.


 Problem (learning_rate): Tune the learning rate (2 B200 hrs) (3 points)


   The learning rate is one of the most important hyperparameters to tune. Taking the base model
   you’ve trained, answer the following questions:
    (a) Perform a hyperparameter sweep over the learning rates and report the final losses (or note
        divergence if the optimizer diverges).
        Deliverable: Learning curves associated with multiple learning rates. Explain your
        hyperparameter search strategy.
        Deliverable: A model with validation loss (per-token) on TinyStories of at most 1.45


         Low-Resource Tip: Train for a few steps on CPU or Apple Silicon


           If you are running on cpu or mps, you should instead reduce the total tokens processed
           count to 40, 000, 000, which will be sufficient to produce reasonably fluent text. You
           may also increase the target validation loss from 1.45 to 2.00.
           Running our solution code with a tuned learning rate on an M4 Max chip and 36 GB
           of RAM, we use batch size × total step count × context length = 32 × 5000 × 256 =
           40, 960, 000 tokens, which takes 1 hour and 22 minutes on cpu and 36 minutes on mps.
           At step 5000, we achieve a validation loss of 1.80.
           Some additional tips:
           • When using 𝑁 training steps, we suggest adjusting the cosine learning rate decay
             schedule to terminate its decay (i.e., reach the minimum learning rate) at precisely
             step 𝑁 .
           • When using mps, do not use TF32 kernels, i.e., do not set
                   torch.set_float32_matmul_precision('high')

              as you might with cuda devices. We tried enabling TF32 kernels with mps (torch
              version 2.9.0) and found the backend sometimes uses silently broken kernels that
              cause unstable training.

           • You can speed up training by JIT-compiling your model with torch.compile.
             Specifically:
              ‣ On cpu, compile your model with
                     model = torch.compile(model)

              ‣ On mps, you can somewhat optimize the backward pass using
                     model = torch.compile(model, backend="aot_eager")

                Compilation with Inductor is not supported on mps as of torch version 2.9.0.

   (b) Folk wisdom is that the best learning rate is “at the edge of stability.” Investigate how the
       point at which learning rates diverge is related to your best learning rate.
        Deliverable: Learning curves of increasing learning rate which include at least one divergent
        run and an analysis of how this relates to convergence rates.


Now let’s vary the batch size and see what happens to training. Batch sizes are important – they let us
get higher efficiency from our GPUs by doing larger matrix multiplies, but is it true that we always want
batch sizes to be large? Let’s run some experiments to find out.


 Problem (batch_size_experiment): Batch size variations (1 B200 hr) (1 point)


   Vary your batch size all the way from 1 to the GPU memory limit. Try at least a few batch sizes
   in between, including typical sizes like 64 and 128.
   Deliverable: Learning curves for runs with different batch sizes. The learning rates should be
   optimized again if necessary.
   Deliverable: A few sentences discussing your findings on batch sizes and their impacts on
   training.


With your decoder in hand, we can now generate text! We will generate from the model and see how
good it is. As a reference, you should get outputs that look at least as good as the example below.


 Example (ts_generate_example): Sample output from a TinyStories language model


   Once upon a time, there was a pretty girl named Lily. She loved to eat gum, especially the big
   black one. One day, Lily’s mom asked her to help cook dinner. Lily was so excited! She loved to
   help her mom. Lily’s mom made a big pot of soup for dinner. Lily was so happy and said, “Thank
   you, Mommy! I love you.” She helped her mom pour the soup into a big bowl. After dinner, Lily’s
   mom made some yummy soup. Lily loved it! She said, “Thank you, Mommy! This soup is so
   yummy!” Her mom smiled and said, “I’m glad you like it, Lily.” They finished cooking and
   continued to cook together. The end.



 Low-Resource Tip: Generate text on CPU or Apple Silicon

   If instead you used the low-resource configuration with 40M tokens processed, you should see
   generations that still resemble English but are not as fluent as above. For example, our sample
   output from a TinyStories language model trained on 40M tokens is below:


   Once upon a time, there was a little girl named Sue. Sue had a tooth that she loved very much. It
   was his best head. One day, Sue went for a walk and met a ladybug! They became good friends
   and played on the path together.
   “Hey, Polly! Let’s go out!” said Tim. Sue looked at the sky and saw that it was difficult to find a
   way to dance shining. She smiled and agreed to help the talking!“
   As Sue watched the sky moved, what it was. She


Here is the precise problem statement and what we ask for:


 Problem (generate): Generate text (1 point)


   Using your decoder and your trained checkpoint, report the text generated by your model. You
   may need to manipulate decoder parameters (temperature, top-p, etc.) to get fluent outputs.
   Deliverable: Text dump of at least 256 tokens of text (or until the first <|endoftext|> token),
   and a brief comment on the fluency of this output and at least two factors which affect how good
   or bad this output is.

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

正在加载本章讨论…

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

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