43 / 90

第 43 天:缩放点积注意力与查询-键-值投影

将注意力机制形式化为用查询匹配键以加权聚合值。推导 R^{d_k} 中点积的方差,证明为什么 1/sqrt(d_k) 缩放因子能防止 Softmax 梯度消失,并通过手算与代码完整追踪 (T, d_k) 形状的分数矩阵。

模型与训练 480 分钟主动学习(8 小时专注研读)
01 120 分钟

查询、键与值:向量角色与注意力公式形式化

助教辅助工程检查

前置要求

第 41-42 天的前向传播、矩阵乘法与逐行 Softmax 机制。

学习目标

将注意力机制分解为用查询检索键以聚合值的路由过程,推导张量维度,并完成原始点积分数矩阵的数值计算。

操作指引

学习来源:在本活动现有的阅读与练习时段内,参考 Stanford CS224N: Natural Language Processing with Deep Learning 的 Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides,用自己的话解释一处与本地任务的联系。保留现有练习与验收检查;若外部资料无法访问,使用课程自写的解释。必做任务:形式化缩放点积注意力公式 Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V。给定序列长度 T=3、键维度 d_k=4、值维度 d_v=2。设定 Q 各行为 q_0=[2.0, 0.0, 2.0, 0.0], q_1=[0.0, 2.0, 0.0, 2.0], q_2=[1.0, 1.0, 1.0, 1.0];K 各行为 k_0=[1.0, 0.0, 1.0, 0.0], k_1=[0.0, 2.0, 0.0, 1.0], k_2=[2.0, 1.0, 0.0, 1.0];V 各行为 v_0=[1.0, 0.0], v_1=[0.0, 2.0], v_2=[1.0, 1.0]。逐步手算原始分数矩阵 S_raw = Q K^T。阐述查询(当前位置在找什么)、键(当前位置提供什么信息)与值(传输的具体表征内容)的几何与物理意义。

自主演练与记录

1. 计算 S_raw = Q K^T 的 3x3 矩阵全部数值。
2. 明确给出 Q、K、V、Q K^T 以及最终输出矩阵的张量形状。
3. 用两句话说明为什么注意力是一种数据驱动的关联检索,而非静态固定权重层?

独立掌握标准

准确列出矩阵乘法各步骤,得到完全正确的 3x3 S_raw 矩阵及各张量形状。

权威源资源与权利证明

linking Stanford University copyright; no course-wide open reuse license verified linking only; no reproduction

Stanford CS224N: Natural Language Processing with Deep Learning

作者 / 机构: Stanford University CS224N staff | 原始出处链接 ↗

对应章节 / 时间戳: Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides

验证版本与日期: Public edition checked 2026-11-01; moving pages may change

入选理由:

Selected attention/Transformer lecture slides provide a coherent teaching check on Q/K/V and architecture; original papers remain definition references and local code exercises remain required.

来源前置条件:

Linear algebra, gradients, basic neural language models and PyTorch.

安全回退方案(离线弹性):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

对比候选资源与选型分析 (2)
The Annotated Transformer ↗ compared_alternative [MIT]

Runnable code commentary remains the implementation spine; its sublayer convention must not be mistaken for the original paper.

The Illustrated Transformer ↗ compared_alternative [Copyright Jay Alammar; edition-specific reuse terms unverified]

Concise diagrams are useful, but provide neither the wider lecture sequence nor checked implementation exercises.

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

作者 / 机构: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出处链接 ↗

对应章节 / 时间戳: Section 3.2.1: Scaled Dot-Product Attention equation and query/key/value matrix definitions

验证版本与日期: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

入选理由:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

来源前置条件:

Linear algebra, matrix multiplication, softmax probability distributions

安全回退方案(离线弹性):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

对比候选资源与选型分析 (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 时间戳: model.py: CausalSelfAttention forward pass query/key/value projection extraction

验证版本与日期: GitHub master commit (Verified: 2026-10-30)

入选理由:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

来源前置条件:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

安全回退方案(离线弹性):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

对比候选资源与选型分析 (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

02 120 分钟

缩放因子 sqrt(d_k) 与注意力分数矩阵 Softmax

独立掌握检查

前置要求

完成第 43 天活动 1。

学习目标

对分数矩阵应用 1/sqrt(d_k) 缩放因子,计算数值稳定的逐行 Softmax 概率分布,并完成值的加权聚合输出。

操作指引

必做任务:当 d_k = 4 时,缩放因子为 sqrt(4) = 2.0。将 S_raw 各元素除以 2.0 获得缩放矩阵 S = S_raw / 2.0。随后采用最大值平移法逐行计算 Softmax:第 0 行缩放值为 [2.0, 0.0, 2.0];第 1 行为 [0.0, 3.0, 2.0];第 2 行为 [1.0, 1.5, 2.0]。求出注意力权重矩阵 A = softmax(S),并计算最终输出 Out = A V。验证 A 的每一行求和严格为 1.0。

自主演练与记录

1. 写出缩放后的分数矩阵 S = S_raw / 2.0。
2. 计算精确到小数点后 6 位的 Softmax 注意力矩阵 A。
3. 计算所有 3 个位置的输出表征向量 Out = A V。

独立掌握标准

独立推导 S 矩阵,求得与参考值在 4 位小数内一致的注意力概率并计算出正确的 Out。

权威源资源与权利证明

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

作者 / 机构: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出处链接 ↗

对应章节 / 时间戳: Section 3.2.1: Mathematical justification for scaling factor 1/sqrt(d_k) to prevent vanishing softmax gradients

验证版本与日期: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

入选理由:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

来源前置条件:

Linear algebra, matrix multiplication, softmax probability distributions

安全回退方案(离线弹性):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

对比候选资源与选型分析 (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

The Annotated Transformer

作者 / 机构: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | 原始出处链接 ↗

对应章节 / 时间戳: Scaled Dot Product Attention code cell and attention matrix visualization

验证版本与日期: Updated 2022 edition (Verified: 2026-10-30)

入选理由:

Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

来源前置条件:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

安全回退方案(离线弹性):

The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

对比候选资源与选型分析 (3)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

03 120 分钟

方差缩放推导与梯度饱和反例剖析

助教辅助工程检查

前置要求

完成第 43 天活动 2;具备初等概率统计与微积分基础。

学习目标

在数学上证明两个 d_k 维独立随机向量的点积方差为 d_k,并定量演示未缩放时 Softmax 梯度严重消失的数值反例。

操作指引

必做任务:设 q 与 k 的各分量 q_i, k_i 相互独立,且 E[q_i] = E[k_i] = 0, Var(q_i) = Var(k_i) = 1。推导 E[q . k] = 0 与 Var(q . k) = d_k。证明 Var((q . k) / sqrt(d_k)) = 1。随后分析反例:当 d_k = 64 时,sqrt(d_k) = 8。若不缩放,点积标准差高达 8,极易产生 +16 和 -16 的对数几率。计算 softmax([16, 0, -16]) 的概率输出,并依据 Softmax 导数公式 dp_i / dz_j = p_i (delta_ij - p_j) 说明梯度为什么几乎为 0。

自主演练与记录

1. 利用独立零均值变量性质 Var(XY) = E[X^2]E[Y^2] 给出完整的方差推导步骤。
2. 计算 softmax([16, 0, -16]) 并在数值上给出其局域梯度幅度。
3. 说明为什么未缩放点积会导致深层 Transformer 在训练初期即陷入优化停滞?

独立掌握标准

完整书写代数推导过程并给出数值反例的具体计算结果。

权威源资源与权利证明

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

作者 / 机构: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出处链接 ↗

对应章节 / 时间戳: Section 3.2.1 footnote and variance derivation for inner products of unit-variance components

验证版本与日期: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

入选理由:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

来源前置条件:

Linear algebra, matrix multiplication, softmax probability distributions

安全回退方案(离线弹性):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

对比候选资源与选型分析 (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 时间戳: model.py: scaling by 1.0 / math.sqrt(k.size(-1)) in attention calculation

验证版本与日期: GitHub master commit (Verified: 2026-10-30)

入选理由:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

来源前置条件:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

安全回退方案(离线弹性):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

对比候选资源与选型分析 (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

04 120 分钟

独立掌握检查:点积注意力运算与张量形状

独立掌握检查

前置要求

活动 43-01 至 43-03。

学习目标

在声明无 AI 辅助的条件下,独立完成全新配置的缩放点积注意力手算、方差推导与张量形状契约检验。

操作指引

必做任务:闭卷独立作答,不依赖 AI 助手与现成计算器。面对新配置 T=2, d_k=4, d_v=2:Q 矩阵包含行 [0.0, 2.0, 0.0, 2.0], [2.0, 0.0, 2.0, 0.0];K 矩阵包含行 [0.0, 2.0, 0.0, 2.0], [1.0, 0.0, 1.0, 0.0];V 矩阵包含行 [2.0, 1.0], [0.0, 3.0]。计算原始点积矩阵 S_raw,以 sqrt(4)=2 进行缩放,求出精确的 Softmax 矩阵与最终输出表征。完成客观测试题。

自主演练与记录

1. 计算 S_raw 与缩放后的 S = S_raw / 2.0。
2. 计算精确的 2x2 Softmax 权重矩阵 A。
3. 计算 2x2 输出表征矩阵 Out = A V。
4. 完成 3 道单项选择题。

客观理解度测试:缩放点积注意力机制

请回答以下诊断题目检验掌握情况。提交前请诚实声明你的辅助条件。

声明辅助条件

说明:无 AI 辅助属于诚实声明条件,非平台监控或强制检测手段。

1.

将点积结果 Q K^T 除以 sqrt(d_k) 的核心数学动机是什么?

2.

对于序列长度 T=3、键维度 d_k=4、值维度 d_v=2 的输入,注意力分数矩阵 S = (Q K^T) / sqrt(d_k) 的张量形状是什么?

3.

若向量 q, k in R^{d_k} 的各分量相互独立且服从零均值、单位方差分布,其未缩放点积 q . k 的方差是多少?

作答应证与历史记录

    独立掌握标准

    独立推导出 S、A、Out 矩阵全套数值,且客观测试题获得 100% 满分。

    权威源资源与权利证明

    linking arXiv.org perpetual non-exclusive license / Open Access

    Attention Is All You Need

    作者 / 机构: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出处链接 ↗

    对应章节 / 时间戳: Section 3.2.1: Attention equation verification and tensor shape dimensions

    验证版本与日期: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

    入选理由:

    The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

    来源前置条件:

    Linear algebra, matrix multiplication, softmax probability distributions

    安全回退方案(离线弹性):

    Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

    对比候选资源与选型分析 (3)

    Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

    Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

    Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

    Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

    linking MIT

    The Annotated Transformer

    作者 / 机构: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | 原始出处链接 ↗

    对应章节 / 时间戳: Attention function test assertions and shape contracts

    验证版本与日期: Updated 2022 edition (Verified: 2026-10-30)

    入选理由:

    Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

    来源前置条件:

    Intermediate Python, PyTorch broadcasting and tensor slicing semantics

    安全回退方案(离线弹性):

    The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

    对比候选资源与选型分析 (3)
    Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

    Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

    Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

    Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

    Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

    The original primary paper; Annotated Transformer annotates it directly.