CS336.wiki
CS336 中文实验手册/Transformer 架构
反馈与讨论
ASSIGNMENT 01 / 3.5

完整模型与资源核算

2026 春季 · v26.0.3原文 p. 26–28对照 PDF ↗

3.5 完整的 Transformer 语言模型#

现在开始组装 Transformer 块,可回看图 2。每个块包含多头自注意力和 SwiGLU 前馈网络两个子层。每个子层先进行 RMSNorm,再执行主要运算,最后加上残差。

具体而言,第一个子层应从输入 xx 得到:

y=x+MultiHeadSelfAttention⁡(RMSNorm⁡(x))(15) y=x+\operatorname{MultiHeadSelfAttention}(\operatorname{RMSNorm}(x)) \tag{15}
练习 transformer_block3 分

实现 Transformer 块

按照第 3.4 节及图 2,实现预归一化 Transformer 块,至少接收:

参数 类型 含义
d_model int 输入维数。
num_heads int 多头自注意力的头数。
d_ff int 逐位置前馈网络的内部维数。

实现 adapters.run_transformer_block,运行 uv run pytest -k test_transformer_block。

交付物: 通过所给测试的 Transformer 块代码。

按照图 1 组装完整模型:第 3.1 节的 token 嵌入,接 num_layers 个 Transformer 块,之后接最终归一化与 LM head,得到词表上的未归一化分数,即 logits。

练习 transformer_lm3 分

实现 Transformer 语言模型

按照第 3.1 节与图 1,实现完整模型。除前述块的构造参数外,至少增加:

参数 类型 含义
vocab_size int 词表大小,用于确定 token 嵌入矩阵形状。
context_length int 最大上下文长度,用于确定 RoPE 正弦、余弦缓冲区形状。
num_layers int Transformer 块数量。

实现 adapters.run_transformer_lm,运行 uv run pytest -k test_transformer_lm。

交付物: 通过上述测试的 Transformer LM 模块。

资源核算#

理解各组件的计算、内存需求很有用。Transformer 的绝大多数 FLOPs 来自矩阵乘法,因此基本核算方法是:列出一次前向传播的全部矩阵乘法,再将其换算为 FLOPs。

规则: 若 A∈Rm×nA\in\mathbb{R}^{m\times n}、B∈Rn×pB\in\mathbb{R}^{n\times p},则 ABAB 需要 2mnp2mnp 次浮点运算。

这是因为输出的每一项是长度为 nn 的点积,按此约定计 nn 次加法与 nn 次乘法;输出有 mpmp 项,因此总计 2mnp2mnp FLOPs。

做下一题前,可以逐个检查 Transformer 块和完整模型的组件,列出对应的矩阵乘法及成本。

练习 transformer_accounting5 分

Transformer 语言模型资源核算

(a) 考虑使用本作业架构的 GPT-2 XL 规模模型:

配置 值
vocab_size 50,257
context_length 1,024
num_layers 48
d_model 1,600
num_heads 25
d_ff 4,288,即最接近 83×1600\frac{8}{3}\times1600 的 64 的倍数。

它有多少可训练参数?每个参数采用单精度浮点数时,仅加载模型需要多少内存?

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

(b) 列出该 GPT-2 XL 形状模型完成一次前向传播所需的矩阵乘法。输入长度等于 context_length 时,总共需要多少 FLOPs?

交付物: 带说明的矩阵乘法列表,以及 FLOPs 总数。

(c) 根据上述分析,模型哪部分消耗最多 FLOPs?

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

(d) 对 GPT-2 small(12 层、768 维、12 头)、medium(24 层、1024 维、16 头)、large(36 层、1280 维、20 头)重复分析。模型变大时,各组件占总 FLOPs 的比例如何变化?

交付物: 每个模型的组件 FLOPs 比例明细,以及一至两句话描述规模变化对占比的影响。

(e) 把 GPT-2 XL 上下文长度增加到 16,384。一次前向传播的总 FLOPs 如何变化?各组件的 FLOPs 相对贡献如何变化?

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

一起把这一章读得更好

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

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

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

3.5 The Full Transformer LM
Let’s begin by assembling the Transformer block (it will be helpful to refer back to Figure 2). A
Transformer block contains two ‘sub-layers’, one for the multihead self attention, and another for the
SwiGLU feed-forward network. In each sub-layer, we first perform RMSNorm, then the main operation
(MHA/FF), finally adding in the residual connection.
To be concrete, the first half (the first ‘sub-layer’) of the Transformer block should be implementing the
following set of updates to produce an output 𝑦 from an input 𝑥,
                             𝑦 = 𝑥 + MultiHeadSelfAttention(RMSNorm(𝑥)).                                (15)


 Problem (transformer_block): Implement the Transformer block (3 points)


   Implement the pre-norm Transformer block as described in Section 3.4 and illustrated in Figure 2.
   Your Transformer block should accept (at least) the following parameters.
   d_model: int Dimensionality of the Transformer block inputs.

   num_heads: int Number of heads to use in multi-head self-attention.

   d_ff: int Dimensionality of the position-wise feed-forward inner layer.

   To test your implementation, implement the adapter [adapters.run_transformer_block] . Then
   run uv run pytest -k test_transformer_block to test your implementation.
   Deliverable: Transformer block code that passes the provided tests.


Now we put the blocks together, following the high-level diagram in Figure 1. Follow our description of
the embedding in Section 3.1.0.1, feed this into num_layers Transformer blocks, and then pass that into
the final layer norm and LM head to obtain an unnormalized distribution over the vocabulary (the
logits).


 Problem (transformer_lm): Implementing the Transformer LM (3 points)


   Time to put it all together! Implement the Transformer language model as described in
   Section 3.1 and illustrated in Figure 1. At minimum, your implementation should accept all the
   aforementioned construction parameters for the Transformer block, as well as these additional
   parameters:
   vocab_size: int The size of the vocabulary, necessary for determining the dimensionality of the
       token embedding matrix.

    context_length: int The maximum context length, necessary for determining the dimensionality
       of the RoPE sin and cos buffer.
    num_layers: int The number of Transformer blocks to use.

    To test your implementation against our provided tests, you will first need to implement the test
    adapter at [adapters.run_transformer_lm] . Then, run uv run pytest -k test_transformer_lm to
    test your implementation.
    Deliverable: A Transformer LM module that passes the above tests.


Resource accounting
It is useful to be able to understand how the various parts of the Transformer consume compute and
memory. We will go through the steps to do some basic “FLOPs accounting.” The vast majority of
FLOPS in a Transformer are matrix multiplies, so our core approach is simple:
1. Write down all the matrix multiplies in a Transformer forward pass.
2. Convert each matrix multiply into FLOPs required.
For this second step, the following fact will be useful:

 Rule: Given 𝐴 ∈ ℝ𝑚×𝑛 and 𝐵 ∈ ℝ𝑛×𝑝 , the matrix-matrix product 𝐴𝐵 requires 2𝑚𝑛𝑝 FLOPs.

To see this, note that (𝐴𝐵)[𝑖, 𝑗] = 𝐴[𝑖, :] ⋅ 𝐵[:, 𝑗], and that this dot product requires 𝑛 additions and 𝑛
multiplications (2𝑛 FLOPs). Then, since the matrix-matrix product 𝐴𝐵 has 𝑚 × 𝑝 entries, the total
number of FLOPS is (2𝑛)(𝑚𝑝) = 2𝑚𝑛𝑝.
Now, before you do the next problem, it can be helpful to go through each component of your
Transformer block and Transformer LM, and list out all the matrix multiplies and their associated
FLOPs costs.


 Problem (transformer_accounting): Transformer LM resource accounting (5 points)


    (a) Consider a GPT-2 XL-sized model using our assignment architecture, which has the following
        configuration:
         vocab_size:   50,257
         context_length:    1,024
         num_layers:   48
         d_model:   1,600
         num_heads:    25
         d_ff:   4,288 (the nearest multiple of 64 to 83 × 1, 600)
        Suppose we constructed our model using this configuration. How many trainable parameters
        would our model have? Assuming each parameter is represented using single-precision floating
        point, how much memory is required to just load this model?
        Deliverable: A one-to-two sentence response.
    (b) Identify the matrix multiplies required to complete a forward pass of our GPT-2 XL-shaped
        model. How many FLOPs do these matrix multiplies require in total? Assume that our input
        sequence has context_length tokens.

          Deliverable: A list of matrix multiplies (with descriptions), and the total number of FLOPs
          required.
      (c) Based on your analysis above, which parts of the model require the most FLOPs?
          Deliverable: A one-to-two sentence response.
      (d) Repeat your analysis with GPT-2 small (12 layers, 768 d_model, 12 heads), GPT-2 medium
          (24 layers, 1024 d_model, 16 heads), and GPT-2 large (36 layers, 1280 d_model, 20 heads). As
          the model size increases, which parts of the Transformer LM take up proportionally more or
          less of the total FLOPs?
          Deliverable: For each model, provide a breakdown of model components and its associated
          FLOPs (as a proportion of the total FLOPs required for a forward pass). In addition, provide
          a one-to-two sentence description of how varying the model size changes the proportional
          FLOPs of each component.
      (e) Take GPT-2 XL and increase the context length to 16,384. How does the total FLOPs for one
          forward pass change? How does the relative contribution of FLOPs of the model components
          change?
          Deliverable: A one-to-two sentence response.

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

正在加载本章讨论…

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

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