44 / 90

第 44 天:自回归因果掩码与严格不变性

在生成式语言模型中严格实施自回归约束。构建下三角因果掩码,证明 Softmax 将 -inf 精确映射为零概率,并通过实验验证未来词元扰动对历史表征的影响精确为零。

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

自回归约束与下三角因果掩码构建

助教辅助工程检查

前置要求

第 43 天的注意力机制与缩放除法推导。

学习目标

阐明解码器语言模型的自回归因式分解约束,构建下三角因果掩码矩阵 M,并推导掩码后的分数矩阵 S_masked = S + M。

操作指引

必做任务:解释为什么因果解码器必须满足 P(x_1, ..., x_T) = prod_{t=1}^T P(x_t | x_{ t,导致模型在训练时发生“作弊泄露”。定义加性因果掩码 M in R^{T x T},满足当 j <= i 时 M_{i,j} = 0,当 j > i 时 M_{i,j} = -inf。写出序列长度 T=3 时的具体矩阵 M。使用第 43 天缩放后的分数矩阵 S = [[2.0, 0.0, 2.0], [0.0, 3.0, 2.0], [1.0, 1.5, 2.0]],计算掩码后的分数矩阵 S_masked = S + M。

自主演练与记录

1. 写出 3x3 因果掩码矩阵 M 的完整元素。
2. 写出加性掩码后的分数矩阵 S_masked = S + M。
3. 如果代码中错误地将主对角线上方设为 0、下方设为 -inf,会产生什么后果?

独立掌握标准

准确写出下三角因果掩码 M 并完成 3x3 掩码分数矩阵 S_masked 的推导。

权威源资源与权利证明

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.3: Masked Multi-Head Attention in the decoder preventing leftward information flow

验证版本与日期: 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) | 原始出处链接 ↗

对应章节 / 时间戳: subsequent_mask implementation using torch.triu and triangular boolean masking

验证版本与日期: 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.

02 120 分钟

因果掩码下的 Softmax:逐步矩阵精确推导

独立掌握检查

前置要求

完成第 44 天活动 1。

学习目标

在掩码分数矩阵上利用最大值平移计算逐行 Softmax,求出因果注意力矩阵 A_causal,并计算因果加权输出。

操作指引

必做任务:对 S_masked = [[2.0, -inf, -inf], [0.0, 3.0, -inf], [1.0, 1.5, 2.0]] 执行逐行 Softmax 计算。第 0 行:有限项最大值为 2.0。exp([2.0-2.0, -inf, -inf]) = [1.0, 0.0, 0.0],归一化得 A_causal[0, :] = [1.0, 0.0, 0.0]。第 1 行:最大值为 3.0。exp([-3.0, 0.0, -inf]) = [exp(-3), 1.0, 0.0] ~= [0.049787, 1.0, 0.0],和为 1.049787。A_causal[1, :] = [0.047426, 0.952574, 0.0]。第 2 行无掩码,得 [0.186324, 0.307196, 0.506480]。使用第 43 天的 V = [[1,0], [0,2], [1,1]] 计算因果输出 Out_causal = A_causal V。

自主演练与记录

1. 计算精确到小数点后 6 位的 A_causal 各行注意力权重。
2. 计算全部 3 行的因果输出 Out_causal = A_causal V。
3. 对比第 43 天未掩码的 Out[0] 与本节 Out_causal[0],阐述其本质差异。

独立掌握标准

精确计算 A_causal 和 Out_causal 各元素,数值与参考值在 4 位小数内一致。

权威源资源与权利证明

linking MIT

The Annotated Transformer

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

对应章节 / 时间戳: Attention masking implementation: masked_fill with -1e9 before softmax

验证版本与日期: 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.

linking MIT

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

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

对应章节 / 时间戳: model.py: att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float("-inf"))

验证版本与日期: 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.

03 120 分钟

因果不变性扰动实验与代数证明

助教辅助工程检查

前置要求

完成第 44 天活动 2。

学习目标

通过数值实验与代数推导,严格验证扰动未来词元时历史位置的注意力权重和输出表征精确保持不变。

操作指引

必做任务:对序列执行严格扰动实验。将未来词元(t=2)替换为任意极端数值:q_2' = [99.0, -42.0, 13.0, 7.0], k_2' = [-50.0, 12.0, 34.0, -8.0], v_2' = [100.0, -200.0]。重新计算 S_masked、A_causal 和 Out_causal。证明 diff(A_causal[0], A_causal_pert[0]) = 0.0,diff(A_causal[1], A_causal_pert[1]) = 0.0,diff(Out[0], Out_pert[0]) = 0.0,以及 diff(Out[1], Out_pert[1]) = 0.0。将此特性与无掩码层(所有历史行均被污染)进行深入对比。

自主演练与记录

1. 从 Softmax 分子分母公式证明为什么 A_causal 的第 i 行绝不依赖任何 j > i 的 k_j 或 v_j。
2. 给出对词元 2 扰动前后,第 0、1、2 行表征差异的最大绝对值。
3. 说明因果不变性如何保障大模型自回归生成中 KV-Cache(键值缓存)机制的正确性?

独立掌握标准

给出严谨的未来独立性代数证明,并在数值上验证历史位置差异精确为 0.0。

权威源资源与权利证明

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.3: Autoregressive self-attention property ensuring causal factorization

验证版本与日期: 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 buffer verification ensuring past tokens remain strictly invariant

验证版本与日期: 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 分钟

独立掌握检查:因果泄露、掩码缺陷与不变性断言

独立掌握检查

前置要求

活动 44-01 至 44-03。

学习目标

在声明无 AI 辅助条件下,独立识别掩码实现缺陷,推导 2 词元序列的因果注意力,并给出严谨的不变性断言。

操作指引

必做任务:闭卷独立作答。给定 T=2、缩放分数 S = [[3.0, 1.0], [2.0, 4.0]] 与 V = [[1.0, 2.0], [3.0, 0.0]]:1. 构建 2x2 因果掩码 M 并写出 S_masked。2. 计算精确的 2x2 因果注意力矩阵 A_causal。3. 计算 Out_causal。4. 若词元 1 被替换为任意新向量,证明 Out_causal[0] 的变化量。5. 完成客观选择题。

自主演练与记录

1. 写出 2x2 设置下的 S_masked。
2. 计算精确到 6 位小数的 A_causal。
3. 计算 Out_causal = A_causal V。
4. 指出若扰动词元 1,Out_causal[0] 的精确变化量。
5. 完成 3 道单项选择题。

客观理解度测试:因果掩码与严格不变性

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

声明辅助条件

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

1.

在自回归生成中,下三角因果掩码(Causal Mask)的核心操作目标是什么?

2.

在为注意力分数构建加性因果掩码时,必须为主对角线上方的上三角区域(j > i)赋予什么数值?

3.

若对长度为 3 的序列(t in {0, 1, 2})中的第 2 个词元进行任意数值扰动,在严格因果掩码下,位置 0 的注意力权重和输出表征会发生什么变化?

作答应证与历史记录

    独立掌握标准

    独立推导 2x2 因果注意力和输出,正确断言历史不变性,且客观测试获 100% 满分。

    权威源资源与权利证明

    linking MIT

    The Annotated Transformer

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

    对应章节 / 时间戳: subsequent_mask unit tests and triangular boundary checks

    验证版本与日期: 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.

    linking MIT

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

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

    对应章节 / 时间戳: model.py: causal mask shape registration and forward assertion

    验证版本与日期: 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.