如何提取并可视化多头注意力权重?
解读
国内面试官问“多头注意力权重”时,通常想确认三件事:
- 你是否真的在 PyTorch 里写过 Transformer,而不是只会调库;
- 你是否知道“权重”在代码里到底对应哪一段张量;
- 你是否能把高维张量变成人类可读的图,并解释它。
因此,回答必须给出“可落地的 10 行以内核心代码 + 可视化套路”,并说明多头与单头的区别、attention dropout 对可视化的影响、以及生产环境如何缓存权重。
知识点
- 多头缩放点积注意力公式
MultiHead(Q,K,V)=Concat(head1,...,headh)WO,其中 headi=Attention(QWiQ,KWiK,VWiV)
Attention(Q,K,V)=softmax(QK^T / √d_k)V - 权重张量形状
训练阶段: (batch, num_heads, seq_len, seq_len)
推理阶段:若开启 key_padding_mask,需先 mask 再 softmax,否则权重和不为 1 - 提取位置
自定义层:在 forward 里 return attn_weights
nn.MultiheadAttention:设置 need_weights=True,返回 (out, attn_weights) - 可视化要点
取单样本、单头或平均头 → 转 numpy → 上三角或下三角可选掩码 → 用 matplotlib/seaborn 画热力图;
若序列长度>512,先做 16×16 分块平均,再放大,否则 Jupyter 容易卡死 - 中文场景踩坑
中文 tokenizer 可能把“字”与“词”混用,导致 x 轴标签过密;建议用 tokenizer.convert_ids_to_tokens 后,间隔采样显示 - 面试加分项
TorchScript 导出时 attn_weights 会丢,需注册 hook;
生产环境用 TensorBoard 的 add_image('attn', heatmap) 可实时远传,避免手动存图
答案
下面给出“最小可运行示例”,可直接在面试白板或 VSCode 里敲出来,10 行核心代码,兼顾“提取”与“可视化”。
import torch, torch.nn as nn, matplotlib.pyplot as plt, seaborn as sns
# 1. 构造 4 头 8 维的 MHA
mha = nn.MultiheadAttention(embed_dim=8, num_heads=4, batch_first=True)
# 2. 伪造 1 条长度 10 的样本
x = torch.randn(1, 10, 8) # (batch, seq, embed)
# 3. 前向并强制返回注意力权重
out, attn = mha(x, x, x, need_weights=True) # attn: (batch, seq, seq)
# 4. 取 0 号样本、0 号头
head0 = attn[0] # (10, 10)
# 5. 可视化
plt.figure(figsize=(4,3))
sns.heatmap(head0.detach().numpy(), cmap='Blues')
plt.title("Head-0 Attention Weights")
plt.xlabel("Key"); plt.ylabel("Query")
plt.tight_layout(); plt.show()
面试口述要点:
“第 3 步的 need_weights=True 是关键,否则 PyTorch 默认不返回权重以节省显存;attn 形状是 (batch, seq, seq) 而不是 (batch, num_heads, seq, seq),因为库内部已经平均过头。若想看每一头,需手写 MultiHeadAttention 类,在 softmax 后把 (batch, num_heads, seq, seq) 返回即可。”
拓展思考
- 如何只看“某一层的某一头”?
在 BertEncoder 里给指定层注册 forward_hook,把 layer.attention.self.attn_weights 缓存到 dict,训练完再画。 - 长度可变 batch 如何对齐?
用 attn_weights.masked_fill(~mask, 0) 后再归一化,否则 pad 区权重会乱。 - 生产环境实时可视化?
把 hook 里拿到的 (num_heads, seq, seq) 做 L2 归一化 → 缩放到 0-255 → torchvision.utils.make_grid → TensorBoard add_image,每 100 step 发一次,无需落盘。 - 多头权重能否蒸馏?
可以。取教师模型各头作为 soft label,用 KL 散度让学生模型对应头逼近,比整层蒸馏省 30% 计算量,已在中文 CLUE 小模型上验证。