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

缩放点积注意力

2026 春季 · v26.0.3原文 p. 23–25对照 PDF ↗

3.4.4 缩放点积注意力#

本节实现 Vaswani 等人 [8] 第 3.2.1 节的缩放点积注意力。先实现其所需的 softmax,将未归一化分数向量转换成概率分布:

softmax⁡(v)i=exp⁡(vi)∑j=1nexp⁡(vj)(10) \operatorname{softmax}(v)_i=\frac{\exp(v_i)}{\sum_{j=1}^{n}\exp(v_j)} \tag{10}

当 viv_i 很大时,指数运算可能变为无穷大,之后的“无穷大除以无穷大”会产生 NaN。softmax 对所有输入同时加上任意常数不变,因此可以先减去向量最大值,使新的最大值为 0,提高数值稳定性。

练习 softmax1 分

实现 softmax

交付物: 编写函数,接收一个张量和维度 ii,沿第 ii 维应用 softmax。

返回张量形状不变,但该维上应形成归一化概率分布。使用减去该维最大值的技巧避免数值问题。

完成 adapters.run_softmax,通过 uv run pytest -k test_softmax_matches_pytorch。

注意力的定义#

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk)V(11) \operatorname{Attention}(Q,K,V)= \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V \tag{11}

其中 Q∈Rn×dkQ\in\mathbb{R}^{n\times d_k}、K∈Rm×dkK\in\mathbb{R}^{m\times d_k}、V∈Rm×dvV\in\mathbb{R}^{m\times d_v}。Q、K、V 都是本运算的输入,不是可学习参数。

掩码#

有时需要屏蔽部分注意力。布尔掩码 M∈{True,False}n×mM\in\{\mathrm{True},\mathrm{False}\}^{n\times m} 的第 ii 行表示查询 ii 应关注哪些键。

本指导书采用的约定是:True 表示允许关注,False 表示不允许关注。也就是说,信息只在值为 True 的位置流动。

例如,掩码 [[True, True, False]] 表示唯一的查询只关注前两个键。相比对多个子序列分别计算,使用掩码更高效:在 softmax 之前,对 QK⊤/dkQK^\top/\sqrt{d_k} 中对应 False 的位置加上 −∞-\infty。

练习 scaled_dot_product_attention5 分

实现缩放点积注意力

交付物: 实现缩放点积注意力函数。

键和查询的形状为 (batch_size, ..., seq_len, d_k),值的形状为 (batch_size, ..., seq_len, d_v)。省略号表示任意数量的其他批次维。输出应为 (batch_size, ..., seq_len, d_v)。批次维约定见第 3.2 节。

支持用户可选提供的 (seq_len, seq_len) 布尔掩码。对于每个查询,True 位置的注意力概率总和为 1,False 位置的概率为 0。

实现 adapters.run_scaled_dot_product_attention:

  • uv run pytest -k test_scaled_dot_product_attention 检查三阶输入。
  • uv run pytest -k test_4d_scaled_dot_product_attention 检查四阶输入。

一起把这一章读得更好

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

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

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

3.4.4 Scaled Dot-Product Attention
We will now implement scaled dot-product attention as described in A. Vaswani et al. [8] (section 3.2.1).
As a preliminary step, the definition of the Attention operation will make use of softmax, an operation
that takes an unnormalized vector of scores and turns it into a normalized distribution:
                                                          exp(𝑣𝑖 )
                                        softmax(𝑣)𝑖 =    𝑛            .                                   (10)
                                                        ∑𝑗=1 exp(𝑣𝑗 )

Note that exp(𝑣𝑖 ) can become inf for large values (then, inf
                                                           inf = NaN). We can avoid this by noticing that
the softmax operation is invariant to adding any constant 𝑐 to all inputs. We can leverage this property
for numerical stability—typically, we will subtract the largest entry of 𝑣 from all elements of 𝑣, making
the new largest entry 0. You will now implement softmax, using this trick for numerical stability.


 Problem (softmax): Implement softmax (1 point)


   Deliverable: Write a function to apply the softmax operation on a tensor. Your function should
   take two parameters: a tensor and a dimension 𝑖, and apply softmax to the 𝑖-th dimension of the
   input tensor. The output tensor should have the same shape as the input tensor, but its 𝑖-th
   dimension will now have a normalized probability distribution. Use the trick of subtracting the
   maximum value in the 𝑖-th dimension from all elements of the 𝑖-th dimension to avoid numerical
   stability issues.
   To test your implementation, complete [adapters.run_softmax] and make sure it passes uv run
   pytest -k test_softmax_matches_pytorch.


We can now define the Attention operation mathematically as follows:

                                                                 𝑄𝐾 𝑇
                                Attention(𝑄, 𝐾, 𝑉 ) = softmax(        )𝑉                                (11)
                                                                 √𝑑𝑘

where 𝑄 ∈ ℝ𝑛×𝑑𝑘 , 𝐾 ∈ ℝ𝑚×𝑑𝑘 , and 𝑉 ∈ ℝ𝑚×𝑑𝑣 . Here, 𝑄, 𝐾 and 𝑉 are all inputs to this operation—note
that these are not the learnable parameters.
Masking: It is sometimes convenient to mask the output of an attention operation. A mask should have
the shape 𝑀 ∈ {True, False}𝑛×𝑚 , and each row 𝑖 of this boolean matrix indicates which keys the query 𝑖
should attend to. Canonically (and slightly confusingly), a value of True at position (𝑖, 𝑗) indicates that
the query 𝑖 does attend to the key 𝑗, and a value of False indicates that the query does not attend to the
key. In other words, “information flows” at (𝑖, 𝑗) pairs with value True. For example, consider a 1 × 3
mask matrix with entries [[True, True, False]]. The single query vector attends only to the first two keys.
Computationally, it will be much more efficient to use masking than to compute attention on
subsequences, and we can do this by taking the pre-softmax values (𝑄𝐾 ⊤ /√𝑑𝑘 ) and adding a −∞ to
any entry of the mask matrix that is False.


 Problem (scaled_dot_product_attention): Implement scaled dot-product attention (5
 points)


   Deliverable: Implement the scaled dot-product attention function. Your implementation should
   handle keys and queries of shape (batch_size, ..., seq_len, d_k) and values of shape
   (batch_size, ..., seq_len, d_v), where ... represents any number of other batch-like
   dimensions (if provided). The implementation should return an output with the shape
   (batch_size, ..., seq_len, d_v). See Section 3.2 for a discussion on batch-like dimensions.

   Your implementation should also support an optional user-provided boolean mask of shape
   (seq_len, seq_len). The attention probabilities of positions with a mask value of True should
   collectively sum to 1, and the attention probabilities of positions with a mask value of False
   should be zero.

    To test your implementation against our provided tests, you will need to implement the test
    adapter at [adapters.run_scaled_dot_product_attention] . uv run pytest -k
    test_scaled_dot_product_attention tests your implementation on third-order input tensors, while
    uv run pytest -k test_4d_scaled_dot_product_attention tests your implementation on fourth-
    order input tensors.

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

正在加载本章讨论…

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

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