Skip to content

Attention 机制 (Attention)

一句话定义:Attention 机制是一种让模型在处理数据时,能够动态关注重要部分并忽略无关部分的机制。它通过计算查询 (Query)键 (Key) 的相似度,来决定从值 (Value) 中提取多少信息。

它是 Transformer 架构的核心,解决了长序列依赖问题。


想象你在图书馆查资料写论文。

  • Query (Q): 你手里的研究课题(比如”人工智能历史”)。
  • Key (K): 书架上每本书的标题/标签
  • Value (V): 书里的具体内容
  • Attention Score: 书名和课题的匹配度。

过程

  1. 你拿课题 (Q) 去扫视书架上的标签 (K)。
  2. 发现《深度学习》这本书标签匹配度很高 (High Score),《烹饪指南》匹配度很低 (Low Score)。
  3. 你把《深度学习》的内容 (V) 拿出来细读,把《烹饪指南》忽略。
  4. 最后你获得的知识 (Output),是所有书内容的加权总和(重点是匹配度高的书)。


🎯 交互演示:Attention 热力图 (Interactive)

Section titled “🎯 交互演示:Attention 热力图 (Interactive)”

观察每个词对其他词的注意力权重分布,理解 Self-Attention 的工作原理。

🎯 Self-Attention 热力图

(标准)
The
cat
sat
on
the
mat
K
The
0.20
0.17
0.17
0.16
0.15
0.15
Q
cat
0.17
0.19
0.17
0.16
0.16
0.16
sat
0.16
0.17
0.19
0.17
0.16
0.16
on
0.16
0.16
0.17
0.19
0.17
0.16
the
0.15
0.15
0.16
0.17
0.19
0.17
mat
0.15
0.15
0.16
0.16
0.17
0.20
Attention(Q, K, V) = softmax(QKT /√dk) × V
QKT = 相似度分数 | √dk = 缩放因子 (8) | softmax = 归一化为概率

💡 点击左侧 Query 词高亮其注意力分布 | 调节 Temperature 观察分布变化


Scaled Dot-Product Attention 的核心公式:

Scaled Dot-Product Attention
Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
  • Q,K,VQ, K, V: 输入向量经过线性变换后的矩阵。
  • QKTQK^T: 计算 Query 和 Key 的点积(相似度)。
  • dk\sqrt{d_k}: 缩放因子,防止点积过大导致 Softmax 梯度消失。
  • softmax\text{softmax}: 将相似度归一化为概率(权重和为 1)。
  • V\cdot V: 根据权重对 Value 进行加权求和。

多头注意力让模型同时关注不同的语义空间(如一个头关注语法,一个头关注指代)。

多头注意力公式
MultiHead(Q,K,V)=Concat(head1,...,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, ..., \text{head}_h)W^O

其中每个 head:headi=Attention(QWiQ,KWiK,VWiV)\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)

  • hh: 头的数量(通常 8 或 16)
  • WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V: 每个头的投影矩阵,形状 [dmodel,dk][d_{model}, d_k]
  • WOW^O: 输出投影矩阵,形状 [hdk,dmodel][h \cdot d_k, d_{model}]
  • dk=dmodel/hd_k = d_{model} / h(如 512/8 = 64)

import torch
import torch.nn.functional as F
import math
def scaled_dot_product_attention(query, key, value, mask=None):
d_k = query.size(-1)
# 1. 计算相似度分数 QK^T / sqrt(d_k)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
# 2. 掩码 (可选,用于 Decoder 屏蔽未来信息)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# 3. Softmax 归一化 -> 得到 Attention 权重
p_attn = F.softmax(scores, dim=-1)
# 4. 加权求和 -> p_attn * V
return torch.matmul(p_attn, value), p_attn
# 示例数据
d_model = 512
heads = 8
batch_size = 1
# 假设已经投影好的 Q, K, V
# [Batch, Seq_Len, d_model]
q = torch.randn(batch_size, 10, d_model)
k = torch.randn(batch_size, 10, d_model)
v = torch.randn(batch_size, 10, d_model)
output, weights = scaled_dot_product_attention(q, k, v)
print(f"Output shape: {output.shape}")
print(f"Weights shape: {weights.shape}")

🔍 Attention 计算流程 (Step-by-Step)

Section titled “🔍 Attention 计算流程 (Step-by-Step)”

逐步观察 Self-Attention 的完整计算过程:Q/K/V 投影 → 分数计算 → Softmax → 输出。

🔍 Attention 流动可视化

输入嵌入: 每个 token 转换为向量
输入 Tokens
The
cat
sat
公式: Attention(Q,K,V) = softmax(QK^T/√d_k)V

💡 点击步骤查看计算流程 | 悬停 token 查看注意力分布




The Illustrated Transformer

Jay Alammar 的可视化讲解

阅读

Attention is All You Need

原论文 (Google 2017)

论文

3Blue1Brown - Attention

可视化讲解 Attention 原理

观看