49 / 90

第 49 天:第 7 周总复习:从注意力到 logits,以及预训练数据管线

回忆并串联第 43-48 天(注意力、掩码、多头、块结构、前向传播),再补上预训练循环唯一需要的新内容:自回归 (x, y) 批次。

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

新内容:自回归 (x, y) 批次与 get_batch

Agent 辅助工程分析

先修要求

第 1-3 天的分词、第 36 天的交叉熵、第 48 天的前向传播。

学习目标

从一维 token 数组构造因果输入-目标对,用 get_batch 采样批次,计算批次张量的大小,并用 ln(V) 核对第一个损失。

实验指南

这是今天唯一的新内容,其余时间复习第 7 周。解码器用位置 t 及之前的 token 预测 token t+1。上下文长度为 L 时,切出 L + 1 个 token 的窗口 chunk = tokens[i : i + L + 1],再令 x = chunk[:-1]、y = chunk[1:],两者形状都是 (L,)。一个批次把 B 个随机窗口堆叠成形状为 (B, T) 的 x 和 y。模型输出 logits 的形状是 (B, T, V),而 F.cross_entropy 需要 (N, V) 和 (N,),因此用 logits.view(-1, V) 和 y.view(-1) 展平。训练开始前所有 token 等概率,第一个损失应接近 ln(V)。

实战与预测记录

1. tokens = [502, 1204, 33, 991, 88, 412],L = 4,从下标 0 开始,写出 x 和 y。为什么窗口需要 L + 1 个 token?
2. 写出 get_batch(data, batch_size, block_size, device)。
3. B = 64、T = 1024 时,x 和 y 合计在 int64 下占多少字节?int32 呢?
4. 写出正确展平后的 cross_entropy 调用,并给出 V = 50,257 时第一个损失的期望值。
5. 如果 y = x(不移位)会怎样?

独立掌握标准

能推导移位后的 (x, y) 对,写出可运行的 get_batch,精确计算批次张量大小,并用 ln(V) 检查第一个损失。

权威来源与学术版权说明

linking MIT

nanoGPT: train.py pretraining loop

作者/提供方: Andrej Karpathy | 原始来源链接 ↗

对应章节/时间戳: train.py: get_batch(split): x = data[i:i+block_size], y = data[i+1:i+1+block_size]

核验版本与日期: Git master commit 71c3905 (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 46-48 Transformer model architecture.

安全降级(离线韧性):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

候选来源对比与遴选分析 (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者/提供方: Stanford University CS336 Staff | 原始来源链接 ↗

对应章节/时间戳: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

核验版本与日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

入选理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

先修背景:

Fluent Python, PyTorch, and linear algebra

安全降级(离线韧性):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

候选来源对比与遴选分析 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

02 120 分钟

复习练习:缩放、掩码与多头注意力(第 43-45 天)

独立完成核心推导

先修要求

第 43 天的缩放点积注意力、第 44 天的因果掩码、第 45 天的多头注意力。闭卷完成,只在对答案时打开第 43-45 天的笔记。

学习目标

手算还原一次因果注意力输出,并在不看笔记的情况下回忆第 43-45 天关于形状、参数和数值稳定性的要点。

实验指南

这是提取练习:先凭记忆作答,再核对。1) 按第 43-44 天的方法计算 S = Q K^T / sqrt(d_k),加上因果掩码(第 44 天),做带最大值平移的逐行 softmax(第 45 天),再乘以 V。2) 追踪第 45 天的多头形状:(B, T, d_model) -> (B, T, h, d_k) -> (B, h, T, d_k) -> 分数 (B, h, T, T) -> 再回到 (B, T, d_model)。3) 查资料前,先用一句话解释每个要点。

实战与预测记录

1. Q = [[1, 1], [0, 2]],K = [[1, 1], [2, 0]],V = [[1, 0], [0, 1]],d_k = 2。计算缩放后的分数、因果注意力权重和 Out。若没有掩码,Out[0] 是多少?
2. B = 2,T = 5,d_model = 12,h = 3。给出 d_k,以及拆分头之后的 Q、分数张量、拼接后输出的形状。
3. d_model = 12 时,W^Q、W^K、W^V、W^O 含偏置共有多少参数?不含偏置呢?
4. 凭记忆回答:为什么要除以 sqrt(d_k)(第 43 天)?为什么 exp(15) 在 float16 下会出错(第 45 天)?如果 token 1 改变,Out[0] 会怎样(第 44 天)?

独立掌握标准

不看笔记即可还原因果注意力输出、多头形状和参数量,并用自己的话解释 sqrt(d_k)、float16 和因果不变性。

权威来源与学术版权说明

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

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.

03 120 分钟

复习实践:块结构、参数台账与前向传播(第 46-48 天)

Agent 辅助工程分析

先修要求

第 46 天的 LayerNorm、RMSNorm 与残差;第 47 天的 FFN 与块参数统计;第 48 天的位置编码、权重共享与完整前向传播。

学习目标

把归一化、Pre-LN 块、FFN 和权重共享整合成一个小型 GPT 的参数台账和形状追踪。

实验指南

使用一个玩具 GPT:V = 100,上下文 16,d_model = 32,n_layer = 2,n_head = 4,d_ff = 4 * d_model,可学习的位置嵌入,带权重和偏置的 LayerNorm,无偏置的线性层,输出头权重共享。1) 按第 46 天的方法手算 LayerNorm 和 RMSNorm。2) 写出第 46 天的 Pre-LN 块公式和第 48 天的完整前向传播。3) 按第 47 天的方法逐行建立参数台账,再算出权重共享节省的参数(第 48 天)。

实战与预测记录

1. 对 x = [4, 0, -2, 2] 计算 LayerNorm(无 epsilon,增益 1,偏置 0)和 RMSNorm。
2. 写出一个块中 Pre-LN 残差的两行,并用一句话说明为什么 Pre-LN 比 Post-LN 训练更稳定。
3. 依次计算该 GPT 的参数量:每块、全部块、嵌入、最终 LayerNorm、总计。不共享权重的输出头会多出多少?
4. 每个块的矩阵权重中,FFN 占多少比例?
5. 对 B = 8、T = 16 追踪从 idx 到 logits 的形状,并指出采样下一个 token 用的切片。

独立掌握标准

能给出归一化数值、Pre-LN 公式、总计 28,608 的参数台账(并解释权重共享的差值),以及正确的端到端形状追踪。

权威来源与学术版权说明

linking arXiv non-exclusive license / Open Access

Root Mean Square Layer Normalization

作者/提供方: Biao Zhang, Rico Sennrich (University of Edinburgh) | 原始来源链接 ↗

对应章节/时间戳: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

核验版本与日期: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

入选理由:

Primary paper showing that mean-centering in LayerNorm can be discarded without performance loss, speeding up modern LLMs (LLaMA, Gemma).

先修背景:

Variance, standard deviation, and LayerNorm basics.

安全降级(离线韧性):

RMSNorm formulas and numerical comparisons are derived completely in the lesson.

候选来源对比与遴选分析 (2)
Ba et al. Layer Normalization (2016) ↗ compared_selected_for_day46 [Open Access]

Original LayerNorm formulation with mean-centering; RMSNorm is compared directly against it as an optimization.

Ioffe & Szegedy Batch Normalization (2015) ↗ compared_alternative [Open Access]

Batch-dependent statistics; unsuitable for autoregressive sequence modeling.

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 Model Architecture (3.1-3.5)

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

04 120 分钟

第 7 周测评:找出小型 GPT 中的四个 bug(第 43-49 天)

完全独立闭卷考核

先修要求

第 43-48 天以及第 49 天活动 1-3。闭卷,声明不使用 AI。

学习目标

独立找出、解释并修复四个各自违反第 7 周某条规则的预埋 bug,并预测它们在训练中的表现。

实验指南

不运行代码,先通读一遍。每个标记行都违反了第 7 周的一条规则:注意力缩放(第 43 天)、因果掩码(第 44 天)、数值稳定性(第 45 天)、Pre-LN 残差(第 46 天)或 (x, y) 移位(第 49 天)。

def attention(q, k, v):                      # q, k, v: (B, h, T, d_k)
T, d_model = q.size(-2), q.size(-1) * q.size(1)
scores = q @ k.transpose(-2, -1) / d_model # (A)
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=0) # (B)
scores = scores.masked_fill(mask, float('-inf'))
return scores.softmax(dim=-1) @ v

class Block(nn.Module):
def forward(self, x):
x = self.ln_1(x + self.attn(x)) # (C)
return x + self.mlp(self.ln_2(x))

x, y = chunk[:-1], chunk[:-1] # (D)

实战与预测记录

1. 对 (A)、(B)、(C)、(D) 各行:说明 bug、它违反的是哪一天的规则,以及修复方法。
2. 哪个 bug 会在第一次前向传播就产生 NaN?为什么?
3. 哪个 bug 会让损失下降得异常快,而模型什么有用的都没学到?
4. 全部修复后,V = 100 时第一个损失的期望值是多少?

独立掌握标准

在无辅助的情况下找出全部四个 bug,对应到出处的那一天,给出可行的修复,并正确预测 NaN 和损失骤降两种症状。

权威来源与学术版权说明

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 arXiv non-exclusive license / Open Access

Root Mean Square Layer Normalization

作者/提供方: Biao Zhang, Rico Sennrich (University of Edinburgh) | 原始来源链接 ↗

对应章节/时间戳: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

核验版本与日期: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

入选理由:

Primary paper showing that mean-centering in LayerNorm can be discarded without performance loss, speeding up modern LLMs (LLaMA, Gemma).

先修背景:

Variance, standard deviation, and LayerNorm basics.

安全降级(离线韧性):

RMSNorm formulas and numerical comparisons are derived completely in the lesson.

候选来源对比与遴选分析 (2)
Ba et al. Layer Normalization (2016) ↗ compared_selected_for_day46 [Open Access]

Original LayerNorm formulation with mean-centering; RMSNorm is compared directly against it as an optimization.

Ioffe & Szegedy Batch Normalization (2015) ↗ compared_alternative [Open Access]

Batch-dependent statistics; unsuitable for autoregressive sequence modeling.