深入理解 Transformer 的注意力机制

背景

自 2017 年 Vaswani 等人提出 Transformer 以来,注意力机制已成为 NLP 领域最重要的技术之一。

数学原理

注意力机制的核心是 Scaled Dot-Product Attention:

$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$

代码实现

import torch
import torch.nn.functional as F

def scaled_dot_product_attention(Q, K, V):
    d_k = Q.size(-1)
    scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
    attention_weights = F.softmax(scores, dim=-1)
    return torch.matmul(attention_weights, V)

注意力变体

  1. Multi-Head Attention - 并行多个注意力头
  2. Linear Attention - 线性复杂度
  3. Sparse Attention - 稀疏模式

实践技巧

  • 适当增加 head 数量通常能提升模型性能
  • 注意力 dropout 是有效的正则化手段
  • 位置编码对结果有显著影响