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

因果多头自注意力

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

3.4.5 因果多头自注意力#

本节实现 Vaswani 等人 [8] 第 3.2.2 节的多头自注意力。多头注意力定义为:

MultiHead⁡(Q,K,V)=Concat⁡(head1,…,headh)(12) \operatorname{MultiHead}(Q,K,V)= \operatorname{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_h) \tag{12}
headi=Attention⁡(Qi,Ki,Vi)(13) \mathrm{head}_i=\operatorname{Attention}(Q_i,K_i,V_i) \tag{13}

Qi,Ki,ViQ_i,K_i,V_i 分别是 Q、K、V 的嵌入维上,第 ii 个大小为 dkd_k 或 dvd_v 的切片,i∈{1,…,h}i\in\{1,\ldots,h\}。Attention 就是第 3.4.4 节的缩放点积注意力。

由此得到多头自注意力:

MultiHeadSelfAttention⁡(x)=WOMultiHead⁡(WQx,WKx,WVx)(14) \operatorname{MultiHeadSelfAttention}(x)= W_O\operatorname{MultiHead}(W_Qx,W_Kx,W_Vx) \tag{14}

可学习参数为:

参数 形状
WQW_Q Rhdk×dmodel\mathbb{R}^{hd_k\times d_{\mathrm{model}}}
WKW_K Rhdk×dmodel\mathbb{R}^{hd_k\times d_{\mathrm{model}}}
WVW_V Rhdv×dmodel\mathbb{R}^{hd_v\times d_{\mathrm{model}}}
WOW_O Rdmodel×hdv\mathbb{R}^{d_{\mathrm{model}}\times hd_v}

因为 Q、K、V 要按头切片,可以把这些权重理解为沿输出维分别属于各个头。实现完成后,键、值和查询投影应总共使用三次矩阵乘法。原文脚注提供的进阶目标是将三种投影合成一个权重矩阵,只用一次矩阵乘法。

因果掩码#

模型不能看到序列中的未来 token。给定 t1,…,tnt_1,\ldots,t_n,计算前缀 t1,…,tit_1,\ldots,t_i 的下一 token 预测时,不能访问位置 i+1i+1 到 nn:推理时这些 token 尚不存在;训练时访问它们则泄露答案,让语言模型预训练目标失去意义。

朴素方法是针对 nn 个不同前缀运行 nn 次多头注意力。更高效的方法是使用因果注意力掩码,让位置 ii 只能关注 j≤ij\le i 的位置。

原文允许使用 torch.triu 或广播索引比较构造掩码,并利用上一节已支持掩码的注意力实现。

应用 RoPE#

RoPE 应用于查询和键,不应用于值。多头注意力中,各个头独立计算,因此头维度应作为批次维处理。各头共享同一个 RoPE 函数;查询和键分别按各自 token position 旋转,使点积结果体现相对位置。

练习 multihead_self_attention5 分

实现因果多头自注意力

交付物: 将因果多头自注意力实现为 torch.nn.Module,至少接收:

  • d_model: int:Transformer 块的输入维数。
  • num_heads: int:注意力头数。

遵循 [8],取 dk=dv=dmodel/hd_k=d_v=d_{\mathrm{model}}/h。

实现 adapters.run_multihead_self_attention,运行 uv run pytest -k test_multihead_self_attention。

一起把这一章读得更好

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

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

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

3.4.5 Causal Multi-Head Self-Attention
We will implement multi-head self-attention as described in section 3.2.2 of A. Vaswani et al. [8]. Recall
that, mathematically, the operation of applying multi-head attention is defined as follows:
                                   MultiHead(𝑄, 𝐾, 𝑉 ) = Concat(head1 , …, headℎ )                                           (12)

                                            for head𝑖 = Attention(𝑄𝑖 , 𝐾𝑖 , 𝑉𝑖 )                                             (13)

with 𝑄𝑖 , 𝐾𝑖 , 𝑉𝑖 being slice number 𝑖 ∈ {1, …, ℎ} of size 𝑑𝑘 or 𝑑𝑣 of the embedding dimension for 𝑄, 𝐾, and
𝑉 respectively. With Attention being the scaled dot-product attention operation defined in Section 3.4.4.
From this we can form the multi-head self-attention operation:

                          MultiHeadSelfAttention(𝑥) = 𝑊𝑂 MultiHead(𝑊𝑄 𝑥, 𝑊𝐾 𝑥, 𝑊𝑉 𝑥)                                         (14)

Here, the learnable parameters are 𝑊𝑄 ∈ ℝℎ𝑑𝑘 ×𝑑model , 𝑊𝐾 ∈ ℝℎ𝑑𝑘 ×𝑑model , 𝑊𝑉 ∈ ℝℎ𝑑𝑣 ×𝑑model , and 𝑊𝑂 ∈
ℝ𝑑model ×ℎ𝑑𝑣 . Since the 𝑄s, 𝐾s, and 𝑉 s are sliced in the multi-head attention operation, we can think of
𝑊𝑄 , 𝑊𝐾 and 𝑊𝑉 as being separated for each head along the output dimension. When you have this
working, you should be computing the key, value, and query projections in a total of three matrix
multiplies.5

Causal masking
Your implementation should prevent the model from attending to future tokens in the sequence. In other
words, if the model is given a token sequence 𝑡1 , …, 𝑡𝑛 , and we want to calculate the next-word predictions
for the prefix 𝑡1 , …, 𝑡𝑖 (where 𝑖 < 𝑛), the model should not be able to access (attend to) the token
representations at positions 𝑡𝑖+1 , …, 𝑡𝑛 since it will not have access to these tokens when generating text
during inference (and these future tokens leak information about the identity of the true next word,
trivializing the language modeling pre-training objective). For an input token sequence 𝑡1 , …, 𝑡𝑛 we can
naively prevent access to future tokens by running multi-head self-attention 𝑛 times (for the 𝑛 unique
prefixes in the sequence). Instead, we’ll use causal attention masking, which allows token 𝑖 to attend to all
positions 𝑗 ≤ 𝑖 in the sequence. You can use torch.triu or a broadcasted index comparison to construct
this mask, and you should take advantage of the fact that your scaled dot-product attention
implementation from Section 3.4.4 already supports attention masking.

Applying RoPE
RoPE should be applied to the query and key vectors, but not the value vectors. Also, the head
dimension should be handled as a batch dimension, because in multi-head attention, attention is being
applied independently for each head. This means that precisely the same RoPE rotation should be
applied to the query and key vectors for each head.


 Problem (multihead_self_attention): Implement causal multi-head self-attention (5 points)



   5
     As a stretch goal, try combining the key, query, and value projections into a single weight matrix so you only need a
single matrix multiply.

   Deliverable: Implement causal multi-head self-attention as a torch.nn.Module. Your
   implementation 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.
                                                   𝑑
   Following A. Vaswani et al. [8], set 𝑑𝑘 = 𝑑𝑣 = model
                                                   ℎ . To test your implementation against our
   provided tests, implement the test adapter at [adapters.run_multihead_self_attention] . Then,
   run uv run pytest -k test_multihead_self_attention to test your implementation.

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

正在加载本章讨论…

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

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