为什么需要 Transformer?
在 Transformer 出现之前,NLP 领域主要依赖 RNN 和 LSTM。但这些架构存在一个根本性问题:无法并行计算。
自注意力机制(Self-Attention)
python
import torch
import torch.nn.functional as F
def self_attention(Q, K, V, mask=None):
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(d_k))
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
return torch.matmul(attention_weights, V)import torch
import torch.nn.functional as F
def self_attention(Q, K, V, mask=None):
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(d_k))
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
return torch.matmul(attention_weights, V)
多头注意力
单头注意力可能只关注一种关系模式。多头注意力让模型同时从多个"表示子空间"中学习。
每个注意力头可以学会关注不同的语言特征——一个头可能关注语法结构,另一个关注语义关系。
位置编码 · 残差连接 · 层归一化
Transformer 没有循环结构,需要显式告知位置信息。原始论文使用正弦和余弦函数。