多头子空间:为什么以及如何分割 d_model
助教辅助工程检查
前置要求
第 43-44 天的缩放点积注意力与因果掩码机制。
学习目标
阐明多头注意力的表征必要性,形式化线性投影 W^Q, W^K, W^V, W^O,并推导微型模型与标准 GPT 规模的参数总账。
操作指引
必做任务:解释为什么单头注意力会将多种截然不同的关联(如句法主谓依存与长程语义共指)压缩为单一的加权平均。形式化 MultiHead(Q,K,V) = Concat(head_1, ..., head_h) W^O,其中每个 head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V)。设 d_model = 4, h = 2,因此 d_k = d_v = 2。推导参数总账:W^Q, W^K, W^V, W^O 均为 (4, 4) 矩阵,各含 16 个参数(无偏置共 64 参数,含偏置共 80 参数)。计算 GPT-2 Small 的参数量:d_model = 768, h = 12, d_k = 64(权重 4 * 768*768 = 2,359,296,偏置 4*768 = 3,072,总计 2,362,368)。
自主演练与记录
1. 为什么单个注意力头无法在关注相邻词元的同时关注远距离句法依存?
2. 写出 d_model = 4, h = 2 在含偏置和不含偏置情况下的精确参数总账。
3. 计算 GPT-2 Small 注意力层的参数总账(d_model = 768, h = 12)。
单个头对每对词元只能输出一个标量相关度,多头机制则提供 h 个独立的标量路由权重,使模型在不同特征子空间中并行关注不同模式。
单头注意力对每个位置的值向量只能生成单一的凸组合;若其权重被局部位置占满,便无法兼顾长程语法关联。对于 d_model=4, h=2:4 个 (4,4) 矩阵共 64 个权重;加偏置(+16)共 80 个参数。对于 GPT-2 Small:W^Q, W^K, W^V, W^O 为 4 个 (768,768) 矩阵 = 4 * 589,824 = 2,359,296 个权重;偏置为 4 * 768 = 3,072;总注意力参数量为 2,362,368。
准确阐述多头子空间路由的表征意义,并无误推导出微型模型与 GPT-2 规模的完整参数台账。
权威源资源与权利证明
Attention Is All You Need
对应章节 / 时间戳: Section 3.2.2: Multi-Head Attention architecture, linear projections, and parameter equations
验证版本与日期: 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.
Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.
The Annotated Transformer
对应章节 / 时间戳: MultiHeadedAttention module implementation: linear projections and subspace splitting
验证版本与日期: 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)
Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.
Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.
The original primary paper; Annotated Transformer annotates it directly.