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

RMSNorm 与 SwiGLU

2026 春季 · v26.0.3原文 p. 19–22对照 PDF ↗

3.4 预归一化 Transformer 块#

每个 Transformer 块有两个子层:多头自注意力与逐位置前馈网络,见 Vaswani 等人 [8] 第 3.1 节。

原始 Transformer 在每个子层外添加残差连接,之后执行层归一化,通常称为 post-norm(后归一化)。后续研究 [9, 10] 发现,把归一化移到每个子层的输入端,并在最终块后额外归一化,能提高训练稳定性,这就是图 2 的 pre-norm 结构。

每个子层的输出仍通过残差连接与其输入相加。对 pre-norm 的一种直觉解释是:从输入嵌入到最终输出,有一条未经归一化打断的“残差流”,可能改善梯度传播。这已成为 GPT-3、LLaMA、PaLM 等模型采用的标准结构。本作业将依次实现其中各组件。

3.4.1 均方根层归一化#

原始 Transformer [8] 使用 LayerNorm [11]。本作业跟随 LLaMA [12],采用均方根层归一化 RMSNorm [13]。给定激活向量 a∈Rdmodela\in\mathbb{R}^{d_{\mathrm{model}}},各分量变换为:

RMSNorm⁡(ai)=aiRMS⁡(a)gi(4) \operatorname{RMSNorm}(a_i)=\frac{a_i}{\operatorname{RMS}(a)}g_i \tag{4}

其中:

RMS⁡(a)=1dmodel∑i=1dmodelai2+ε \operatorname{RMS}(a)=\sqrt{\frac{1}{d_{\mathrm{model}}}\sum_{i=1}^{d_{\mathrm{model}}}a_i^2+\varepsilon}

gig_i 是可学习的增益参数,共 dmodeld_{\mathrm{model}} 个;ε\varepsilon 通常设为 10−510^{-5}。

计算前应把输入提升为 torch.float32,避免平方时溢出;计算后将结果转回原始数据类型。原文给出的前向框架保留如下:

指导书原文
in_dtype = x.dtype
x = x.to(torch.float32)

# Your code here performing RMSNorm
...
result = ...

# Return the result in the original dtype
return result.to(in_dtype)
练习 rmsnorm1 分

均方根层归一化

交付物: 将 RMSNorm 实现为 torch.nn.Module。

构造方法接收 d_model: int、eps: float = 1e-5,以及可选 device、dtype。d_model 为模型隐藏维度,eps 用于数值稳定。

前向方法接收 (batch_size, sequence_length, d_model) 张量,返回同形状张量。务必在归一化前提升到 float32,之后恢复原类型。

实现 adapters.run_rmsnorm,运行 uv run pytest -k test_rmsnorm。

3.4.2 逐位置前馈网络#

原始 Transformer [8] 第 3.3 节采用两次线性变换,中间使用 ReLU⁡(x)=max⁡(0,x)\operatorname{ReLU}(x)=\max(0,x);内部维度通常为输入维度的 4 倍。

现代语言模型主要有两个改动:使用其他激活函数,并引入门控。本作业采用 Llama 3 [14]、Qwen 2.5 [15] 等模型使用的 SwiGLU,将 SiLU/Swish 与门控线性单元 GLU 结合。同时沿用 PaLM [16]、LLaMA [12] 以来多数现代模型的做法,省略偏置项。

SiLU,又称 Swish [17, 18],定义为:

SiLU⁡(x)=xσ(x)=x1+e−x(5) \operatorname{SiLU}(x)=x\sigma(x)=\frac{x}{1+e^{-x}} \tag{5}

指导书图 3:SiLU、恒等函数与 ReLU 的比较

图 3:SiLU 与 ReLU 类似,但在零点处平滑;Identity 表示恒等函数。

GLU 最初由 Dauphin 等人 [19] 定义为:一次线性变换经过 sigmoid 后,与另一次线性变换逐元素相乘:

GLU⁡(x,W1,W2)=σ(W1x)⊙W2x(6) \operatorname{GLU}(x,W_1,W_2)=\sigma(W_1x)\odot W_2x \tag{6}

⊙\odot 表示逐元素乘法。原文引用的直觉是:在保留非线性能力的同时,为梯度提供一条线性路径,以减轻深层网络中的梯度消失。

结合 SiLU 与 GLU,得到本作业使用的前馈网络:

FFN⁡(x)=SwiGLU⁡(x,W1,W2,W3)=W2(SiLU⁡(W1x)⊙W3x)(7) \operatorname{FFN}(x)=\operatorname{SwiGLU}(x,W_1,W_2,W_3) =W_2\big(\operatorname{SiLU}(W_1x)\odot W_3x\big) \tag{7}

其中 x∈Rdmodelx\in\mathbb{R}^{d_{\mathrm{model}}},W1,W3∈Rdff×dmodelW_1,W_3\in\mathbb{R}^{d_{\mathrm{ff}}\times d_{\mathrm{model}}},W2∈Rdmodel×dffW_2\in\mathbb{R}^{d_{\mathrm{model}}\times d_{\mathrm{ff}}}。通常取 dff=83dmodeld_{\mathrm{ff}}=\frac{8}{3}d_{\mathrm{model}},实现中可舍入到附近的 64 的倍数,以提高硬件效率。

Shazeer [20] 首先提出结合 SiLU 与 GLU,并通过实验发现 SwiGLU 在语言建模上优于 ReLU、无门控 SiLU 等基线。后续作业会比较 SwiGLU 与 SiLU。虽然有上述启发式解释和论文证据,仍应保持实证视角。原文引用 Shazeer 的玩笑:“我们无法解释这些结构为何奏效;与其他一切一样,我们将它们的成功归功于上天的仁慈。”

练习 positionwise_feedforward2 分

实现逐位置前馈网络

交付物: 实现由 SiLU 和 GLU 组成的 SwiGLU 前馈网络。

为保证数值稳定,此处允许直接使用 torch.sigmoid。

将 dffd_{\mathrm{ff}} 设置为约 83dmodel\frac{8}{3}d_{\mathrm{model}},同时保证内部维度是 64 的倍数,以充分利用硬件。

实现 adapters.run_swiglu,运行 uv run pytest -k test_swiglu。

一起把这一章读得更好

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

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

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

3.4 Pre-Norm Transformer Block
Each Transformer block has two sub-layers: a multi-head self-attention mechanism and a position-wise
feed-forward network ([A. Vaswani et al., 2017], section 3.1).
In the original Transformer paper, the model uses a residual connection around each of the two sub-
layers, followed by layer normalization. This architecture is commonly known as the “post-norm”
Transformer, since layer normalization is applied to the sub-layer output. However, a variety of work has
found that moving layer normalization from the output of each sub-layer to the input of each sub-layer
(with an additional layer normalization after the final Transformer block) improves Transformer training
stability [T. Q. Nguyen et al., 2019; R. Xiong et al., 2020] — see Figure 2 for a visual representation of
this “pre-norm” Transformer block. The output of each Transformer block sub-layer is then added to the
sub-layer input via the residual connection (A. Vaswani et al. [8], section 5.4). An intuition for pre-norm
is that there is a clean “residual stream” without any normalization going from the input embeddings to
the final output of the Transformer, which is purported to improve gradient flow. This pre-norm
Transformer is now the standard used in language models today (e.g., GPT-3, LLaMA, PaLM, etc.), so
we will implement this variant. We will walk through each of the components of a pre-norm Transformer
block, implementing them in sequence.

3.4.1 Root Mean Square Layer Normalization
The original Transformer implementation of A. Vaswani et al. [8] uses layer normalization
[J. L. Ba et al., 2016] to normalize activations. Following H. Touvron et al. [12], we will use root mean
square layer normalization (RMSNorm; B. Zhang et al. [13], equation 4) for layer normalization. Given a
vector 𝑎 ∈ ℝ𝑑model of activations, RMSNorm will rescale each activation 𝑎𝑖 as follows:
                                                            𝑎𝑖
                                       RMSNorm(𝑎𝑖 ) =           𝑔,                                       (4)
                                                          RMS(𝑎) 𝑖

where RMS(𝑎) = √ 𝑑 1 ∑𝑑𝑖=1   model
                                   𝑎2𝑖 + 𝜀. Here, 𝑔𝑖 is a learnable “gain” parameter (there are d_model such
                     model
parameters total), and 𝜀 is a hyperparameter that is often fixed at 1e-5.
You should upcast your input to torch.float32 to prevent overflow when you square the input. Overall,
your forward method should look like:
  in_dtype = x.dtype
  x = x.to(torch.float32)

  # Your code here performing RMSNorm
  ...
  result = ...

  # Return the result in the original dtype
  return result.to(in_dtype)


 Problem (rmsnorm): Root Mean Square Layer Normalization (1 point)


    Deliverable: Implement RMSNorm as a torch.nn.Module. We recommend the following interface:
    def __init__(self, d_model: int, eps: float = 1e-5, device=None, dtype=None) Construct the
       RMSNorm module. This function should accept the following parameters:
     d_model: int   Hidden dimension of the model
     eps: float = 1e-5    Epsilon value for numerical stability
     device: torch.device | None = None      Device to store the parameters on
     dtype: torch.dtype | None = None      Data type of the parameters
    def forward(self, x: torch.Tensor) -> torch.Tensor Process an input tensor of shape
       (batch_size, sequence_length, d_model) and return a tensor of the same shape.

    Note: Remember to upcast your input to torch.float32 before performing the normalization
    (and later downcast to the original dtype), as described above.
    To test your implementation, implement the test adapter at [adapters.run_rmsnorm] . Then, run
    uv run pytest -k test_rmsnorm.

3.4.2 Position-Wise Feed-Forward Network

                                             SiLU: f(x) = x (x)
                                    4        Identity: f(x) = x
                                             ReLU: f(x) = max(0, x)
                                    2


                          SiLU(x)   0

                                    2

                                    4
                                         4          2         0       2      4
                                                              x
                Figure 3: Comparing the SiLU (aka Swish) and ReLU activation functions.
In the original Transformer paper (section 3.3 of A. Vaswani et al. [8]), the Transformer feed-forward
network consists of two linear transformations with a ReLU activation (ReLU(𝑥) = max(0, 𝑥)) between
them. In that original architecture, the dimensionality of the inner feed-forward layer is typically 4x the
input dimensionality.
However, modern language models tend to incorporate two main changes compared to this original
design: they use another activation function and employ a gating mechanism. Specifically, we will
implement the “SwiGLU” activation function adopted in LLMs like Llama 3 [A. Grattafiori et al., 2024]
and Qwen 2.5 [A. Yang et al., 2024], which combines the SiLU (often called Swish) activation with a
gating mechanism called a Gated Linear Unit (GLU). We will also omit the bias terms sometimes used in
linear layers, following most modern LLMs since PaLM [A. Chowdhery et al., 2022] and LLaMA
[H. Touvron et al., 2023].
The SiLU or Swish activation function [D. Hendrycks et al., 2016; S. Elfwing et al., 2017] is defined as
follows:
                                                                     𝑥
                                          SiLU(𝑥) = 𝑥 ⋅ 𝜎(𝑥) =                                             (5)
                                                                  1 + 𝑒−𝑥
As can be seen in Figure 3, the SiLU activation function is similar to the ReLU activation function, but is
smooth at zero.
Gated Linear Units (GLUs) were originally defined by Y. N. Dauphin et al. [19] as the element-wise
product of a linear transformation passed through a sigmoid function and another linear transformation:
                                        GLU(𝑥, 𝑊1 , 𝑊2 ) = 𝜎(𝑊1 𝑥) ⊙ 𝑊2 𝑥,                                 (6)

where ⊙ represents element-wise multiplication. Gated Linear Units are suggested to “reduce the
vanishing gradient problem for deep architectures by providing a linear path for the gradients while
retaining non-linear capabilities.”

Putting the SiLU/Swish and GLU together, we get the SwiGLU, which we will use for our feed-forward
networks:
                          FFN(𝑥) = SwiGLU(𝑥, 𝑊1 , 𝑊2 , 𝑊3 ) = 𝑊2 (SiLU(𝑊1 𝑥) ⊙ 𝑊3 𝑥),                              (7)

where 𝑥 ∈ ℝ𝑑model , 𝑊1 , 𝑊3 ∈ ℝ𝑑ff ×𝑑model , 𝑊2 ∈ ℝ𝑑model ×𝑑ff , and canonically, 𝑑ff = 83 𝑑model . For concrete
implementations, it is fine to round this to a nearby multiple of 64 for hardware efficiency.
N. Shazeer [20] first proposed combining the SiLU/Swish activation with GLUs and conducted
experiments showing that SwiGLU outperforms baselines like ReLU and SiLU (without gating) on
language modeling tasks. Later in the assignment, you will compare SwiGLU and SiLU. Though we’ve
mentioned some heuristic arguments for these components (and the papers provide more supporting
evidence), it’s good to keep an empirical perspective: a now famous quote from Shazeer’s paper is


  “We offer no explanation as to why these architectures seem to work; we attribute their success, as
  all else, to divine benevolence.”


 Problem (positionwise_feedforward): Implement the position-wise feed-forward network (2
 points)


    Deliverable: Implement the SwiGLU feed-forward network, composed of a SiLU activation
    function and a GLU.
    Note: in this particular case, you should feel free to use torch.sigmoid in your implementation
    for numerical stability.
    You should set 𝑑ff to approximately 83 × 𝑑model in your implementation, while ensuring that the
    dimensionality of the inner feed-forward layer is a multiple of 64 to make good use of your
    hardware. To test your implementation against our provided tests, you will need to implement the
    test adapter at [adapters.run_swiglu] . Then, run uv run pytest -k test_swiglu to test your
    implementation.

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

正在加载本章讨论…

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

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