AIAA 4051 Introduction to Natural Language Processing

详细主题版笔记。来源为 Lecture 1-25 课件逐页知识集、现有 Obsidian 笔记和 Homework 复习点;不保留逐页课件标题,但每页知识点都被吸收进对应主题。

How to Use This Note

Lecture 1: 课程介绍、数学基础、概率基础与 MLE

Part I: Lecture Map

Part II: Detailed Foundations

1. NLP 的统一视角:把语言问题写成概率问题

NLP 课程里出现的模型看起来很多:n-gram、word vector、HMM、CFG、PCFG、RNN、Transformer、RLHF、diffusion、agent。它们的共同点是:都试图把语言对象转化成可计算的概率、向量或结构。

最基础的抽象是:

  1. 输入是一段文本、一个 token 序列、一个 prompt,或者一个多模态/工具环境状态。
  2. 模型内部有参数 θ
  3. 模型输出一个概率分布,比如下一个词、POS tag、parse tree、translation、answer、action。
  4. 训练就是调节 θ,让真实数据在模型下概率更高。

因此,NLP 的核心不是“背模型名字”,而是要能看懂每个模型如何回答三个问题:

2. 梯度、向量和矩阵为什么是 NLP 的地基

在现代 NLP 中,文本最终会被转成向量。词向量、hidden state、attention score、logit、reward 都是向量或矩阵。训练时,损失函数通常是多变量函数:

L(θ)

梯度告诉我们参数往哪个方向改能让 loss 下降:

θL=(Lθ1,,Lθn)

矩阵乘法是神经模型高效计算的核心。一个线性层可以写成:

z=Wx+b

attention 的核心也依赖矩阵:

Attention(Q,K,V)=softmax(QKTdk)V

这就是为什么 Lecture 1 复习 calculus、linear algebra、probability:后面每个 lecture 都在复用这些工具。

3. 概率分布、MLE 与语言模型训练

如果 X 是一个 categorical random variable,表示下一个 token,那么模型要估计:

Pθ(X=w)

给定观测计数 ci,categorical distribution 的 MLE 是:

θi^=cin

这就是 unigram / bigram 模型中“数频率”的数学来源。复杂模型不能直接数所有可能组合,于是改用神经网络输出概率,再最大化 log-likelihood:

maxθ(x,y)DlogPθ(y|x)

或者最小化 negative log-likelihood:

minθ(x,y)DlogPθ(y|x)

4. Exam Focus

Lecture 1 的考试点通常不是复杂计算,而是概念区分:

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. 为什么学习 NLP:自然语言的重要性

3. 为什么学习 NLP:生成式 AI 与跨学科影响

4. 为什么学习 NLP:职业与能力投资

5. 先修要求

6. 后续可以做什么

7. 课程 logistics:成绩与课堂规则

8. 课程 logistics:Office hour 与 GPU

9. NLP 大图景

10. 微积分回顾:多元函数、导数与梯度

11. 线性代数回顾:向量与矩阵

12. 线性代数回顾:范数、角度与点积

13. 概率回顾:样本空间、事件、随机变量

14. 概率公理

15. 联合分布

16. 概率定理:补集、全概率、条件概率

17. Bayes Rule

18. Bayes Rule 的展开形式与条件版本

19. 期望与方差

20. Bernoulli 与 Binomial 分布

21. Categorical 与 Multinomial 分布

22. 独立性假设

23. 最大似然估计 MLE 的直觉

24. MLE 在 AI/NLP 中的地位

25. Categorical 分布的 MLE 形式化

26. NLP 模型训练的一般流程

27. 扩展阅读

28. Demo

29. Conclusion

30. Quiz

Lecture 2: Tokenization、n-gram、语义表示、Word2Vec/GloVe/FastText

Part I: Lecture Map

Part II: Detailed Language Model Notes

1. Tokenization:模型看到的不是“句子”,而是 token 序列

Tokenization 是 NLP 的第一步。原始文本是字符串,但统计模型和神经模型都需要离散单位。最简单的方法是按空格切分,但真实文本会出现标点、复合词、大小写、数字、emoji、代码符号等复杂情况。

例如:

tokenization 的选择会影响 vocabulary size、OOV、subword sharing 和模型泛化。现代 LLM 常用 BPE / SentencePiece 等 subword tokenizer,本质上就是在“词”和“字符”之间找折中。

2. n-gram Language Model:用短历史近似完整历史

完整句子概率是:

P(w1,,wn)

根据 chain rule:

P(w1,,wn)=i=1nP(wi|w1,,wi1)

问题是完整历史太长,参数不可估计。n-gram 用 Markov-style approximation:

P(wi|w1,,wi1)P(wi|win+1,,wi1)

bigram 特例:

P(wi|w1,,wi1)P(wi|wi1)

MLE 估计为:

P(wi|wi1)=Count(wi1,wi)Count(wi1)

完整证明见:Bigram MLE Derivation

考试直觉: MLE 不是“随便数频率”。分母 Count(wi1) 是所有以前词 wi1 开头的 bigram 总数,而不是整个语料 token 总数。

3. Laplace Smoothing:解决零概率,但会重新分配概率质量

如果某个 bigram 在训练集没出现,MLE 会给它概率 0。只要句子中出现一个概率 0 的 bigram,整句概率就变成 0,这太极端。

Laplace smoothing 给每个候选词加 1:

PL(w2|w1)=c(w1,w2)+1c(w1)+|V|

直觉是:每个可能事件都先给一个“虚拟计数”。这样未见事件不再是 0,但代价是高频事件的概率会被压低。

4. Word Semantics:从 symbolic 到 distributional

one-hot vector 只能表示“词 ID”,不能表示词义。cattiger 在 one-hot 中正交,模型看不出它们都和动物有关。

distributional hypothesis 说:

You shall know a word by the company it keeps.

如果两个词出现在相似上下文,它们就应该有相似语义。Word2Vec、GloVe、FastText 都是在不同方式下实现这个想法。

5. Word2Vec Skip-gram 的训练直觉

Skip-gram 用中心词预测上下文词:

P(wo|wc)=exp(uoTvc)wexp(uwTvc)

loss 是:

L=uoTvc+logwexp(uwTvc)

梯度:

Lvc=uo+wP(w|wc)uw

第一项把中心词向量拉向真实上下文;第二项把它推离模型当前认为可能的平均上下文。softmax 分母太贵,所以 negative sampling 只采少数负样本。

Homework / Exam Connection

Bigram 题的解题固定流程:

  1. 列出所有训练句子,包括 <S></S>
  2. 统计前一个词的总次数 Count(wi1)
  3. 统计 bigram 次数 Count(wi1,wi)
  4. 无 smoothing 用 MLE;有 Laplace 就套:
c(w1,w2)+1c(w1)+|V|

易错点:

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. NLP 的语言层级

3. Word tokenization

4. 词的拆解:复合词、命名风格、数字

5. n-gram language models:句子概率

6. Unigram 模型与 MLE

7. Bigram、Trigram 与零概率问题

8. n-gram smoothing:Laplace 平滑

9. Symbolic vs. Semantics:符号与意义

10. 为什么计算机天然是符号系统

11. Word semantics:字典与 WordNet

12. One-hot word vector

13. Distributional word vector

14. 词向量可视化与 PCA

15. 从文本学习词向量:distributional hypothesis

16. Word2Vec Skip-gram 直觉

17. Word2Vec 建模

18. Word2Vec 优化

19. Word2Vec 梯度推导

20. 梯度下降解释

21. Word2Vec 优化效率:Negative Sampling 与 Mini-batch SGD

22. GloVe 直觉

23. GloVe 建模与目标函数

24. FastText:subword 表示

25. 扩展阅读

26. Demo

27. Conclusion

28. Quiz

Lecture 3: POS tagging 与 Hidden Markov Model 建模

Part I: Lecture Map

Part II: Detailed HMM Modeling Notes

1. POS Tagging 是结构化预测的入门任务

POS tagging 的输入是词序列:

O=[o1,,oT]

输出是同样长度的 tag 序列:

Q=[q1,,qT]

它不是逐词独立分类,因为每个 tag 会影响邻近 tag。例如 determiner 后常接 adjective 或 noun,pronoun 后常接 verb。HMM 把 POS tag 当作 hidden states,把 words 当作 observations。

2. HMM 的两个概率:transition 和 emission

HMM 参数包括:

πi=P(q1=i) aij=P(qt=j|qt1=i) bi(o)=P(ot=o|qt=i)

transition 描述语法结构,emission 描述某个 tag 生成某个词的可能性。

3. HMM 的两个独立性假设

First-order Markov assumption:

P(qt|q1,,qt1)P(qt|qt1)

Emission independence:

P(ot|q1,,qT,o1,,ot1)P(ot|qt)

这两个假设很强,但它们把指数级问题变成可计算问题。

4. MAP Decoding

预测目标是:

Q=argmaxQP(Q|O)

用 Bayes rule:

P(Q|O)=P(O|Q)P(Q)P(O)

因为 P(O)Q 无关:

Q=argmaxQP(O|Q)P(Q)

HMM decoding 不是只选每个词最常见 tag,而是选整体最可能 tag sequence。

Homework / Exam Connection

常见选择题陷阱:

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. English POS 类别

3. POS running example

4. POS 的重要性:句法信息与拼写纠错

5. POS 的重要性:语义信息与下游任务

6. POS tagging 为什么难

7. Buffalo 问题

8. 社交媒体与 OOV

9. HMM 动机:用上下文消除 POS 歧义

10. HMM 形式化

11. HMM 与 Bayes Rule

12. n-gram 理论:两个概率都太复杂

13. Markov assumption

14. 用 Markov assumption 简化 tag 序列

15. Transition probability matrix

16. Emission probability

17. Emission probability matrix

18. 完整 HMM 与三个任务

19. 扩展阅读

20. Demo

21. Conclusion

22. Quiz

Lecture 4: HMM Forward / Backward Algorithm

Part I: Lecture Map

Part II: Detailed Forward / Backward Notes

1. Inference 目标:算观测序列概率

HMM inference 问的是:

P(O|λ)

其中 λ=(A,B,π)。因为 hidden tag sequence 不可见:

P(O)=QP(O,Q)

直接枚举 QNT 条路径,复杂度指数级。Forward/Backward 用 DP 把所有路径“压缩”进局部概率。

2. Forward Probability

定义:

αt(j)=P(o1,,ot,qt=j)

它是一个 joint probability:到时间 t 为止观测到前 t 个词,并且当前状态是 j

初始化:

α1(j)=πjbj(o1)

递推:

αt(j)=iαt1(i)aijbj(ot)

最后:

P(O)=jαT(j)

3. Backward Probability

定义:

βt(i)=P(ot+1,,oT|qt=i)

它是 conditional probability:已知当前状态是 i,未来观测出现的概率。

初始化:

βT(i)=1

递推:

βt(i)=jaijbj(ot+1)βt+1(j)

4. 任意中间时刻也可以恢复整句概率

Forward 和 Backward 在任意 t 可以拼起来:

P(O)=jαt(j)βt(j)

这是因为 αt(j) 覆盖过去和当前,βt(j) 覆盖未来;二者乘积覆盖完整 observation sequence。

Homework / Exam Connection

易错点:

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. Inference 问题定义

3. Forward algorithm 与动态规划

4. Forward probability 定义

5. Forward base case

6. Forward 第二步

7. Forward example:Fly High

8. Forward general case 与证明

9. 展开递推与复杂度

10. 句子概率与矩阵化

11. Backward algorithm 定义

12. Backward base case

13. Backward example:fly high

14. Backward general case 与证明

15. Backward 算法流程与矩阵化

16. 扩展阅读

17. Demo

18. Conclusion

19. Quiz

Lecture 5: HMM Viterbi Decoding 与 EM / Baum-Welch

Part I: Lecture Map

Part II: Detailed Viterbi and EM Notes

1. Viterbi:把 Forward 的 sum 换成 max

Forward 算所有路径总概率;Viterbi 找最可能的一条路径。

定义:

vt(j)=maxq1,,qt1P(q1,,qt1,qt=j,o1,,ot)

初始化:

v1(j)=πjbj(o1)

递推:

vt(j)=maxivt1(i)aijbj(ot)

要恢复路径,需要 backpointer:

pt(j)=argmaxivt1(i)aijbj(ot)

2. Example: They base

题目给:

v1(NNP)=0.50.8=0.4v1(N)=0,v1(V)=0

计算:

v2(V)=maxiv1(i)ai,VbV(base)

最大来自 NNPV

v2(V)=0.40.70.4=0.112

而:

v2(N)=0.40.10.6=0.024

所以最优路径:

Q=[NNP,V]

3. Supervised HMM MLE

如果 tag 已知,可以直接数:

aij=C(ij)C(i)bi(o)=C(io)C(i)πi=C(q1=i)number of sentences

4. EM / Baum-Welch

如果 tag 不知道,不能直接数 hard counts。EM 用 soft counts。

状态 posterior:

γt(i)=P(qt=i|O,λ)=αt(i)βt(i)P(O|λ)

转移 posterior:

ξt(i,j)=P(qt=i,qt+1=j|O,λ)=αt(i)aijbj(ot+1)βt+1(j)P(O|λ)

E-step:用 Forward/Backward 算 γ,ξ
M-step:用 soft counts 更新 π,A,B

5. Conditional Independence Proof for γ

从定义:

γt(i)=P(qt=i|O,λ)=P(qt=i,O|λ)P(O|λ)

O 拆成:

O=(o1:t,ot+1:T)

HMM 条件独立给出:

P(ot+1:T|o1:t,qt=i,λ)=P(ot+1:T|qt=i,λ)

所以:

P(qt=i,O|λ)=P(o1:t,qt=i|λ)P(ot+1:T|qt=i,λ)=αt(i)βt(i)

得到:

γt(i)=αt(i)βt(i)P(O|λ)

Homework / Exam Connection

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. HMM prediction 问题

3. Running example:Time flies like an arrow

4. Structured prediction

5. Viterbi algorithm 概念

6. Viterbi base case

7. Viterbi t=2 情况

8. Viterbi general case

9. Backpointer 记录最优路径

10. Viterbi algorithm 流程

11. Running example:They base

12. Viterbi 趣闻

13. Supervised HMM 参数估计

14. EM algorithm 基本思想

15. EM 例子与性质

16. HMM 转移矩阵的 soft counts

17. Soft label 的计算

18. 发射矩阵的 soft counts

19. Baum-Welch Algorithm

20. 扩展阅读

21. Demo

22. Conclusion

23. Quiz

Lecture 6: Syntax、CFG、CYK Parsing

Part I: Lecture Map

Part II: Detailed CFG / CYK Notes

1. Constituent 和 CFG 的意义

句法分析不是只看相邻词,而是要识别哪些词组成一个整体。这个整体叫 constituent (语法成分)。例如:

CFG 用规则描述这些组合:

G=(N,Σ,R,S)

其中 N 是 non-terminals,Σ 是 terminals,R 是 rules,S 是 start symbol。

2. CNF 与 derivation step 数量

CNF 只允许:

ABC

或:

Aa

如果一个 CNF parse tree 生成 n 个词,那么:

所以总 derivation steps:

n+(n1)=2n1

这是 Homework 选择题常考点。

3. CYK Table

CYK 用 span boundary,而不是 word index。长度为 n 的句子有 gap index 0,,n。cell (i,j) 表示从 gap i 到 gap j 的子串。

如果:

Btable[i,k]Ctable[k,j]

并且有规则:

ABC

那么:

Atable[i,j]

4. Attachment Ambiguity Example

句子:

agents observe scenes with cameras

词级初始化:

[0,1]=NP,[1,2]=V,[2,3]=NP,[3,4]=P,[4,5]=NP

先得到:

[3,5]=PP

因为:

PPP NP

路径 1:PP attach 到 NP

[2,5]=NP

因为:

NPNP PP

然后:

[1,5]=VP

因为:

VPV NP

含义是:observe [scenes with cameras]

Wiki/Image/Class/Introdution to NLP/1.png

路径 2:PP attach 到 VP

[1,3]=VP

因为:

VPV NP

然后:

[1,5]=VP

因为:

VPVP PP

含义是:[observe scenes] with cameras

5. CYK Complexity Proof

CYK 的循环结构:

  1. span length 有 O(n) 种。
  2. 每个 span length 下 start index 有 O(n) 种。
  3. 每个 cell 枚举 split point k,有 O(n) 种。
  4. 每个 split 需要检查 grammar rules,最坏 O(|R|)

所以:

O(n)O(n)O(n)O(|R|)=O(n3|R|)

Homework / Exam Connection

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. Grammar and syntax

3. Syntax 定义

4. n-gram/HMM 建模 shallow syntax

5. Constituent

6. Context-free grammar 概念

7. CFG 四元组、推导、语言

8. CFG 示例与 parse tree

9. CFG:句子类型规则

10. CFG:Noun Phrase

11. CFG:Nominal

12. CFG:Verb Phrase

13. CFG 来源:Penn Treebank

14. The bitter lesson

15. Syntactic parsing 目标

18. Parsing ambiguity:attachment ambiguity

19. Parsing ambiguity:coordination ambiguity

20. Repeated subproblems

21. CYK parsing algorithm

22. CNF CFG

23. CNF 转换算法

24. CYK 矩阵结构

25. CYK algorithm 伪代码

26. CYK parsing examples

27. 扩展阅读

28. Demo

29. Conclusion

30. Quiz

Lecture 7: Probabilistic CFG、Inside/Outside、最优解析树

Part I: Lecture Map

Part II: Detailed PCFG / Inside Notes

1. 从 CFG 到 PCFG

CFG 只能回答“这个句子是否合法 / 这棵树是否可能”。PCFG 给每条 rule 加概率,能比较不同 parse tree 的可能性。

对同一个 LHS,所有规则概率和为 1:

αP(Aα)=1

一棵 parse tree 的概率是所有 rule 概率的乘积:

P(t,w|G)=rtP(r)

句子概率是所有 parse tree 概率求和:

P(w|G)=tP(t,w|G)

2. Inside Probability

Inside probability 表示一个 non-terminal 生成某个 span 的概率。

Base case:

βA(i,i)=P(Awi)

CNF 递推:

βA(i,j)=ABCk=ij1P(ABC)βB(i,k)βC(k+1,j)

它和 CYK 很像,只是 CYK 存“能不能生成”,Inside 存“生成概率是多少”。

3. Homework Example: cats catch mice

Grammar:

SNP VP,P=1VPV NP,P=1

Lexicon:

NPcats, P=0.5NPmice, P=0.5Vcatch, P=1

Base:

βNP(1,1)=0.5βV(2,2)=1βNP(3,3)=0.5

VP:

βVP(2,3)=P(VPV NP)βV(2,2)βNP(3,3)=110.5=0.5

Sentence:

βS(1,3)=P(SNP VP)βNP(1,1)βVP(2,3)=10.50.5=0.25

4. Outside and Viterbi-style PCFG

Outside probability 表示 span 外部的上下文概率。Inside + Outside 可用于估计某个 rule 或 constituent 在整句 parse 中出现的 posterior。

如果要找最优 parse tree,而不是句子总概率,就把 Inside 的求和换成 max,并记录 backpointer。这就是 PCFG 的 Viterbi-style parsing。

Part II-B: Homework / Exam Connection

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. PCFG 动机

3. PCFG 定义

4. Parse tree 概率与句子概率

5. PCFG 三个假设

6. PCFG 假设示例

7. PCFG 的三个算法任务

8. Inside / Outside probability

9. Inside algorithm

10. Inside probability example

11. Outside probability

12. Outside algorithm base case

13. Outside DP 依赖 inside probability

14. 用 inside/outside 得到句子概率

15. 寻找最优 parse tree

16. 最优树 running example

17. 扩展阅读

18. Demo

19. Conclusion

20. Quiz

Lecture 8: Neural Network 与 RNN Language Modeling

Part I: Lecture Map

Part II: Detailed Neural LM Notes

1. 为什么 n-gram 不够:稀疏、复杂度、固定窗口

n-gram language model 的概率来自计数。它能工作,是因为短局部上下文里常有强统计规律;它的问题也正来自这里:当上下文稍微变长,可能的组合数量会指数级增加。

例如要估计:

P(professor|and asked the)

训练集中必须足够多次出现 and asked the professor 这类片段,否则概率估计会不稳定;如果完全没见过,MLE 甚至会给 0。增大 n 看似能捕捉更长上下文,但也会让 data sparsity 和 model complexity 更严重。

神经网络语言模型换了一个思路:不再显式记住每个短语的频率,而是学习一个共享参数的函数:

Pθ(wt|context)

这样相似上下文可以共享表示,未见过的组合也可以通过 embedding 和 hidden state 泛化。

2. Logistic Regression 是最小的神经网络

二分类 logistic regression 可以写成:

z=wTx+ba=σ(z)=11+exp(z)

binary cross-entropy loss:

(a,y)=log(ay(1a)1y)=yloga(1y)log(1a)

这个模型已经具备神经网络的基本结构:输入经过线性变换,接一个非线性函数,再用 loss 衡量输出和标签的差距。更深的网络只是把这种可微计算图堆叠起来。

3. MLP:隐藏层和非线性让模型表达复杂模式

一个隐藏层 MLP 可写成:

z[1]=W[1]x+b[1]a[1]=g(z[1])z[2]=W[2]a[1]+b[2]

隐藏层把原始输入变成中间特征;非线性 g 很关键。如果没有非线性,多层线性变换会合并成一个线性变换:

W2(W1x)=Wx

这样就失去“深层”的意义。ReLU、sigmoid、tanh 都是为了让模型能表示非线性语言规律。

4. Vectorization:从逐 neuron 计算到矩阵计算

课件强调 vectorization,因为神经网络的速度来自矩阵运算。逐个 neuron 写循环:

zj=wjTx+bj

可以合并为:

z=Wx+b

这不仅代码更简洁,也能让 GPU 一次性并行处理大量乘加操作。后面的 Transformer、LoRA、FLOPs、quantization 都默认我们已经把模型看成矩阵计算。

5. RNN:用 hidden state 压缩历史

RNN 的核心递推是:

ht=tanh(Wht1+Uxt+b)ot=Vht+cy^t=softmax(ot)

其中 ht 是到第 t 步为止的历史摘要。语言模型中,训练目标通常是预测下一个 token:

L=tlogPθ(wt+1|wt)

POS tagging 中,输出可以是当前位置或下一位置的 POS tag。区别在输出含义,递归结构类似。

6. BPTT 与梯度消失 / 爆炸

RNN 训练时要把时间展开成一个很深的网络,再用 Back-Propagation Through Time (BPTT) 反传。长序列中,早期 hidden state 到后期 loss 的梯度会反复乘上 W 的相关项。

如果矩阵乘法让梯度范数不断变小,就出现 vanishing gradient (梯度消失);如果不断变大,就出现 exploding gradient (梯度爆炸)。tanh 把 hidden value 限制在 [1,1],能稳定数值,但不能彻底解决长程依赖。

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. n-gram 的动机问题

3. n-gram 三个问题

4. 神经网络作为解决方案

5. Logistic regression 是神经网络

6. 从 logistic regression 到 MLP

7. 神经网络是堆叠的 logistic 模型

8. Vectorization

9. RNN 基本思想

10. RNN 结构、参数与训练数据

11. RNN 计算公式

12. RNN training 与 BPTT

13. 为什么需要 tanh 非线性

14. 扩展阅读

15. Demo

16. Conclusion

17. Quiz

Lecture 9: Machine Translation、Rule-based MT、IBM Model 1

Part I: Lecture Map

Part II: Detailed Machine Translation Notes

1. MT 的基本问题:从 Rosetta Stone 到平行语料

机器翻译的核心是:给定源语言句子 F,生成目标语言句子 E。Rosetta Stone 的故事说明了 translation 的统计基础:如果同一内容以多种语言出现,就可以通过模式、位置和共现关系推断语言之间的映射。

现代统计 MT 使用 parallel corpus,例如 Canadian Hansards。平行语料提供大量句子对,让模型学习哪些词、短语或结构在两种语言之间对应。

2. 语言差异:翻译不是查字典

课件给了几类语言差异:

所以翻译系统不仅要翻词,还要决定词序、语法一致性、上下文语义和目标语言自然度。

3. Rule-based MT 与 Vauquois Triangle

Vauquois triangle 把翻译方法按抽象程度分层:

direct method 可处理 green witch -> bruja verde 这种局部重排,但难处理长程结构差异。transfer method 更强,但依赖 parser 和人工规则。

4. Fluency 和 Faithfulness 的概率分解

传统统计 MT 把好翻译理解成两个目标的乘积:

形式化目标:

E=argmaxEP(E|F)

用 Bayes rule:

E=argmaxEP(F|E)P(E)

其中:

5. Word Alignment 是隐藏变量

word alignment 表示源语言词和目标语言词的对应关系。设外语句子:

F=(f1,,fJ)

英语句子:

E=(e1,,eI)

alignment 用 aj 表示第 j 个外语词 fj 对齐到英语第几个词:

aj{0,1,,I}

0 可表示 NULL,用来处理没有显式对应的词。真实翻译可能 one-to-one、one-to-many、many-to-one、many-to-many,因此 alignment 是统计 MT 的核心隐变量。

6. IBM Model 1

IBM Model 1 的 generative story:

  1. 给定目标句 E
  2. 生成源句长度 J
  3. 生成 alignment A
  4. 对每个位置 j,根据 eaj 生成 fj

联合概率:

P(F,A|E)=P(J|I)P(A|I,J)j=1JP(fj|eaj)

因为 alignment 不可见,要求和:

P(F|E)=AP(F,A|E)

Model 1 的问题也很清楚:它把词当作 bag-of-words,不建模位置 locality;词翻译只依赖词对,不看上下文;也不能自然表示 many-to-many 短语翻译。

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. 古代 Rosetta Stone 与翻译问题

3. 翻译技巧与现代 Rosetta Stone

4. 机器翻译与 LLM

5. IBM Model 1 与 LLM 翻译对比

6. 语言差异:lexical 与 syntactic

7. 语言差异:word ordering

8. Vauquois triangle

9. Rule-based direct translation

10. Direct method 的缺陷

11. Rule-based transfer method

12. 翻译评价:fluency 与 faithfulness

13. 翻译评价与“信达雅”

14. MT 目标的概率形式

15. Word alignment

16. Alignment matrix

17. Alignment 的复杂情况

18. IBM Model 1 generative story

19. IBM Model 1 概率

20. IBM Model 1 问题

21. 扩展阅读

22. Demo

23. Conclusion

24. Quiz

Lecture 10: HMM Alignment、Decoding Search、BLEU、Seq2Seq、Attention

Part I: Lecture Map

Part II: Detailed MT Decoding / Seq2Seq / Attention Notes

1. HMM Alignment:给 alignment 加上 locality

IBM Model 1 的弱点是忽略词序。HMM alignment model 把 alignment 位置看成 hidden state,把源语言词看成 observation。

Markov 假设:

P(aj|a1,,aj1,E)P(aj|aj1,I)

发射假设:

P(fj|history,E,A)P(fj|eaj)

联合概率:

P(F,A|E)=P(J|I)j=1JP(aj|aj1,I)P(fj|eaj)

这里 P(aj|aj1,I) 是 jump model,鼓励相邻源词对齐到相邻目标词,因为真实翻译通常有 locality。

2. Translation Decoding 是搜索问题

训练 alignment/translation model 后,解码目标是:

E^=argmaxEP(F|E)P(E)

候选译文空间巨大,不能枚举。因此需要 search-based decoding:

beam 太小会丢掉未来更优候选;beam 太大计算贵,也不一定保证更好。

3. BLEU:自动评价的优点和陷阱

BLEU 用候选翻译与参考翻译的 n-gram overlap 来近似质量。对 n=1,2,3,4 分别算 precision,再做几何平均:

BLEUexp(1Nn=1Nlogpn)

unigram precision 更像词义覆盖,高阶 n-gram 更像局部词序和流畅度。

主要陷阱:

4. Seq2Seq:从统计 MT 到神经 MT

seq2seq encoder-decoder 用一个 RNN 编码源句,用另一个 RNN 生成目标句。encoder 递推:

hi=f(hi1,xi)

decoder 生成:

P(yt|y<t,x)=softmax(g(st))

训练时常用 teacher forcing:decoder 的上一步输入用真实词 yt1,而不是模型预测词。loss 是目标序列的 NLL:

L=tlogPθ(yt|y<t,x)

5. Fixed-length Bottleneck 和 Attention

经典 seq2seq 把整个源句压进一个 fixed-length vector。长句时,这个向量必须同时保存所有词义和词序,负担过重。

attention 的想法是:每生成一个目标词,都动态查看源句 hidden states。设 decoder state 是 query,encoder states 是 keys/values:

et,i=score(st,hi)αt,i=softmax(et,i)ct=iαt,ihi

context vector ct 再和 decoder state 一起预测当前词。这样模型不需要把所有信息压缩进最后一个 hidden state。

6. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. 课程标题页

2. IBM Model 1 的弱点

3. 用 HMM 改造 translation alignment

4. HMM translation 的 Markov 假设与模型

5. Alignment locality 与 jump model

6. Translation decoding

7. Search-based methods

11. BLEU 直觉

12. BLEU 计算

13. BLEU pitfalls

14. Seq2seq encoder-decoder

15. Seq2seq 结构细节

16. Seq2seq training

17. Seq2seq issue:fixed-length bottleneck

18. Seq2seq issue:长程依赖、梯度与并行性

19. Attention mechanism 直觉

20. Attention mechanism 公式与优缺点

21. 扩展阅读

22. Demo

23. Conclusion

24. Quiz

Lecture 11: Transformer 架构、位置编码、注意力、LayerNorm 与残差连接

Part I: Lecture Map

Part II: Detailed Transformer Notes

1. Transformer 的基本动机

RNN 最大的问题是 sequential dependency:第 t 步必须等第 t1 步算完,训练很难完全并行;长程依赖还会遇到梯度消失/爆炸。Transformer 用 self-attention 直接让每个 token 访问序列中其他 token,从而更适合大规模并行训练。

一个 Transformer block 可以粗略看成:

  1. token embedding + positional embedding。
  2. multi-head self-attention。
  3. residual connection + layer normalization。
  4. MLP / feed-forward layer。
  5. residual connection + layer normalization。

2. Positional Embedding:给 attention 顺序感

self-attention 本身对顺序不敏感。如果只看 token 集合,dog bites manman bites dog 的 token 一样,但意思不同。因此输入表示通常写成:

xi=e(wi)+pi

其中 e(wi) 是 token embedding,pi 是 position embedding。没有 positional information,模型很难区分主语、宾语、相对位置和语序。

3. Scaled Dot-Product Attention

给定矩阵:

Q=XWQ,K=XWK,V=XWV

attention 计算:

Attention(Q,K,V)=softmax(QKTdk)V

解释每一项:

如果 batch size 是 B,head 数是 nh,序列长度是 T,每个 head 维度是 hs,课件里的典型形状是:

q.shape=[B,nh,T,hs]

4. Multi-head Attention

多个 attention head 不是简单重复。不同 head 可以学习不同关系:

如果 embedding 维度是 C,通常有:

C=nh×hs

每个 head 独立计算 attention,最后 concat 后投影回模型维度。

5. MLP、Layer Normalization 和 Residual

attention 做 token 间信息交换,MLP 做每个位置内部的特征变换:

MLP(x)=W2σ(W1x+b1)+b2

LayerNorm 对每个 token 的 hidden vector 做归一化:

LN(x)=γxμσ2+ϵ+β

它让训练更稳定。residual connection 则让模型学习增量:

xl+1=xl+F(xl)

这能缓解深层网络训练困难,也让信息可以跨层保留。

6. Training、Inference 和 Mechanistic Interpretability

训练时,autoregressive Transformer 可用 causal mask 并行计算所有位置的 next-token loss。推理时却必须一个 token 一个 token 生成:

wtPθ(wt|w<t)

因此推理效率低,后续 Lecture 20 的 KV Cache、PagedAttention、StreamingLLM 都是在处理这个系统瓶颈。

Mechanistic interpretability 尝试解释 Transformer 内部 circuit:哪些 head 负责复制、括号匹配、指代或特定 pattern。这不是 Transformer 架构组件,而是研究模型行为的方法。

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 11

2. Transformer

3. Transformer

4. Transformer: positional embedding

5. Transformer: positional embedding

6. Transformer: positional embedding

7. Transformer: MLP layer

8. Transformer: attention

9. Transformer: attention C = nh * hs=n_embd

10. Transformer: attention q.shape=[B, nh, T, hs]

11. Transformer: attention

12. Transformer: layer normalization

13. Transformer: layer normalization

14. Transformer: residual connections

15. Transformer: residual connections

16. Transformers: mechanistic interpretability

17. Transformer: mechanistic interpretability

18. Transformer: training

19. Transformer: inference INEFFICIENCY: 1) need a for loop to generate token-by-token;

20. Research project 1

21. Extra readings

22. Demo

23. Conclusion

24. Quiz

Lecture 12: Pretraining、Mid-training、Post-training、BERT 与 GPT

Part I: Lecture Map

Part II: Detailed Pretraining Notes

1. 三阶段:Pretraining、Mid-training、Post-training

LLM 不再主要遵循传统小任务的 train/test paradigm,而是按阶段训练:

课件用 chef 类比:pretraining 像学会基本厨艺和食材知识,mid-training 像专攻某菜系,post-training 像学会按顾客要求服务。

2. 为什么 pretraining 有迁移能力

pretraining 让模型参数落在一个更好的 loss landscape 区域。后续任务不需要从随机参数开始,而是在已经学到语言规律和概念组织的模型上微调或 prompting。

这解释了 downstream fine-tuning/prompting:

同一个 pretrained model 可以被初始化到不同任务上,因为它已经学到可复用表示。

3. Pretraining 成败因素

课件列出四类因素:

数据方面,常见来源包括 books、Wikipedia、Common Crawl、social media、open-source code repositories。随着公开数据被有效用尽,private data 和 AI-generated data 变得重要。

4. Masked Language Modeling and BERT

MLM 把一部分 token 替换成 [MASK],让模型根据双向上下文预测原词。目标只在 masked positions 上计算:

LMLM(θ)=iMlogPθ(xi|xM)

BERT 的 15% masking 规则:

原因是 fine-tuning 时不会出现 [MASK],所以训练不能只让模型适应 mask token。

BERT 输入 embedding 是三者相加:

xi=tokeni+segmenti+positioni

BERT Base:12 layers、768 hidden、12 heads、110M parameters。BERT Large:24 layers、1024 hidden、16 heads、340M parameters。

5. Autoregressive Language Modeling and GPT

autoregressive objective 从左到右预测下一个 token:

LAR(θ)=DtlogPθ(wt|w<t)

优点:

缺点:

GPT 是 decoder-only Transformer。课件提到 GPT 2018 的 12 layers、117M parameters、768 hidden、3072 FFN hidden、BPE 40k merges,以及 Llama 系列用 trillion tokens 级别数据训练。

6. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 12

2. Pretraining, mid-training, post-training

3. Pretraining, mid-training, post-training

4. Pretraining: downstream fine-tuning/prompting

5. Pretraining: why

6. Pretraining: why

7. Major factors affecting pre-training

8. Model architecture

9. What data to use

10. Data factors: quantity

11. Data factors: quality

12. Pretraining objective function

13. Masked language modeling

14. Masked language modeling: BERT

15. Masked language modeling: BERT

16. Masked language modeling: BERT

17. Masked language modeling: BERT

18. Autoregressive language modeling

19. Autoregressive language modeling

20. Autoregressive language modeling: GPT

21. Autoregressive language modeling: GPT

22. Autoregressive language modeling: GPT

23. Autoregressive language modeling: GPT

24. Autoregressive language modeling: GPT

25. Extra readings

26. Demo

27. Conclusion

28. Quiz

Lecture 13: Supervised Fine-Tuning (SFT)、Alignment 与数据构造

Part I: Lecture Map

Part II: Detailed SFT / Alignment Notes

1. SFT 和 Pretraining 数学相似,但数据分布不同

Supervised Fine-Tuning (SFT) 仍然是 next-token prediction。差别在于数据不是海量 raw text,而是 prompt/instruction 与高质量 response 的配对。

预训练:

Lpretrain=tlogpθ(wt|w<t)

SFT:

LSFT=tmtlogpθ(yt|x,y<t)

其中 mt 是 loss mask。通常 prompt 部分 mt=0,response 部分 mt=1,因为我们希望模型学习“如何回答”,而不是学习复述用户 prompt。

2. Alignment:Helpful、Harmless、Honest

base LM 擅长续写文本,但不一定擅长做 assistant。alignment 试图让模型满足:

这解释了为什么 GPT-3 直接使用时可能不如 InstructGPT:base model 学的是“互联网文本续写”,aligned model 学的是“按人类偏好回答”。

3. Single-task SFT vs Multi-task SFT

Single-task SFT 用大量同一任务数据训练专门模型,例如只做 sentiment 或 bug fixing。优点是任务表现强,缺点是泛化窄。

Multi-task SFT / instruction tuning 混合多任务,训练 generalist assistant。它更适合开放式交互,但数据组成更难:不同任务可能语义冲突,混太多会导致 catastrophic forgetting。

4. SFT 数据来源和格式

人工标注优点是质量高,缺点是慢、贵、缺多样性。AI-generated data 出现后,Self-Instruct 等方法让强 teacher model 生成 instruction-response pair。

常见数据格式:

课件列出的数据集包括 Alpaca、Dolly-15k、COIG、OASST1;要记住它们说明了 SFT 数据可以是英文、中文、多语言、单轮、多轮、人写或模型生成。

5. Prompt Loss Weight

prompt loss weight 控制 prompt token 是否也参与 loss:

直觉是:完全不看 prompt loss 可能更像 instruction follower,但也可能忘掉一些语言和世界知识;少量 prompt loss 可以让模型保持 base model 能力。

6. Industrial SFT: SWE-Lego

SWE-Lego 说明 coding-agent SFT 不只是普通 QA。它的数据包括:

合成 bug 可通过 LLM rewrite 或 AST reformulation,例如删除 conditional、修改 operator、改变依赖。curriculum learning 让模型先学简单读代码/修 bug,再学困难任务。

7. Catastrophic Forgetting and Dual-stage Mixed Fine-tuning

多任务 SFT 中,math、coding、general chat 的数据分布不同。直接大量混合可能让某些能力下降。dual-stage mixed fine-tuning 的思想是:用少量 general data 保持通用能力,同时加入目标任务数据学习专业技能。

8. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 13

2. Supervised fine-tuning (SFT)

3. Pretraining vs. SFT

4. Why alignment?

5. Why alignment

6. Why alignment

7. Why alignment

8. Two kinds of SFT

9. Two kinds of SFT

10. Data for SFT

11. Data for SFT

12. Data for SFT

13. Data for SFT

14. Data for SFT: AI generated data

15. Data for SFT: available datasets

16. Data for SFT: available datasets

17. Data for SFT: available datasets

18. Data for SFT

19. SFT loss function

20. SFT loss function

21. SFT loss function

22. SFT performance

23. SFT performance

24. Industrial SFT

25. SWE-Lego: coding agent

26. SWE-Lego: pipeline

27. SWE-lego: data curation

28. SWE-Lego: synthetic data curation

29. SWE-Lego: curriculum learning for SFT

30. SWE-Lego: results

31. Multi-task SFT: catastropic fogetting

32. Multi-task SFT: Dual-stage mixed fine-tuning

Lecture 14: Parameter-Efficient Fine-Tuning、LoRA 与 QLoRA

Part I: Lecture Map

Part II: Detailed PEFT / LoRA / QLoRA Notes

1. Full Fine-tuning 为什么贵

full-parameter fine-tuning 要更新所有参数,还要保存梯度和 optimizer states。课件给出的 16-bit fine-tuning 每个参数大约需要:

合计约 96 bits = 12 bytes per parameter。65B model 约需要:

65×109×12 bytes780GB

这解释了为什么普通组织难以全量微调大模型。

2. PEFT 的直觉:只改低维有效方向

Parameter-Efficient Fine-Tuning (PEFT) 只训练少量参数。它背后的课程直觉有两层:

pretraining 已经把概念组织到一个好表示空间,fine-tuning 只需沿少数方向移动。

3. LoRA:低秩更新

LoRA 假设 full fine-tuning 的权重变化:

ΔW

虽然形状很大,但有效 rank 很低。于是分解为两个小矩阵:

ΔW=BA

其中 ARr×dBRk×rrmin(d,k)。前向计算变成:

h=Wx+BAx

base weight W 冻结,只训练 A,B

初始化规则:

LoRA adapter 可切换、可合并到 base weight,部署时通常没有额外 latency。

4. LoRA Cost

课件给出 LoRA 后每参数平均成本约 17.6 bits,因为只有少量 adapter 参数需要 gradient/optimizer states。65B model 从 780GB 级别降到约 143GB,仍需要多张 A6000,但已大幅降低门槛。

工业场景中,一个 SaaS 平台可常驻一个 base model,然后按客户动态加载 LoRA adapter。这样 1000 个客户不需要 1000 个完整模型。

5. QLoRA:把 base model 量化到 4-bit

QLoRA 冻结并量化 base Transformer 到 4-bit,同时训练 LoRA adapter。课件强调 NF4:

QLoRA 还使用 paged optimizer,把 optimizer states 在 GPU/CPU 间 page in/out,处理长序列或梯度导致的 memory spikes。

课件给出 QLoRA 成本约 5.6 bits per parameter,65B model 约 45.5GB,可放进一张 48GB A6000。

6. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 14

2. Parameter-efficent fine-tuning

3. Start with a phenomenon

4. Start with a phenomenon

5. Fine-tuning is expensive

6. PEFT: Parameter-efficient Fine-tuning

7. Questions about PEFT

8. Intuition of pre-training

9. Intrinsic Dimension & Manifold Learning

10. Parameter Overload & Matrix Factorization

11. Intrinsic Dimension of LLM

12. Intrinsic Dimension

13. Intrinsic Dimension

14. Motivation of LoRA

15. LoRA

16. LoRa Initialization

17. LoRA Cost

18. From LoRa to QLoRa

19. Why NF4 is Optimal

20. From LoRa to QLoRa

21. QLoRa Cost

22. LoRa in Industry

23. Demo

24. Extra readings

25. Quiz

Lecture 15: RLHF 动机、Reward Model 与 Bradley-Terry

Part I: Lecture Map

Part II: Detailed RLHF Notes

1. 为什么 SFT 不够

开放式问题没有唯一正确答案。写诗、摘要、建议、长解释、聊天风格都不能简单用 one-hot ground truth 衡量。SFT loss 会把所有“不是参考答案”的 token 都惩罚掉,即使其中有些答案其实也很好。

因此需要一个 scalar quality metric:

R(y|x)

它表示回答 y 对 prompt x 的质量。

2. Policy Gradient:reward 不可微也能优化

RLHF 的目标是让模型生成高 reward 回答:

J(θ)=Es^pθ(s)[R(s^)]

用 log-derivative trick:

θJ(θ)=θspθ(s)R(s)=spθ(s)R(s)θlogpθ(s)=Espθ[R(s)θlogpθ(s)]

重要直觉:reward model 输出不需要可微;我们只需要对 language model 的 log probability 求梯度。高 reward 的 sentence 会被提高概率,低 reward 的 sentence 会被压低概率。

3. Reward Model:为什么用 pairwise comparison

直接让人给回答打 1-10 分有两个问题:

pairwise comparison 更稳定:给同一个 prompt 的两个回答,让人判断哪个更好。

Bradley-Terry model:

P(ywyl|x)=σ(rϕ(x,yw)rϕ(x,yl))

reward model loss:

LRM(ϕ)=logσ(rϕ(x,yw)rϕ(x,yl))

只有 reward difference 影响 preference probability,absolute reward offset 不重要。

4. Reward Hacking 和 KL Penalty

reward model 是 proxy,不是真实人类价值。policy 可能学会 exploit reward model,例如用过度自信、礼貌套话或空泛表达骗高分。

RLHF 通常加入 KL penalty,让新 policy 不要离 reference/pretrained policy 太远:

J(θ)=E[R(x,y)]βDKL(πθ(|x)||πref(|x))

直觉是:reward 推动模型更符合偏好,KL 保留原模型的语言能力和分布稳定性。

5. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 15

2. Limitations of SFT

3. Limitations of SFT

4. Need a way to measure

5. Use measurement to optimize

6. Use measurement to optimize

7. Policy Gradient for RLHF

8. Policy Gradient for RLHF

9. Policy Gradient for RLHF

10. Update Parameters

11. Reward Model

12. Reward Model

13. The Math Behind: Bradley-Terry Model

14. Train Reward Model

15. Reward Model Problem

16. Reward Model Problem

17. RLHF

18. RLHF Performance

19. RLHF in Industry

20. Quiz

Lecture 16: PPO、KL Divergence、TRPO 与 RLHF 稳定优化

Part I: Lecture Map

Part II: Detailed PPO / TRPO Notes

1. RLHF 回顾与 delayed reward

在语言生成中,policy 是 LLM:

πθ(yt|x,y<t)

reward 往往在完整回答生成后才知道,例如整段回答是否有帮助、是否安全、是否正确。这叫 delayed reward。policy gradient 能处理 delayed reward,但更新很敏感。

2. 为什么普通参数空间 step 不可靠

普通神经网络里,我们常假设参数小变化会导致输出小变化。但 policy network 的分布可能很敏感:参数空间欧氏距离相同的两个更新,可能让某些 action probability 从很高变成 0。

这会导致 catastrophic collapse

所以 RLHF 需要限制 policy 行为分布的变化,而不仅是限制参数距离。

3. KL Divergence 和 Fisher Information Matrix

KL divergence 衡量两个分布差异:

DKL(P||Q)=xP(x)logP(x)Q(x)

性质:

在当前参数 θ 附近,对 KL 做 Taylor expansion:

DKL(πθ||πθ+Δθ)12ΔθTFΔθ

其中 FFisher Information Matrix (FIM)。它是局部 metric,描述参数变化会让 policy distribution 变化多少。

4. Natural Gradient

普通梯度方向 g=θJ 没考虑 policy distribution 的曲率。natural gradient 用 FIM 修正方向:

dF1g

可理解为:在 KL trust region 中选择能最大提升 objective 的方向。

问题是 F 维度等于参数量,无法显式求逆。TNPG 用 conjugate gradient 近似求解线性系统:

Fd=g

并通过 Hessian-vector product 避免显式构造大矩阵。

TRPO 的思想是:用 trust region 保证 policy 更新安全。实际可看成 TNPG 加 line search。它更稳,但仍是二阶优化,计算重:每次更新需要多次 backward pass。

这就是 PPO 被广泛使用的原因:能保留安全更新的直觉,同时只用一阶优化器如 Adam。

6. PPO Clipped Objective

PPO 定义 probability ratio:

rt(θ)=πθ(at|st)πθold(at|st)

advantage:

At=Q(st,at)V(st)

At>0 表示这个 action 比平均好,应提高概率;At<0 表示比平均差,应降低概率。

clipped objective:

LCLIP(θ)=Et[min(rt(θ)At,clip(rt(θ),1ϵ,1+ϵ)At)]

直觉:

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 16 title page(课件原文疑似写成 Lecture 2)

2. Last Lecture: RLHF

3. This Lecture: PPO

4. Policy learning from delayed rewards

5. How to train a policy

6. Policy gradient sensitivity

7. Catastrophic Collapse

8. Catastrophic Collapse

9. Policy gradient direction issue

10. KL Divergence

11. Why KL Divergence

12. Taylor Expansion of KL Divergence

13. FIM Properties

14. Natural Gradient

15. Natural Gradient

16. Natural Gradient Problems

17. Truncated Natural Policy Gradient (TNPG)

18. Natural Gradient Problems

19. TRPO

20. TRPO Problems

21. PPO

22. PPO

23. PPO

24. Extra readings

25. Quiz

Lecture 17: DPO、GRPO 与 Preference Optimization

Part I: Lecture Map

Part II: Detailed DPO / GRPO Notes

1. PPO/RLHF 的复杂性

PPO-based RLHF 需要 policy model、reward model、value/critic model、rollout、advantage estimation、KL control 和工程调参。它强大,但复杂、贵,而且 reward model 可能被 reward hacking。

Lecture 17 的核心问题是:能不能不用显式 RL 和 reward model,直接从 preference data 优化 policy?

2. Advantage 的意义

课件例子:rollout rewards 是 10、100、1000,平均值 370。直接看 reward=10 可能以为是正数、还不错,但 advantage:

10370=360

说明它比平均差。advantage 的作用是给 reward 提供 baseline,让模型知道一个 action 相对当前状态平均水平是好是坏。

3. DPO 的核心推导

KL-regularized RLHF objective 可写成:

maxπEyπ(|x)[r(x,y)]βDKL(π(|x)||πref(|x))

理论最优 policy 满足:

π(y|x)=1Z(x)πref(y|x)exp(1βr(x,y))

因此可以把 reward 写成 policy ratio:

r(x,y)=βlogπ(y|x)πref(y|x)+βlogZ(x)

令当前 policy πθ 近似 π

rθ(x,y)=βlogπθ(y|x)πref(y|x)+βlogZ(x)

把它代入 Bradley-Terry preference probability:

P(ywyl|x)=σ(rθ(x,yw)rθ(x,yl))

logZ(x) 对 winner 和 loser 抵消,于是得到 DPO loss:

LDPO(θ)=logσ(β[logπθ(yw|x)πref(yw|x)logπθ(yl|x)πref(yl|x)])

直觉:提高 winner 相对 reference 的概率,降低 loser 相对 reference 的概率。

4. DPO 的价值和局限

DPO 的工程价值是:像 supervised learning 一样用 preference pair 训练,不需要显式 reward model 和 PPO rollout。课件提到 Zephyr-7B 说明 DPO 可让小模型通过高质量偏好训练获得强对话能力。

局限:DPO 依赖严格 paired preference data;如果真实数据只有 thumbs up/down,就需要 KTO 等扩展。

5. GRPO:不用 critic 的 group baseline

PPO 用 critic/value model 估计 advantage,成本高。GRPO (Group Relative Policy Optimization) 对同一个 query 采样 G 个回答,用这一组回答的平均 reward 作为 baseline:

Ai=ri1Gj=1Grj

这样不需要与 policy 同规模的 critic model。它尤其适合数学/推理任务中同一题可采多条解答并比较。

6. Extensions: KTO, SimPO, DAPO

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 17

2. Limitations of RL + Reward Model

3. RLHF with PPO can be quite complex

4. Why using advantages

5. DPO Motivation

6. Solve optimization objective of RLHF

7. Solve the optimization objective of RLHF

8. Solve the optimization objective of RLHF

9. Solve the optimization objective of RLHF

10. Solve the optimization objective of RLHF

11. Define RM by policy

12. Bradley-Terry Model can help

13. Put RM definition into Bradley-Terry Model Loss

14. DPO Effect

15. GRPO Motivation

16. GRPO Loss

17. Industry: PPO vs DPO

18. DPO Extension 1: Kahneman-Tversky Optimization (KTO)

19. DPO Extension 2: Simple Preference Optimization (SimPO)

20. GRPO Extension 1: DAPO

21. Quiz

Lecture 18: Synthetic Data:生成、评估、可靠性与局限

Part I: Lecture Map

Part II: Detailed Synthetic Data Notes

1. 为什么需要 Synthetic Data

LLM 消耗的数据规模增长很快。课件提到 Llama 3、Qwen2.5 都是万亿 token 级别训练,而真实世界高质量公开文本增长更慢。简单重复已有数据在早期有用,但重复次数越多,收益越快下降。

synthetic data 的动机包括:

2. Synthetic Data 的类型

课件列出几类:

这些数据分别服务 SFT、reward model、DPO/GRPO、evaluation 等阶段。

3. 主要合成方法

Prompting a teacher LLM:用强 teacher model 生成 labels 或 responses,训练 student model;本质上常和 distillation 相连。

Retrieve and transform:先检索真实文档或数据集,再改写为目标任务格式。优点是 grounded,缺点是依赖检索质量。

Extract and rewrite:从网页中抽取有用 QA 或内容,过滤低质量样本,再重写成统一 instruction-response 格式。

Rephrasing:重写表达但尽量保留知识,提升格式和多样性;风险是语气变得更像 teacher model。

Knowledge graph extraction:从结构化知识中生成自然语言样本,适合私有/领域数据;风险是 relation extraction 或 generation 出错。

AI rating / hybrid feedback:让系统判断哪些样本交给人、哪些交给 AI,以节省成本。

4. Self-Instruct、Self-Guide、Evol-Instruct、Multi-agent

Self-Instruct 从少量 seed tasks 扩展出大量新任务。优点是便宜、规模大;缺点是 seed 质量决定上限,生成任务可能表面多样但实际浅。

Self-Guide 增加结构化示例和过滤,让生成更可控。

Evol-Instruct 让任务逐步变难,例如 adding constraints、deepening、increasing reasoning、complicating input。它适合训练复杂指令、代码和数学能力,但任务可能演化得不现实或过难。

Multi-agent 方法让多个 agent 相互批评和修改,可以减少单一模型偏见,但也可能互相强化错误,计算成本高。课件中的“高中是否减少历史课”例子说明,多 agent 反馈可能把同一个价值立场越推越偏。

5. Synthetic Data Evaluation

Correctness (正确性):回答是否遵循指令、代码是否能执行、自由文本是否可由 LLM-as-a-judge 或规则检查。

Complexity (复杂度):是否覆盖难题,而不是只生成简单题。可看 CoT steps、约束数、领域知识深度。

Diversity (多样性):self-BLEU 越高通常表示样本越相似;Vendi Score 用 similarity matrix 的谱/熵估计集合中“有效不同样本数”。

Fidelity (忠实性):合成数据是否忠于源事实。课件例子中,知识库只说 Penicillin treats Bacterial infections,若生成回答解释 PBP 机制,就是引入了未给出的额外事实。

6. 三个核心风险

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 18

2. LLM’s training data

3. Running out of training data

4. Data synthesis: motivation

5. Data synthesis: motivation

6. Data synthesis: motivation

7. Reliability concerns

8. Alignment effectiveness

9. Data synthesis for evaluation

10. Type of synthetic data

11. Type of synthetic data

12. Data synthesis methods: prompting a teacher LLM

13. Data synthesis methods: retrieve and transform

14. Data synthesis methods: extract and re-write

15. Data synthesis methods: extract and re-write

16. Data synthesis methods: rephrasing

17. Data synthesis: extracting from knowledge graphs

18. Data synthesis: extracting from knowledge graphs

19. Data synthesis methods: AI rating

20. Data synthesis methods: prompting a teacher LLM

21. Data synthesis methods: self-instruct

22. Data synthesis methods: self-instruct

23. Data synthesis methods: self-guide

24. Data synthesis methods: self-guide

25. Data synthesis methods: Evol-instruct

26. Data synthesis methods: Evol-instruct

27. Data synthesis methods: mutli-agent methods

28. Data synthesis methods: mutli-agent methods

29. Synthetic data evaluation: correctness

30. Synthetic data evaluation: correctness

31. Synthetic data evaluation: complexity

32. Synthetic data evaluation: diversity

33. Synthetic data evaluation: diversity

34. Synthetic data evaluation: diversity

35. Synthetic data evaluation: fidelity

36. Synthetic data evaluation: fidelity

37. Limitation of synthetic data

Lecture 19: Scaling Laws、FLOPs、Kaplan 与 Chinchilla

Part I: Lecture Map

Part II: Detailed Scaling Law Notes

1. Scaling 的三个变量:N、D、C

Scaling 不是单纯把模型变大,而是在三个资源之间平衡:

课件核心关系:

C6ND

如果 compute budget C 固定,增大 N 通常意味着减小 D,反之亦然。真正的问题是:固定预算下,钱该花在更大模型,还是更多数据?

2. FLOPs 基础

矩阵-向量乘法 ARm×nxRn 需要约:

2mn

其中乘法和加法各算一个 FLOP。

矩阵乘法 ARm×nBRn×p 需要约:

2mnp

训练中 backward pass 通常约为 forward pass 的两倍,所以一次完整训练 step 可粗略看作 forward + backward:

2ND+4ND=6ND

这只是估算,实际还会受到 softmax、LayerNorm、communication、memory bandwidth、checkpointing、data loading、OOM recovery 等影响。

3. Transformer 参数量估计

课件给出 Transformer 参数估计形式:

N12×nlayers×dmodel2+(nvocab+npos)×dmodel

前半部分是非 embedding 参数,后半部分是 token/position embeddings。实际模型还会因 FFN ratio、bias、normalization、tie embeddings 等细节略有差异。

4. Kaplan Scaling Law

Kaplan 发现 training/test loss 随 model size、data、compute 呈 predictable power-law。直觉是:更大模型 data efficiency 更高,能从同样数据中提取更多 pattern。

power-law 的意义是:在多个数量级上,loss 可以用较平滑的曲线预测。这让研究者可用小规模实验外推大规模训练趋势。

5. Chinchilla:Compute-optimal 不是越大越好

Chinchilla 的关键结论是:很多大模型参数太多、数据太少,即 data-undertrained。固定 compute 下,较小模型 + 更多 tokens 可能优于更大模型 + 较少 tokens。

课件例子:Gopher 280B 参数但 token 不足;Chinchilla 70B 参数配更多数据,在相似 compute 下表现更好。

IsoFLOP curves 的思想:固定不同 FLOPs C,扫描 model size,找每个 compute budget 下的 optimal ND

6. Scaling Law 的变体和限制

变体:

限制:

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 19

2. Motivation of Scaling laws

3. Model Size vs Accuracy

4. Motivation of Scaling laws

5. What is Scaling

6. Constraints of Real world

7. FLOPs

8. FLOPs: Matrix-vector Multiplication

9. FLOPs: Matrix Multiplication

10. FLOPs: Matrix Multiplication

11. FLOPs: Matrix Multiplication

12. Transformer FLOPs

13. Calculating Transfomer’s N

14. Calculating Transfomer’s N

15. Calculating Transfomer’s C

16. Calculating Transfomer’s C

17. Calculating Transfomer’s C

18. Kaplan’s scaling laws

19. Kaplan’s scaling laws

20. Kaplan’s scaling laws

21. Chinchilla’s scaling law

22. Chinchilla’s scaling law

23. Chinchilla’s scaling law

24. Kaplan or Chinchilla?

25. Variants of scaling laws

26. Variants of scaling laws

27. Variants of scaling laws

28. Limitations of Scaling Laws

29. Why inverse scaling

30. Limitations of Scaling Laws

31. Quiz

Lecture 20: LLM Inference、KV Cache、Memory Wall、PagedAttention、StreamingLLM

Part I: Lecture Map

Part II: Detailed LLM Inference Systems Notes

1. Autoregressive Decoding 为什么慢

LLM 生成是逐 token 的:

wtPθ(wt|w<t)

naive decoding 每生成一个新 token 都重新计算全部历史 token 的 Key/Value,造成大量重复。生成 n 个 token 时,重复历史计算会近似形成 quadratic growth。

KV cache 用 memory 换 time:历史 token 的 K,V 只算一次,后面直接读取。

2. KV Cache

对最新 token 的 query qt,只需和缓存中的历史 keys 做 attention:

Attention(qt,Kt,Vt)=softmax(qtKtTdk)Vt

KV cache size 公式:

SizeKV=Batch×SeqLen×2×Layers×Heads×Dim×Bytes

其中 2 表示 K 和 V 两套矩阵;Bytes 对 FP16 通常是 2。注意模型 weights 固定,但 KV cache 随 sequence length 和 batch size 线性增长,长上下文 OOM 往往是 cache 造成的。

3. Prefill vs Decode

Prefill:处理完整 prompt,建立 initial cache。prompt tokens 可以并行,GPU 利用率高,偏 compute-bound。它决定 TTFT:

TTFT=Time To First Token

Decode:每次只生成一个 token。每步都要读取整个 KV cache,GPU core 常等 memory transfer,偏 memory-bandwidth bound。它决定 TPOT:

TPOT=Time Per Output Token

用户觉得慢,往往是 TPOT 高,而不是 prefill 慢。

4. Memory Wall

硬件 compute FLOPS 增长很快,但 memory bandwidth 跟不上。decode 时大量时间花在从 HBM 读取 KV cache,而不是做矩阵乘法。这就是 memory wall

序列越长,KV cache 越大:

KV memoryL

因此 long-context serving 的瓶颈不只是算力,更是显存容量和带宽。

5. FlashAttention:online exact softmax

FlashAttention 的思想是 tiling:不把完整 attention matrix 写入显存,而是 block-by-block 计算 softmax 的分母和 weighted sum。

online softmax 维护 running max 和 denominator,因此不是近似 softmax,而是 exact online computation。它减少 HBM read/write,提升 attention 训练/推理效率。

6. MHA、MQA、GQA

MHA (Multi-Head Attention):每个 query head 有自己的 K/V head,表达力强,但 KV cache 大。

MQA (Multi-Query Attention):多个 query heads 共享一组 K/V,KV cache 压缩最强,但可能损失表达能力。

GQA (Grouped-Query Attention):query heads 分组,每组共享 K/V,是 MHA 与 MQA 的折中,常用于降低 memory bandwidth,同时保留较好质量。

7. PagedAttention 和 Continuous Batching

serving 中每个 request 长度不同。如果为每个 request 按 max length 预留 cache,会有 internal fragmentation;物理显存不连续还会有 external fragmentation。

PagedAttention 把 KV cache 像 OS virtual memory 一样分 block:

这样不同 request 的 KV blocks 可以灵活放置,提高显存利用率。

continuous batching 中,decode 任务可能被别人的 prefill 阻塞,出现 bubbles。chunked prefill 把长 prefill 切成块,让 decode 可以 piggyback,减少 GPU 空转。

8. StreamingLLM and Attention Sink

长上下文超过显存后,简单 sliding window 会丢掉开头 token,模型 perplexity 可能突然崩。StreamingLLM 发现 attention sink:初始 tokens 经常吸收 attention,即使语义不强,也对 softmax 稳定很重要。

解决方法:保留少量初始 sink tokens,加上最近 window tokens:

KV=sink tokens+recent tokens

这样 cache size 固定,同时维持较稳定 attention。

9. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 20

2. Motivation of KV Cache

3. Incremental Attention with Cache

4. What is Key-Value (KV) Cache?

5. The Two Stages of Token Generation

6. Phase 1: Prefill (processing the input)

7. Phase 2: Decode (Generation)

8. The "Memory Wall" in LLMs FLOPs

9. Linear Growth, Massive Impact

10. How big is the KV Cache A batch of 3 sequences. LLM generates a token

11. FlashAttention

12. Optimizing Attention Heads

13. Optimizing Attention Heads

14. The Memory Waste: Why Fragmentation Happens

15. PagedAttention (One request:)

16. PagedAttention (Multi requests:)

17. Bubbles and Preemption in Continuous Batching

18. Chunked prefills with decode-maximal batching

19. Memory Wall in Long Context

20. StreamingLLM: Attention Sink is All You Need

21. StreamingLLM: Attention Sink is All You Need

22. Attention Map

23. Quiz

Lecture 21: LLM Compression:Quantization、Pruning、Distillation

Part I: Lecture Map

Part II: Detailed Compression Notes

1. Compression 要解决什么

scaling law 推动模型变大,但硬件显存、带宽和成本跟不上。70B model 用 FP16 权重约需:

70B×2 bytes=140GB

compression 让模型更便宜地训练/部署,主要方法是:

2. Quantization 的数学映射

quantization 把连续值映射到离散整数。一般形式:

q=clip(round(xS)+Z,qmin,qmax)

dequantization:

x^=S(qZ)

S 是 scale,Z 是 zero-point。symmetric quantization 常令 Z=0;asymmetric quantization 用 zero-point 对齐非对称范围。

bit width 越小,内存越省,但误差越大。课件强调 4-bit 常是大模型 memory/accuracy 的好折中;3-bit 往往会遇到 precision cliff。

3. QAT vs PTQ

Post-Training Quantization (PTQ):训练后直接量化。优点是快、便宜;缺点是低 bit 下容易掉精度。

Quantization-Aware Training (QAT):训练中模拟 quantization error,让模型适应低精度。优点是恢复精度好;缺点是贵,需要数据和训练。

round() 不可微:

ddxround(x)=0almost everywhere

QAT 用 Straight-Through Estimator (STE):forward 用 round,backward 假装它是 identity:

ddxround(x)1

4. LLM Outliers、LLM.int8 和 SmoothQuant

LLM 大模型中会出现 activation outliers:少数维度激活值巨大,而且对 perplexity 很重要。如果用全局 absmax scale,outlier 会把 S 拉大,普通值量化后都变成 0。

LLM.int8 的思想是 mixed precision:大多数普通值用 INT8,少数关键 outlier 用 FP16 保留。

SmoothQuant 观察到 activations 有 outliers,而 weights 更容易量化,于是用 per-channel factor 把量化困难从 activation 平滑迁移到 weight:

Y=XW=(XS1)(SW)

这样 activation 更平滑,weight 吸收 scale 后仍可较好量化。

5. Pruning

pruning 删除冗余参数或结构。

Unstructured pruning:删除单个权重,模型大小可降,但 GPU 很难跳过散乱 0,速度收益有限。

Structured pruning:删除 neuron、channel、attention head 等完整结构,剩余矩阵仍 dense,更容易获得真实 speedup。

activation pruning 不只看 weight magnitude,还看 calibration data 上的 activation。课件例子:

w=[1,2],x=[2,0.1]

内积是:

wTx=12+20.1=2.2

虽然第二个 weight 更大,第一维贡献更大,因为 activation 更大。这就是 WANDA 这类方法要同时看 weight 和 activation 的原因。

6. Iterative Pruning、OBS 和 2:4 Sparsity

iterative pruning 反复执行:

  1. 按重要性删除一部分 block/channel/weight。
  2. fine-tune/retrain 恢复性能。
  3. 重复直到达到 size/accuracy trade-off。

Optimal Brain Surgeon 用 Hessian 估计删除一个参数对 loss 的影响,并更新剩余参数补偿。

2:4 structured sparsity 是硬件友好折中:每连续 4 个值中固定 2 个为 0。NVIDIA Sparse Tensor Core 能利用这种模式加速。

7. Distillation

distillation 用大 teacher model 训练小 student model。hard label 只告诉正确类别;soft distribution 还包含 teacher 的相似性知识:

pi=exp(zi/T)jexp(zj/T)

温度 T>1 会让 distribution 更平滑,提高非目标类别之间的可学习差异,这些小概率就是 dark knowledge

distillation 可让 student 不同架构、参数更少、速度更快;缺点是需要训练 student,且 teacher 输出来源可能涉及数据许可和法律争议。

8. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 21

2. The Efficiency Challenge

3. Numeric formats in computers

4. Mathematical mapping

5. Quantization accuracy cost

6. How to Quantize?

7. Quantization-Aware Training

8. Quantization-Aware Training (QAT)

9. Post-Training Quantization (PTQ)

10. Emergent outliers in LLMs

11. Why LLM has and needs outlier activations?

12. Compression efficiency

13. LLM.int8 (mixed precision quantization)

14. SmoothQuant Optimization

15. Concept of Pruning

16. Activation Pruning

17. Activation Pruning

18. Iterative pruning

19. Iterative pruning

20. Structured Sparsity (2:4)

21. Structured Sparsity (2:4)

22. Concept of Distillation

23. Concept of Distillation

24. Distillation

25. Distillation

26. Distillation: debates and lawsuits

27. Quiz

Lecture 22: Mixture of Experts (MoE)、Routing 与 Sparse Upcycling

Part I: Lecture Map

Part II: Detailed MoE Notes

1. MoE 的目标:参数多,但每次只激活一小部分

dense model 每个 token 都经过所有参数。MoE 的想法是:模型可以拥有很多 experts,但每个 token 只路由到少数 experts,从而提高总参数容量,同时控制 activated FLOPs。

基本形式:

G(x)=softmax(Wgx)

选择 top-k experts:

I=TopK(G(x))

输出是 selected experts 的加权和:

y=iIsiEi(x)

2. Transformer 中的 MoE

Switch Transformer 把标准 FFN 替换成 MoE layer。对每个 token hidden state h

p=softmax(Wrh)

Top-1 routing 时:

MoE(h)=piEi(h)

只有被选中的 expert 处理该 token。attention 层通常仍 dense,MoE 主要替换 FFN,因为 FFN 占 Transformer 计算量很大。

3. Routing Collapse

Top-1 routing 省 FLOPs,但容易 routing collapse:router 总把 token 分给少数 experts,其他 experts 不训练,整体容量浪费。

Top-2 routing 让每个 token 走两个 experts:

auxiliary load-balancing loss 鼓励专家使用更均匀。课件中:

训练时梯度主要通过 Pi 流动,fi 当作常量。

4. 离散路由为什么难训练

expert selection 是 discrete choice,普通 backprop 无法穿过 argmax/top-k。可用近似:

RL routing 的问题是 reward sparse、variance 高。

5. BASE Routing

BASE routing 把 token-to-expert assignment 视为 linear assignment problem,强制每个 expert 接收 T/E 个 tokens,从而严格 load balance。

优点:专家利用均衡。
缺点:assignment 求解昂贵,不适合 autoregressive decoding 中逐 token 生成的场景。

6. MoE 案例:GLaM、DeepSeek、Mixtral、Qwen

课件的共同结论:在相似 activated FLOPs 下,MoE 往往比 dense model 更强。

DeepSeek-MoE 例子:

Mixtral、Qwen MoE 说明 sparse upcycling 可从 dense checkpoint 出发构建 MoE,降低从零训练成本。

7. Sparse Upcycling vs Sparse Splitting

Sparse Upcycling:复制原 dense FFN 形成多个 experts。优点是复用 pretrained knowledge;缺点是总参数按 expert 数增加,存储/通信成本变高。

Sparse Splitting:把原 FFN 切分成多个 experts,总参数量不增加,activated parameters 减少;缺点是每个 expert 容量变小。

8. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 22

2. Motivation of Mixture of Experts

3. Road map of Mixture of Experts

4. Overview of Mixture of Experts

5. Mixture of Experts in LSTM

6. Mixture of Experts in Transformer

7. Routing algorithms — Top 1 routing

8. Routing algorithms — Routing collapse

9. Routing algorithms — Top 2 routing

10. Case of Mixture of Experts

11. Case of Mixture of Experts--DeepSeek

12. Case of Mixture of Experts—DeepSeek

13. Case of Mixture of Experts—DeepSeek

14. MoE training: backprop through expert selection

15. MoE training

16. MoE training

17. Routing algorithms — BASE routing

18. Routing algorithms — BASE routing

19. Routing algorithms — Reinforcement learning

20. Building MoE LLMs

21. Building MoE LLMs—Sparse Upcycling

22. Sparse Upcycling-Mixtral MoE

23. Sparse Upcycling-Qwen MoE

24. Building MoE LLMs—Sparse Splitting

25. models of similar scale

26. Quiz

Lecture 23: Diffusion Models:Forward Process、Reverse Process 与 DDPM

Part I: Lecture Map

Part II: Detailed DDPM Diffusion Notes

1. Diffusion 的生成观

Diffusion model 把生成分成两个过程:

它不是一次性生成,而是 iterative refinement。

2. Forward Stochastic Process

常见 DDPM forward step:

q(xt|xt1)=N(1βtxt1,βtI)

定义:

αt=1βtα¯t=s=1tαs

Gaussian 闭包给出直接采样公式:

q(xt|x0)=N(α¯tx0,(1α¯t)I)

等价写法:

xt=α¯tx0+1α¯tϵ,ϵN(0,I)

variance schedule βt 控制每一步加多少噪声。

3. Reverse Process 为什么难

真实 reverse distribution:

q(xt1|xt)

需要数据边缘分布,难以直接计算。但如果额外知道 clean data x0,posterior:

q(xt1|xt,x0)

是 tractable Gaussian。训练时我们知道 x0,所以能推导出可学习目标;推理时不知道 x0,于是用神经网络预测噪声或 reverse mean。

4. 从 ELBO 到 Simplified Loss

diffusion 最大化 log-likelihood 的 variational lower bound (ELBO)。DDPM 推导中,固定 variance 后,高斯 KL 可化为 mean 的 L2 距离。进一步发现预测噪声效果好,于是常用 simplified loss:

Lsimple=Et,x0,ϵϵϵθ(xt,t)2

这就是“训练 diffusion model 可归约为预测噪声”的考试重点。

5. Reverse Mean

如果模型能预测噪声 ϵθ(xt,t),就能估计 x0

x^0=xt1α¯tϵθ(xt,t)α¯t

再用 posterior mean 公式得到反向采样均值。直觉是:模型不是直接画图,而是在每个噪声级别估计“当前噪声是多少”,然后把它减掉。

6. U-Net、Time Embedding、Training/Sampling

U-Net 通过 downsample/upsample 和 skip connections 同时保留细节与全局结构。time embedding 告诉模型当前噪声级别 t,因为不同 t 的 denoising 难度和策略不同。

训练算法:

  1. 采样 clean data x0
  2. 采样 timestep t
  3. 采样 noise ϵ
  4. 构造 xt
  5. 训练 ϵθ(xt,t) 预测 ϵ

采样算法:

  1. xTN(0,I) 开始。
  2. t=T,,1 逐步用模型预测噪声并采样 xt1
  3. 得到 x0

7. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 23

2. GPT: generative pretrained transformer(only?)

3. Generative Models Overview

4. Iterative Refinement

5. The Forward Stochastic Process

6. Mathematical Formulation of the Forward Process

7. Analyzing Stochastic Degradation

8. Variance Schedules

9. Deriving a key property of forward noising

10. Bayesian Inference for the Reverse Process

11. Objectives and Training

12. Objectives and Training

13. Bayesian Challenges

14. Tractable Posterior via Clean data Conditioning

15. Deriving the Tractable Posterior Mean

16. Substituting to derive

17. Deriving the Reverse Mean

18. The Simplified Loss

19. U-Net and Time Embeddings

20. Training Algorithm

21. Sampling Algorithm - Generation

22. Case Study - CIFAR-10 Progressive Generation

23. Quiz

Lecture 24: Score-Based Diffusion、Text Diffusion 与 Block Diffusion

Part I: Lecture Map

Part II: Detailed Score / Text Diffusion Notes

1. Score Function

score-based modeling 学的是数据分布 log-density 的梯度:

score(x)=xlogp(x)

这个向量指向概率密度上升最快的方向,也就是把 noisy sample 推回高概率数据流形的方向。denoising 可以理解成沿 score field 往真实数据分布移动。

2. Langevin Dynamics

如果已知 score,可从随机点开始迭代采样:

xk+1=xk+ηxlogp(xk)+2ηzk

其中 zkN(0,I)。第一项把样本推向高密度区域,第二项保留随机探索。

实际不知道 p(x),所以训练神经网络 sθ(x) 近似 score。

3. Denoising Score Matching

直接学习 xlogp(x) 很难。score matching 通过给 clean data 加噪得到 xt,条件分布的 score 可计算:

xtlogq(xt|x0)

对 Gaussian perturbation:

q(xt|x0)=N(x0,σ2I)

有:

xtlogq(xt|x0)=xtx0σ2

于是训练目标可让 sθ(xt,t) 拟合这个方向。它和 DDPM 预测噪声本质相通。

4. 为什么 NLP 上 diffusion 更难

图像像素是连续变量,有自然距离和局部结构;文本 token 是离散 vocabulary:

wiV

vocabulary 中 token 没有天然几何距离。随便替换 token 可能破坏语法和语义。因此 text diffusion 要么在 discrete token space 设计 transition matrix,要么把 token 映射到 continuous embedding/latent space。

5. Discrete Text Diffusion

离散扩散用 transition matrix 替代 Gaussian kernel:

xt=Qtxt1

其中 xt 可是 token distribution / one-hot vector。常见 forward step:

训练 reverse model 时,用 Bayes rule 写 forward posterior,再用 categorical cross-entropy 学习反向去噪。

6. Continuous Latent Diffusion for Text

Diffusion-LM 把 token sequence 映射到 continuous embedding sequence:

wieiRd

然后在 embedding space 做 Gaussian diffusion。这样有距离和方向,适合 gradient-based denoising。最后需要把 continuous vectors rounding / decoding 回 discrete tokens。

7. Controllable Generation

如果想控制文本属性 c,目标是从 posterior 生成:

p(x|c)p(c|x)p(x)

在 diffusion 每一步中,可以用 classifier 或 discriminator 提供梯度,引导 sample 满足控制条件。课件中的 FUDGE 和 controlled text generation 体现了这种思路。

8. Block Diffusion

纯 discrete diffusion 可能固定长度,且不容易像 autoregressive model 一样复用 KV cache。Block Diffusion 在 AR 和 diffusion 之间折中:按 block 生成或修正,试图结合 diffusion 的 self-correction 和 AR 的可扩展推理。

9. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 24

2. Score-Based Perspective: The Score Function

3. Score-Based Perspective: The Score Function

4. Score-Based Perspective: The Score Function

5. Deriving

6. Langevin Dynamics for inference (reverse process)

7. Unified Framework: Denoising vs. Score Matching

8. Why Diffusion for NLP?

9. Advanced Diffusion: From Images to Text

10. Diffusion of text samples

11. Need to be careful about text perturbations

12. From Gaussian Kernels to Transition Matrices

13. How to Forward Step Works

14. The Forward Posterior in Discrete Space

15. Diffusion in Continuous Latent Spaces

16. Solution

17. How to control our text generation?

18. Deriving

19. How to train a classifier

20. Experiment

21. Case Study: Block Diffusion

22. Autoregressive vs. Diffusion

Lecture 25: Agentic Systems:Memory、RAG、Reflection、Tools 与 MCP

Part I: Lecture Map

Part II: Detailed Agentic System Notes

1. Agentic System 是 LLM 加上可行动的循环

plain LLM 通常是一次输入、一次输出。agentic system 把 LLM 放进一个反复执行的 loop:

  1. 读取任务和环境状态。
  2. 规划下一步。
  3. 调用工具或输出动作。
  4. 观察结果。
  5. 反思并修正。

所以 agent 不只是 model,而是 LLM + memory + tools + environment + feedback + control flow。

2. LLM vs Agentic System

LLM 更像语言模型本体,擅长根据上下文生成文本。agentic system 面向任务完成,常需要:

课件中的 robotics、电力交易等例子说明:agent 的 action 会改变外部世界,不只是写回答。

3. Context Engineering and Memory

context engineering 是决定把什么信息放入 prompt/context:

memory 可分为短期上下文和长期记忆。长期 memory 保存偏好、项目背景、常用路径、错误经验等;但 memory 也可能过期或错误,所以需要检索、更新和冲突处理。

4. RAG

Retrieval-Augmented Generation (RAG) 用外部文档补充模型知识:

  1. Indexing:切块、embedding、建索引。
  2. Retrieval:根据 query 找 top-k chunks。
  3. Generation:把 chunks 放进 context,让模型基于证据回答。

RAG 的价值:

RAG 的风险:

5. Reflection and LLM-as-a-judge

reflection 让 agent 检查自己的计划和输出。它可以发现格式错误、遗漏步骤、代码失败、事实不一致。

LLM-as-a-judge 是常见反思机制:让另一个或同一个模型评价回答质量。但 judge 也可能偏见、过度自信或被 prompt 误导,所以对高风险任务要结合规则、测试和外部验证。

6. Tools

tools 让模型把语言决策变成外部动作,例如:

工具调用的核心不是“模型会说要做什么”,而是系统真的执行动作并返回 observation。agent 的可靠性取决于工具权限、错误处理和验证闭环。

7. MCP and Collaboration

MCP 试图给模型和外部服务提供统一连接协议。若有 N 个模型和 M 个工具/服务,逐一适配需要:

N×M

通过统一协议,可降为:

N+M

collaboration 则强调 agent 与人类或其他 agent 协作:人类给目标、约束和反馈,agent 做检索、执行、检查和迭代。

8. Exam Focus

Part III: Concept Coverage from Lecture Materials

1. AIAA 4051 Lecture 25

2. Everyone is talking about agent

3. What is an agentic system

4. Comparing LLM and agentic systems

5. Agentic system examples

6. Agentic system for robotics

7. Agentic system for electricity trading

8. Comparing agentic system and computers

9. Context engineering

10. Memory

11. Memory examples in Codex

12. RAG (Retrieval-Augmented Generation)

13. Reflection

14. Reflection: LLM-as-a-judge

15. Tools

16. Tools

17. Tools

18. Collaboration

Formula Cheat Sheet / 公式速查表

Probability and MLE

P(A|B)=P(AB)P(B)P(B|A)=P(A|B)P(B)P(A)θ^i=cin

n-gram

P(w1,,wn)=iP(wi)P(wi|wi1)=Count(wi1,wi)Count(wi1)PL(w2|w1)=c(w1,w2)+1c(w1)+|V|

HMM

P(Q)=πq1t=2Taqt1,qtP(O|Q)=t=1Tbqt(ot)αt(j)=iαt1(i)aijbj(ot)βt(i)=jaijbj(ot+1)βt+1(j)vt(j)=maxivt1(i)aijbj(ot)γt(i)=αt(i)βt(i)P(O)ξt(i,j)=αt(i)aijbj(ot+1)βt+1(j)P(O)

CFG / PCFG

G=(N,Σ,R,S)ABC,AaCYK=O(n3|R|)βA(i,j)=ABCk=ij1P(ABC)βB(i,k)βC(k+1,j)

Transformer / Training / Systems

Attention(Q,K,V)=softmax(QKTdk)VLAR(θ)=Dtlogpθ(wt|w<t)LSFT(θ)=tlogpθ(yt|x,y<t)P(ywyl|x)=σ(r(x,yw)r(x,yl))SizeKV=Batch×SeqLen×2×Layers×Heads×Dim×2 bytesLdiffusion=Et,x0,ϵϵϵθ(xt,t)2score(x)=xlogp(x)