47 / 90

第 47 日:前馈网络 (FFN)、SwiGLU 与多层 Block 堆叠

构建按位置前馈网络,追踪中间隐藏维度的扩张与投影,并以严格的张量不变量堆叠多个 Transformer 模块。

模型、预训练与微调 (LoRA) 480 分钟专注学习(8 小时)
01 120 分钟

按位置前馈网络 (FFN) 架构

Agent 辅助工程分析

前置要求

第 46 日 Transformer Block 与第 41 日 MLP 基础知识。

学习目标

解释 FFN 作为词元键值记忆库的角色,及其典型的 4 倍隐层扩展维度 d_ff = 4 * d_model。

操作指引

1. 写出带全部形状的 FFN:x 为 (T, d_model),W1 为 (d_model, d_ff),b1 为 (d_ff),W2 为 (d_ff, d_model),b2 为 (d_model),因此 FFN(x) = act(x W1 + b1) W2 + b2 仍为 (T, d_model)。
2. 解释"按位置":同一组 W1, b1, W2, b2 分别作用于每一行 x_t;词元 s 的值不会进入词元 t 的 FFN 输出。跨词元的混合由注意力负责。
3. 比较激活函数:ReLU max(0, z) 有硬性的零;GELU z * Phi(z) 平滑,允许小的负值通过;SwiGLU 使用门控 (Swish(x W) ⊙ (x V)) W2,因此需要三个矩阵而不是两个。
4. 对 d_model = 64、d_ff = 256 计算参数量,先不含偏置,再含偏置。
5. 用 d_ff' ≈ (2/3) d_ff 并取整,求出使 SwiGLU 参数量大致相同的隐藏宽度。

时间安排(120 分钟):阅读 30 + 练习 60 + 检查 30。 阅读:Vaswani et al. 第 3.3 节(按位置前馈网络)和 nanoGPT model.py 中的 MLP 类。练习:第 1-5 项。检查:独立完成掌握题中的两种参数量计算。

自主演练与记录

1. 写出标准两层 FFN 数学公式,并标出每个张量的形状。
2. 为何 FFN 被称为 '按位置 (position-wise)'?
3. 计算无偏置下 W1 (64x256) 与 W2 (256x64) 的总参数量。
4. 加上偏置 b1 和 b2,给出新的总数。
5. SwiGLU 使用三个矩阵(d_model x d_ff' 的 W 和 V,以及 d_ff' x d_model 的 W2)。选择 d_ff' 使其参数量接近第 3 项,并给出该数量。

独立掌握标准

阐明按位置特性并准确推导出 4 倍扩展下的参数账目。

权威源资源与权利证明

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.3 Position-wise Feed-Forward Networks

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

入选理由:

Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.

来源前置条件:

Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.

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

All mathematical formulas and structural definitions are self-contained in the lesson text.

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.

linking MIT

nanoGPT: model.py architecture implementation

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

对应章节 / 时间戳: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

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

入选理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

来源前置条件:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

对比候选资源与选型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

02 120 分钟

手算 FFN 前向传播与隐藏层扩张

Agent 辅助工程分析

前置要求

活动 01 及第 22 日矩阵乘法。

学习目标

手算一个输入向量 x = [1.0, 2.0] 通过 d_model=2 扩展到 d_ff=3 再投影回 d_model=2 的完整 FFN 前向传播。

操作指引

1. 先写形状:x 为 1x2,W1 为 2x3,所以 z = x W1 为 1x3;h 为 1x3;W2 为 3x2,所以 y 为 1x2。
2. 把 z 的每个分量算成 x 与 W1 某一列的点积,写出每个乘积。
3. 逐分量应用 ReLU,记下哪些分量(如果有)变为零。
4. 把 y 算成 h 与 W2 各列的点积。
5. 加上残差:在模块中子层输出会被加回,所以模块输出是 x + y。
6. 对变式 x = [2, -1] 重做整个前向过程,比较激活的隐藏单元数量。

时间安排(120 分钟):阅读 20 + 练习 70 + 检查 30。 阅读:The Annotated Transformer 中的按位置 FFN 和 nanoGPT 的 MLP forward。练习:手算第 1-5 项。检查:在白纸上重做变式,并用计算器或 NumPy 验证一个分量。

自主演练与记录

1. 计算未激活前向得分 z = x W1。
2. 应用 ReLU 得到 h。
3. 计算最终投影输出 y = h W2。
4. 加上残差连接,给出 x + y。
5. 对 x = [2, -1] 重复第 1-3 项,并说明 ReLU 关闭了哪些隐藏单元。

独立掌握标准

毫无差错地完成扩张与投影矩阵乘法的手算推导。

权威源资源与权利证明

linking MIT

The Annotated Transformer

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

对应章节 / 时间戳: Position-wise Feed-Forward Networks (class PositionwiseFeedForward)

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

入选理由:

Clear reference implementation of Transformer modules, residual connections, and layer normalization.

来源前置条件:

PyTorch tensor operations and attention theory.

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

All block assembly and normalization logic are provided in runnable local Python snippets.

对比候选资源与选型分析 (2)
HuggingFace Transformers library source ↗ compared_alternative [Apache 2.0]

Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.

PyTorch nn.Transformer documentation ↗ compared_alternative [Modified BSD]

Standard library implementation, but internal C++ bindings obscure the first-principles data flow.

linking MIT

nanoGPT: model.py architecture implementation

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

对应章节 / 时间戳: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

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

入选理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

来源前置条件:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

对比候选资源与选型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

03 120 分钟

堆叠 Transformer 模块与张量不变量

Agent 辅助工程分析

前置要求

活动 01 与 02。

学习目标

追踪一批词元张量 (B=2, T=4, d=64) 连续通过 2 个 Transformer Block,断言张量形状与数据类型的不变性。

操作指引

1. 把一个 Pre-LN 模块写成两个残差子层:x = x + Attn(LN1(x)),然后 x = x + FFN(LN2(x))。
2. 固定示例:B = 2,T = 4,d_model = 64,n_heads = 4(head_dim = 16),d_ff = 256。
3. 追踪注意力内部(每个头的 Q, K, V、得分矩阵、合并后的输出)和 FFN 内部(隐藏层)的形状。
4. 标出形状不同于 (B, T, d_model) 的每个位置,并检查它在每次残差相加之前回到 (B, T, d_model)。
5. 也检查 dtype:模块必须返回与输入相同的 dtype。
6. 解释为什么相同的模块接口允许堆叠 L 个模块,以及为什么残差相加需要形状一致。

时间安排(120 分钟):阅读 25 + 练习 60 + 检查 35。 阅读:Vaswani et al. 第 3.1 节(编码器与解码器堆叠)和 The Annotated Transformer 中 EncoderLayer/SublayerConnection 的代码。练习:第 1-4 项及完整形状表。检查:不看笔记解释形状契约,再对照。

自主演练与记录

1. 写出 2 层 Pre-LN Transformer 的子层执行序列。
2. 说明 Block 1 与 Block 2 之间所有边界处的张量形状。
3. 为何各层保持统一维度是残差直接相加的前提?
4. 假设有 4 个头且 d_ff = 256。给出每个头的 Q、注意力得分和 FFN 隐藏层的形状。

独立掌握标准

清晰掌握模块化契约与形状不变性原理。

权威源资源与权利证明

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.1 Encoder and Decoder Stacks (N = 6 identical layers, d_model = 512)

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

入选理由:

Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.

来源前置条件:

Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.

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

All mathematical formulas and structural definitions are self-contained in the lesson text.

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.

linking MIT

The Annotated Transformer

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

对应章节 / 时间戳: Encoder and Decoder Stacks

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

入选理由:

Clear reference implementation of Transformer modules, residual connections, and layer normalization.

来源前置条件:

PyTorch tensor operations and attention theory.

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

All block assembly and normalization logic are provided in runnable local Python snippets.

对比候选资源与选型分析 (2)
HuggingFace Transformers library source ↗ compared_alternative [Apache 2.0]

Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.

PyTorch nn.Transformer documentation ↗ compared_alternative [Modified BSD]

Standard library implementation, but internal C++ bindings obscure the first-principles data flow.

04 120 分钟

Transformer 模块参数量与计算复杂度精算

独立完成核心推导

前置要求

完成活动 01 至 03。

学习目标

精确推导一个完整 Transformer Block(注意力 + FFN)的参数量预算与比例关系。

操作指引

1. 使用 GPT-2 small 的模块:d_model = 768,n_heads = 12(head_dim = 64),d_ff = 3072。
2. 计算注意力权重(Q, K, V, O:4 * 768 * 768)和 FFN 权重(2 * 768 * 3072),再求比例。
3. 加上偏置(每个注意力投影 768,FFN 上投影 3072,下投影 768)和两个 LayerNorm(增益与偏置,各 2 * 768)。
4. 扩展到整个模型:12 个模块、词元嵌入 50257 x 768、位置嵌入 1024 x 768、最终 LayerNorm,以及权重绑定的 LM 头(无额外参数)。
5. 估计每个词元的前向 FLOPs:矩阵乘法中每个权重约 2 FLOPs,另加注意力得分与加权求和的乘积,每层约 4 * T * d_model。
6. 在 T = 1024 下,比较 FFN 与注意力在参数量和 FLOPs 中各自的占比。

时间安排(120 分钟):阅读 25 + 练习 60 + 检查 35。 阅读:nanoGPT model.py(Block、CausalSelfAttention、MLP、get_num_params)和 Vaswani et al. 表 1。练习:第 1-6 项。检查:独立重算 124M 总数,并与 get_num_params 对照。

自主演练与记录

1. 计算注意力子层的总参数量(无偏置)。
2. 计算 FFN 子层的总参数量(无偏置)。
3. FFN 与注意力层在单个 Block 中的参数占比分别是多少?
4. 加上偏置和两个 LayerNorm,得到整个模块的参数量。
5. 对于 12 个模块、词表 50257、上下文 1024、LM 头权重绑定的模型,计算总参数量。
6. 估计 T = 1024 时一个模块每个词元的前向 FLOPs。

独立掌握标准

准确推导参数账目,并指认 FFN 与注意力层 2:1 的黄金参数比例。

权威源资源与权利证明

linking MIT

nanoGPT: model.py architecture implementation

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

对应章节 / 时间戳: model.py: GPT.get_num_params and GPT.estimate_mfu

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

入选理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

来源前置条件:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

对比候选资源与选型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

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.3 Position-wise Feed-Forward Networks and Section 4 Why Self-Attention (Table 1)

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

入选理由:

Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.

来源前置条件:

Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.

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

All mathematical formulas and structural definitions are self-contained in the lesson text.

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.