CS336.wiki
CS336 中文实验手册/训练与优化
反馈与讨论
ASSIGNMENT 01 / 4.3

AdamW 优化器

2026 春季 · v26.0.3原文 p. 31–33对照 PDF ↗

4.3 AdamW#

现代语言模型通常使用比 SGD 更复杂的优化器,近期多数优化器源自 Adam [22]。本作业采用广泛使用的 AdamW [23]。

AdamW 通过增加与梯度更新解耦的权重衰减,改善正则化效果:每次迭代都让参数向零收缩。实现应遵循 Loshchilov 等人 [23] 的算法 2。

AdamW 是有状态的:每个参数都要维护一阶、二阶矩的运行估计。因此,它用额外内存换取更好的稳定性与收敛。

除学习率 α\alpha,还有控制矩估计更新的 (β1,β2)(\beta_1,\beta_2),以及权重衰减系数 λ\lambda。常见取值是 (0.9,0.999)(0.9,0.999),但 LLaMA [12]、GPT-3 [24] 等大语言模型经常采用 (0.9,0.95)(0.9,0.95)。ε\varepsilon 是如 10−810^{-8} 这样的小数,用于在二阶矩很小时改善数值稳定性。

指导书算法 1#

下面原样保留指导书的 AdamW 算法图,避免重新排版改变更新顺序或偏置校正细节。

指导书算法 1:AdamW 优化器

图中 init 为初始化,first/second moment 为一阶/二阶矩,weight decay 为权重衰减。注意迭代计数 tt 从 1 开始。学习率校正、权重衰减和矩更新的顺序均按原图。

练习 adamw2 分

实现 AdamW

交付物: 实现继承 torch.optim.Optimizer 的 AdamW 类。构造方法接收学习率 α\alpha、一阶和二阶矩衰减系数 (β1,β2)(\beta_1,\beta_2)、数值稳定项 ε\varepsilon、权重衰减系数 λ\lambda 等超参数。

父类的 self.state 字典将 nn.Parameter 映射到各参数的状态字典,可保存 AdamW 所需的矩估计。

实现 adapters.get_adamw_cls,通过 uv run pytest -k test_adamw。

练习 adamw_accounting2 分

AdamW 训练资源核算

假设全部张量均使用 float32,计算 AdamW 的内存与运算需求。

(a) 峰值内存是多少?分别计算参数、激活、梯度、优化器状态的占用,用 batch_size 与模型超参数 vocab_size、context_length、num_layers、d_model、num_heads 表示,假定 dff=83dmodeld_{\mathrm{ff}}=\frac83d_{\mathrm{model}}。

为简化计算,激活内存只考虑:

  • Transformer 块中的 RMSNorm。
  • 多头自注意力子层:QKV 投影、QK⊤QK^\top 矩阵乘法、softmax、值的加权和、输出投影。
  • SwiGLU 前馈网络:W1W_1、W2W_2、门控分支的 SiLU、逐元素乘积、W3W_3。
  • 最终 RMSNorm、输出嵌入、logits 上的交叉熵。

交付物: 参数、激活、梯度、优化器状态各自的代数式与总和。

(b) 对 GPT-2 XL 形状的模型代入数值,使表达式只依赖 batch_size。在 80 GB 内存内能容纳的最大批次是多少?

交付物: 形如 a⋅batch_size+ba\cdot\mathrm{batch\_size}+b 的数值表达式,以及最大批次大小。

(c) AdamW 一次更新需要多少 FLOPs?

交付物: 代数表达式及简短说明。

(d) 模型 FLOPs 利用率 MFU [16] 通常定义为训练实际需要的模型 FLOPs 与硬件同时期理论可提供峰值 FLOPs 之比;实际测量时,常由 token 吞吐量和每个 token 的模型 FLOPs 推导。NVIDIA H100 的 495 TFLOP/s 指 TensorFloat-32(TF32)Tensor Core 峰值;原文中的 “bfloat19” 是笔误。

若达到 50% MFU,单张 H100 训练 GPT-2 XL 400K 步、批次大小 1024,需要多久?沿用 Kaplan 等人 [25] 和 Hoffmann 等人 [26],假定反向传播 FLOPs 是前向传播的两倍。

交付物: 所需小时数及简短说明。

一起把这一章读得更好

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

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

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

4.3 AdamW
Modern language models are typically trained with more sophisticated optimizers, instead of SGD. Most
optimizers used recently are derivatives of the Adam optimizer [D. P. Kingma et al., 2015]. We will use
AdamW [I. Loshchilov et al., 2019], which is in wide use in recent work. AdamW proposes a modification
to Adam that improves regularization by adding weight decay (at each iteration, we pull the parameters
towards 0), in a way that is decoupled from the gradient update. We will implement AdamW as described
in algorithm 2 of I. Loshchilov et al. [23].
AdamW is stateful: for each parameter, it keeps track of a running estimate of its first and second
moments. Thus, AdamW uses additional memory in exchange for improved stability and convergence.
Besides the learning rate 𝛼, AdamW has a pair of hyperparameters (𝛽1 , 𝛽2 ) that control the updates to
the moment estimates, and a weight decay rate 𝜆. Typical applications set (𝛽1 , 𝛽2 ) to (0.9, 0.999), but
large language models like LLaMA [H. Touvron et al., 2023] and GPT-3 [T. B. Brown et al., 2020] are
often trained with (0.9, 0.95). The algorithm can be written as follows, where 𝜀 is a small value (e.g.,
10−8 ) used to improve numerical stability in case we get extremely small values in 𝑣:

                Algorithm 1: AdamW Optimizer
                 1 init(𝜃)   ▷ Initialize learnable parameters
                 2 𝑚←0       ▷ Initial value of the first moment vector; same shape as 𝜃
                 3 𝑣←0      ▷ Initial value of the second moment vector; same shape as 𝜃
                 4 for 𝑡 = 1, …, 𝑇 do
                 5   Sample batch of data 𝐵𝑡
                 6   𝑔 ← ∇𝜃 ℓ(𝜃; 𝐵𝑡 ) ▷ Compute the gradient of the loss
                              √1−𝛽𝑡
                 7    𝛼𝑡 ← 𝛼 1−𝛽𝑡 2   ▷ Compute adjusted 𝛼 for iteration 𝑡
                                 1
                 8    𝜃 ← 𝜃 − 𝛼𝜆𝜃 ▷ Apply weight decay
                 9    𝑚 ← 𝛽1 𝑚 + (1 − 𝛽1 )𝑔 ▷ Update the first moment estimate
                10    𝑣 ← 𝛽2 𝑣 + (1 − 𝛽2 )𝑔2 ▷ Update the second moment estimate
                                   𝑚
                11    𝜃 ← 𝜃 − 𝛼𝑡 √𝑣+𝜀     ▷ Apply moment-adjusted weight updates
                12 end for

                               Algorithm 1: AdamW optimizer pseudocode.
Note that 𝑡 starts at 1. You will now implement this optimizer.


 Problem (adamw): Implement AdamW (2 points)


   Deliverable: Implement the AdamW optimizer as a subclass of torch.optim.Optimizer. Your
   class should take the learning rate 𝛼 in __init__, as well as the 𝛽, 𝜀 and 𝜆 hyperparameters. To
   help you keep state, the base Optimizer class gives you a dictionary self.state, which maps
   nn.Parameter objects to a dictionary that stores any information you need for that parameter (for
   AdamW, this would be the moment estimates). Implement [adapters.get_adamw_cls] and make
   sure it passes uv run pytest -k test_adamw.



 Problem (adamw_accounting): Resource accounting for training with AdamW (2 points)


   Let us compute how much memory and compute running AdamW requires. Assume we are using
   float32 for every tensor.
   (a) How much peak memory does running AdamW require? Decompose your answer based on the
       memory usage of the parameters, activations, gradients, and optimizer state. Express your
       answer in terms of the batch_size and the model hyperparameters (vocab_size,
       context_length, num_layers, d_model, num_heads). Assume 𝑑ff = 83 × 𝑑model .

        For simplicity, when calculating memory usage of activations, consider only the following
        components:
        • Transformer block
          ‣ RMSNorm(s)
          ‣ Multi-head self-attention sublayer: 𝑄𝐾𝑉 projections, 𝑄𝐾 ⊤ matrix multiply, softmax,
            weighted sum of values, output projection.
          ‣ Position-wise feed-forward (SwiGLU): 𝑊1 , 𝑊2 , SiLU on the gate branch, element-wise
            product, 𝑊3

            • final RMSNorm
            • output embedding
            • cross-entropy on logits
            Deliverable: An algebraic expression for each of parameters, activations, gradients, and
            optimizer state, as well as the total.
       (b) Instantiate your answer for a GPT-2 XL-shaped model to get an expression that only
           depends on the batch_size. What is the maximum batch size you can use and still fit within
           80GB memory?
            Deliverable: An expression that looks like 𝑎 ⋅ batch_size + 𝑏 for numerical values 𝑎, 𝑏, and a
            number representing the maximum batch size.
       (c) How many FLOPs does running one step of AdamW take?
            Deliverable: An algebraic expression, with a brief justification.
       (d) Model FLOPs utilization (MFU) is defined as the ratio of observed throughput (tokens per
           second) relative to the hardware’s theoretical peak FLOP throughput
           [A. Chowdhery et al., 2022]. An NVIDIA H100 GPU has a theoretical peak of 495 teraFLOP/
           s for “float32” (actually TensorFloat-32, which in reality is “bfloat19”) operations. Assuming
           you are able to get 50% MFU, how long would it take to train a GPT-2 XL for 400K steps
           and a batch size of 1024 on a single H100? Following J. Kaplan et al. [25] and
           J. Hoffmann et al. [26], assume that the backward pass has twice the FLOPs of the forward
           pass.
            Deliverable: The number of hours training would take, with a brief justification.

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

正在加载本章讨论…

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

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