跳到主要内容

注意力与 Transformer — 动态决定看哪里

这一章讲三件事: 注意力怎么从「打分-加权-混合」三步长出来; 装上可学习投影、多头并排、残差与归一化之后,它怎么变成 Transformer; 以及 ViT 怎么把「图切成词」让同一套架构看图。 主走查是「The teacher praised a student because she improved」里那个 she——它该看谁。

1. 顶层全景

上一章 seq2seq 的死结 本章的解法
───────────────── ────────────
整句压进一个上下文向量 不再只留最后一步:
长句必丢信息 每处理一个词,都能按"相关度"
回看整句的每一个词,各取所需
│ │
▼ ▼
简单翻译句子够用 注意力(2.1) → 可训练版(2.3)
→ 多头+残差+归一化 = Transformer(2.4)
→ 图像切块也能用 = ViT(2.5)

2. 核心原理

2.1 主走查:给「she」找到它的出处

原书的例句:「The teacher praised a student because she improved」—— 「improved」说的是 teacher 还是 student?人一眼看出是 student; 算法要答对,必须建立「she」和句子里其他词的联系,这正是注意力登场的地方1

先分清两个方向:自注意力(句子看自己)和交叉注意力(一句看另一句)。 原书演示用交叉注意力:query(查询)句是上面那句,key(键)句是 「A student asked the teacher to help her improve」2

每个词先变成 300 维的向量——这种「词的数字表示」叫词嵌入(GloVe 是现成的一套,从海量文本的共现统计学来)3。 整句就是一个「每行一个词」的矩阵。然后三步,每步都是具体的矩阵运算:

① 打分:query 句每个词的向量,与 key 句每个词的向量做点积
点积=对齐分数:两个向量方向越一致,分越高;互相垂直,分恰好为 0[^4]
② 缩放+归一化:每个分数除以向量维度的平方根(高维下稳住梯度,故称"缩放点积"),
再过 softmax,变成每行加起来等于 1 的权重
③ 取用:用这行权重去加权混合 key 句的词向量,得到 query 词的新表示
——"she"这一步的新向量里,掺进了大半"student"的成分

(用一个 2 维玩具例子看清点积,下面这些数字是为演示编的:
"she" 的向量 = (1.0, 0.1) "improve" 的向量 = (0.9, 0.0)
"the" 的向量 = (0.1, 1.0)
点积:she·improve = 1.0×0.9 + 0.1×0.0 = 0.90 ← 方向接近,分高
she·the = 1.0×0.1 + 0.1×1.0 = 0.20 ← 几乎垂直,分低)

原书对这套流程的类比一针见血:它就是一次哈希(按「键」找「值」的快速查表)表查询

query 是检索(按条件查找)词,key 是条目名,value 是条目内容;按相似度找到最相关的条目,取出内容4。 「查询/键/值」三件套的名字由此而来。

这版「素注意力」的边界:嵌入和打分全程没有可学习的参数, 注意力热图上「she」确实照亮了「her」「student」, 但那只是 GloVe 通用语义的照妖——比如它也会给没意义的「a↔the」打高分5。 真正的威力要到参数可训练的版本才解锁6

2.2 可训练版:Q、K、V 各自先过一道投影

升级版给三件套各配一个可学习的线性变换(记作 Wq、Wk、Wv): 不直接用词向量(词的那个数字表示),而是「词向量 × Wq」当查询、「× Wk」当键、「× Wv」当值7。 学什么?学「该用什么姿态去问、去被查、去被取」——同一批词, 在不同任务里值得被问的侧面不同。原书点明:这个可训练版就是现代 Transformer 自注意力的骨干8

变体还有加法注意力(查询与键相加过 tanh 再打分):更善于表达复杂关系,但更慢; 点积版快、适合高维——大规模模型几乎都选后者,速度是硬通货9

2.3 装回 seq2seq:上下文向量不再是唯一的记忆

把注意力装进上一章的翻译模型,改动只有一处但效果判若云泥: 解码器每生成一个词,不再只盯着编码器的最终隐藏状态,而是按当前要译的词, 动态回看输入句的不同部分。上一章「长句必丢信息」的死结(「The book that I bought is very interesting」译错)就此解开——需要的词还在原句里,随时可取10。 注意力热图还白送一份对齐(每个输出词该看输入哪个词)可视化:源语言词和目标语言词的对应关系直接看得见。

2.4 Transformer:多头、残差、归一化

Transformer 的定义式结构:一层 = 多头注意力(几组并排、各看各的注意力)+ 前馈(每个位置各自过一遍的小网络)层,外加两种稳定剂。

稳定剂之一是残差连接;之二是层归一化(把每层的数值拉回稳定范围)11。四个零件各司其职:

零件干什么
多头注意力把 Q/K/V 投影成多个低维"头",各看各的,拼回一起——不显著增加参数的前提下,让不同位置的关系从多个角度看12
前馈网络每个位置各自过的两层全连接,做注意力的"后处理"
残差连接每个子层的输出加上子层的输入——梯度有直通车,深层才训得动(第 07 章跳连的同族思想)13
层归一化把每层的数值拉回稳定范围,防训练漂移

Transformer 与 RNN 的本质分野:RNN 沿时间一步一步走,Transformer 一次看全句。 没有循环,就不必等上一步算完——整句并行,长句不慢,这就是它可扩展性的全部来源14。 (「词在句中的先后」这个信息因此丢了,要靠给每个词加上位置编码补回——原书在 ViT 一节演示了 正弦位置编码的完整实现,第 12 章还会再用它编码时间步。) 处理分类任务时用 mask 挡住补齐用的空白符:把它们的注意力分数压到负无穷, softmax 后恰好为零,白拿不到任何注意力15

项目:IMDb 五万条影评(2.5 万训练/2.5 万测试)上做情感分析,transformer 编码器接分类头16

2.5 ViT:图像切块,同一套架构

视觉 Transformer(ViT),Google 2020:既然注意力不关心输入是词还是什么, 那就把图像切成小块(patch),每个块当一个「词」,排成一个「词序」,交给原封不动的 Transformer 编码器17

工程细节有三处值得记。第一,切块嵌入用一个卷积层实现:核大小=步长=块大小, 滑一次正好产出一个块的向量,又快又稳18。 第二,小数据集上 ViT 打不过 CNN:CIFAR-10(6 万张 32×32 图、10 类)上从零训练, 验证准确率到 70% 附近就封顶——注意力自己不会找空间结构,需要喂大数据19。 第三,补救两手:训练时用 CutMix 增广(把一张图的一块剪下来贴到另一张图上, 标签按两块面积比例混合——逼模型别只认最显眼的特征)20; 或者干脆在大数据集上预训练再搬到小任务,威力才真正释放(原书项目的最终形态)21

3. 作者的判断与证据

  • 有证据的:注意力热图(素版)、翻译质量对比(装注意力前后)、IMDb 情感分析、 CIFAR-10 的 70% 封顶与预训练后的提升——全是可复跑的实测。

  • 作者的结构性判断:可训练点积注意力是现代 Transformer 的骨干(引 2.2 节)8; 点积优于加法的理由是算得快(大规模模型的速度刚需)9

  • 历史脉络:注意力 2014 年生于机器翻译(Bahdanau);2017 年 Vaswani 等的 「Attention Is All You Need」把循环和卷积整个扔掉,只留注意力—— 它铺平了 BERT(编码式——专做填空理解——预训练语言模型的代表)的路;

  • GPT(生成式,即负责接着往下写的那类)也出自这篇论文铺的路;ViT(2020)则证明同一架构看得见图22

4. 边界与局限

边界说明
素注意力只是语义照妖镜没有可学参数时,「a↔the」也高亮;威力在可训练版
并行的代价是丢词序位置编码要另加;加法本身又是一组参数
ViT 数据饥渴小数据集从零训必输 CNN;CutMix/预训练是止痛药不是解药
计算量随长度平方涨每个词对全句打分,句子翻倍、打分翻四倍(原书未展开,属书出版后的讨论焦点)
mask 用错=静默泄漏补齐符挡不严,模型学会从「空白的位置」偷看答案

判断(我们的,不是书里的): 原书把注意力讲成「打分-加权-取用」, 把 Transformer 讲成「注意力的堆叠+稳定剂」,这个讲法对读者最友好, 但容易让人低估 2017 年那篇论文的激进程度——它删掉的是「沿时间递推」这个 此前所有序列模型的公共地基,而不只是换了个零件。 读史时要把「改进」和「换地基」分开记账。 如果错,会错在: 如果后续研究发现 Transformer 的优势主要来自工程并行性 而非表达力,那「换地基」的叙事也要相应降权——两种解释目前都有证据。

5. 可带走的

  1. 注意力三步:点积打分 → 缩放+softmax 归一 → 加权取用;类比哈希表查询(Q/K/V);
  2. 素版只反映预训练语义,可训练版(Wq/Wk/Wv)才是主力;
  3. 注意力装进 seq2seq,上下文向量瓶颈解除:每个输出词动态回看全句;
  4. Transformer = 多头注意力+前馈,配残差与层归一化;多头=多个视角;
  5. 并行取代循环:快、可扩展,词序靠位置编码补;
  6. ViT = 图像切块当词:小数据必输 CNN,预训练/CutMix 才能打;
  7. mask 的作用:挡住补齐符,softmax 后归零;
  8. 情感分析是 Transformer 编码器最轻量的试金石:五万影评,正负二分类(二选一的判断)。

6. 原文地图

主题原书章原文位置
she improved 例句Understanding Attentiontext/58-fm-understanding-attention.txt:3(搜「she improved」)
自/交叉注意力Understanding Attentiontext/58-fm-understanding-attention.txt:7(搜「self-attention」)
嵌入与注意力矩阵Understanding Attentiontext/58-fm-understanding-attention.txt:17(搜「attention matrix」)
GloVe 嵌入Understanding Attentiontext/58-fm-understanding-attention.txt:41(搜「GloVe」)
点积=相似度Understanding Attentiontext/58-fm-understanding-attention.txt:61(搜「dot product between the matrices」)
对齐分数与垂直为零Understanding Attentiontext/58-fm-understanding-attention.txt:67(搜「90-degree angle」)
缩放点积Understanding Attentiontext/58-fm-understanding-attention.txt:69(搜「square root of the embedding dimension」)
值加权取用Understanding Attentiontext/58-fm-understanding-attention.txt:75(搜「value embeddings」)
哈希表类比Understanding Attentiontext/58-fm-understanding-attention.txt:101(搜「hash table lookup」)
素版无参数的局限Understanding Attentiontext/58-fm-understanding-attention.txt:146(搜「no learnable weights」)
真正威力在可学习版Understanding Attentiontext/58-fm-understanding-attention.txt:148(搜「true strength of attention」)
Wq/Wk/WvUnderstanding Attentiontext/58-fm-understanding-attention.txt:164(搜「learnable linear transformations」)
Transformer 自注意力骨干Understanding Attentiontext/58-fm-understanding-attention.txt:197(搜「backbone of the self-attention」)
加法注意力与取舍Understanding Attentiontext/58-fm-understanding-attention.txt:209(搜「additive attention」) · text/58-fm-understanding-attention.txt:237(搜「higher computational costs」)
seq2seq 上下文瓶颈Project 8A: Using Attention to Improve Language Translationtext/59-fm-project-8a-using-attention-to-improve-language-t.txt:5(搜「significant information loss」)
动态回看Project 8A: Using Attention to Improve Language Translationtext/59-fm-project-8a-using-attention-to-improve-language-t.txt:7(搜「long-range dependencies dynamically」)
Transformer 并行/多头Project 8B: Performing Sentiment Analysis with a Transformertext/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:3(搜「multi-head attention mechanism」)
多头不加参数增表达力Project 8B: Performing Sentiment Analysis with a Transformertext/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:11(搜「without significantly increasing the parameter count」)
层结构与稳定剂Project 8B: Performing Sentiment Analysis with a Transformertext/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:65(搜「layer normalization」)
IMDb 数据Project 8B: Performing Sentiment Analysis with a Transformertext/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:79(搜「50,000 movie reviews」)
mask 负无穷Project 8B: Performing Sentiment Analysis with a Transformertext/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:231(搜「negative infinity」)
残差+归一化顺序Project 8B: Performing Sentiment Analysis with a Transformertext/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:239(搜「residual connection」)
ViT 2020Project 8C: Classifying Images with a Vision Transformertext/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:3(搜「vision transformer」)
CIFAR-10Project 8C: Classifying Images with a Vision Transformertext/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:11(搜「60,000 full-color images」)
切块与配置Project 8C: Classifying Images with a Vision Transformertext/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:132(搜「64 patches」)
卷积实现切块Project 8C: Classifying Images with a Vision Transformertext/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:138(搜「kernel size and stride equal to the patch size」)
70% 封顶Project 8C: Classifying Images with a Vision Transformertext/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:161(搜「approximately 70 percent」)
CutMixProject 8C: Classifying Images with a Vision Transformertext/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:186(搜「mixed proportionally」)
注意力谱系Seminal Works and Further Readingtext/63-fm-seminal-works-and-further-reading.txt:3(搜「Align and Translate」) · text/63-fm-seminal-works-and-further-reading.txt:7(搜「Attention Is All You Need」) · text/63-fm-seminal-works-and-further-reading.txt:9(搜「16×16 Words」)

Footnotes

  1. 出处:「Understanding Attention」第 3 段(text/58-fm-understanding-attention.txt:3,搜「she improved」)、第 5 段(text/58-fm-understanding-attention.txt:5,搜「ambiguous references」)。

  2. 出处:「Understanding Attention」第 7 段(text/58-fm-understanding-attention.txt:7,搜「self-attention」)、第 13-14 段(text/58-fm-understanding-attention.txt:13,搜「query_sentence」)。

  3. 出处:「Understanding Attention」第 41 段(text/58-fm-understanding-attention.txt:41,搜「GloVe」)。

  4. 出处:「Understanding Attention」第 101 段(text/58-fm-understanding-attention.txt:101,搜「hash table lookup」)。

  5. 出处:「Understanding Attention」第 146 段(text/58-fm-understanding-attention.txt:146,搜「no learnable weights」)。

  6. 出处:「Understanding Attention」第 148 段(text/58-fm-understanding-attention.txt:148,搜「true strength of attention」)。

  7. 出处:「Understanding Attention」第 164 段(text/58-fm-understanding-attention.txt:164,搜「learnable linear transformations」)、第 175-177 段(text/58-fm-understanding-attention.txt:175,搜「Wq」)。

  8. 出处:「Understanding Attention」第 197 段(text/58-fm-understanding-attention.txt:197,搜「backbone of the self-attention」)。 2

  9. 出处:「Understanding Attention」第 237 段(text/58-fm-understanding-attention.txt:237,搜「higher computational costs」)。 2

  10. 出处:「Project 8A: Using Attention to Improve Language Translation」第 5 段(text/59-fm-project-8a-using-attention-to-improve-language-t.txt:5,搜「significant information loss」)、第 7 段(text/59-fm-project-8a-using-attention-to-improve-language-t.txt:7,搜「long-range dependencies dynamically」)。

  11. 出处:「Project 8B: Performing Sentiment Analysis with a Transformer」第 65 段(text/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:65,搜「layer normalization」)。

  12. 出处:「Project 8B: Performing Sentiment Analysis with a Transformer」第 11 段(text/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:11,搜「without significantly increasing the parameter count」)。

  13. 出处:「Project 8B: Performing Sentiment Analysis with a Transformer」第 239-241 段(text/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:239,搜「residual connection」)。

  14. 出处:「Project 8B: Performing Sentiment Analysis with a Transformer」第 3 段(text/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:3,搜「multi-head attention mechanism」)。

  15. 出处:「Project 8B: Performing Sentiment Analysis with a Transformer」第 231 段(text/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:231,搜「negative infinity」)。

  16. 出处:「Project 8B: Performing Sentiment Analysis with a Transformer」第 79 段(text/60-fm-project-8b-performing-sentiment-analysis-with-a-.txt:79,搜「50,000 movie reviews」)。

  17. 出处:「Project 8C: Classifying Images with a Vision Transformer」第 3 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:3,搜「vision transformer」)、第 132 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:132,搜「64 patches」)。

  18. 出处:「Project 8C: Classifying Images with a Vision Transformer」第 138 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:138,搜「kernel size and stride equal to the patch size」)。

  19. 出处:「Project 8C: Classifying Images with a Vision Transformer」第 161 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:161,搜「approximately 70 percent」)、第 7 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:7,搜「unimpressive results」)。

  20. 出处:「Project 8C: Classifying Images with a Vision Transformer」第 186 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:186,搜「mixed proportionally」)。

  21. 出处:「Project 8C: Classifying Images with a Vision Transformer」第 7 段(text/61-fm-project-8c-classifying-images-with-a-vision-tran.txt:7,搜「pretrained on larger datasets」)。

  22. 出处:「Seminal Works and Further Reading」第 3 段(text/63-fm-seminal-works-and-further-reading.txt:3,搜「Align and Translate」)、第 7 段(text/63-fm-seminal-works-and-further-reading.txt:7,搜「Attention Is All You Need」)、第 9 段(text/63-fm-seminal-works-and-further-reading.txt:9,搜「16×16 Words」)。