Files
2026_DesignAI/04-transformer/03.1-attention.md
T
pengxiao e58b95d227 初始化:从 docx 拆分为独立 Markdown 章节
将《设计人工智能:基础与应用》拆分为 38 个 Markdown 文件,
按 11 个部分(上篇6部分+下篇5部分)+ 3 个附录组织。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 10:32:58 +08:00

157 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
### 学习目标
理解Self-Attention的动机和原理
掌握Q、K、V的计算过程
了解Multi-Head Attention的优势
### 为什么需要Attention
#### 序列标注问题
`输入序列:``x₁, x₂, ..., xₙ (N``个元素``)`\
`输出序列:``y₁, y₂, ..., yₙ' (N'``个元素``)`
传统方法 (RNN/FCN): - 固定窗口大小 - 长距离依赖丢失 - 难以并行计算
Self-Attention - 每个元素都能关注所有元素 - 直接建模任意距离依赖 - 可以并行计算
### Self-Attention原理
#### 核心思想 {#核心思想-1}
为每个输出元素,计算输入序列中所有元素的相关性:
`对于每个位置``i```\
` yᵢ = Σ (``注意力权重`` × ``对应输入值``)`
#### Q、K、V计算
`输入``X → ``三个线性变换`\
` ↓`\
`Q (Query): "``我想找什么``"`\
`K (Key): "``我有什么标签``"`\
`V (Value): "``我的实际内容``"`
#### 注意力分数计算
`1. ``计算相似度:``Score = Q × Kᵀ`
`2. ``缩放:``Score = Score / √dₖ`
`3. ``Softmax````Weight = ``softmax``(Score)`
`4. ``加权求和:``Output = Weight × V`
#### 直观理解 {#直观理解-2}
`查询:``"``苹果``"`\
` ↓`\
`与所有``Key``计算相似度`\
` ↓`\
`权重高的``Key``对应``Value``贡献更大`\
` ↓`\
`输出:融合上下文的``"``苹果``"``表示`
### Multi-Head Attention
单头 vs 多头
**单头注意力**
`一组``Q``、``K``、``V → ``一个注意力表示`
**多头注意力**
`多组``Q``、``K``、``V → ``多个注意力表示`` → ``拼接`
#### 多头优势
---------------------
头 关注内容
-------- ------------
Head 1 语法关系
Head 2 语义指代
Head 3 长距离依赖
... ...
---------------------
多头让模型从不同角度理解序列。
### Positional Encoding
#### 问题
Self-Attention本身是**置换不变**的:
`Attention(``[A, B, C]) = Attention([B, A, C])`
但序列位置很重要!
#### 解决方案
添加位置信息:
`输入`` = X + ``PositionalEncoding`
常用方法: - 正弦/余弦位置编码 - 可学习位置编码
### Self-Attention vs CNN
感受野对比
------------------------------------
层级 CNN Self-Attention
------ ------------ ----------------
单层 局部感受野 全局感受野
深层 逐层扩大 始终全局
------------------------------------
计算复杂度
--------------------------------------
操作 CNN Self-Attention
-------- ------------ ----------------
复杂度 O(k²·C) O(n²·d)
n 图像尺寸 序列长度
k 卷积核大小 \-
--------------------------------------
### 思考与练习
1.为什么Attention需要Scaling (除以√dₖ)
2.Multi-Head Attention中,头数越多越好吗?
3.Self-Attention如何应用在图像上?
### 关键术语
------------------------------------------------------
中文 英文 说明
---------- -------------------- ----------------------
查询 Query 查询向量
键 Key 键向量
值 Value 值向量
缩放点积 Scaled Dot-Product 注意力计算方式
掩码 Mask 屏蔽某些位置的注意力
------------------------------------------------------
### 延伸阅读
[Attention Is All You Need](https://arxiv.org/abs/1706.03762)
[The Illustrated Transformer](https://jalammar.github.io/illustrated-transformer/) \# 03.2 Transformer架构