Week 19: 深度学习补遗:自注意力和Transformer Encoder架构
自注意力机制的基本原理
自注意力(Self-Attention)是Transformer架构的核心组件,用于捕捉输入序列中不同位置间的依赖关系。其核心思想是通过计算查询(Query)、键(Key)和值(Value)之间的相关性,动态生成权重以加权聚合信息。数学表达式为:
$$ \text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V $$
其中,$d_k$是键向量的维度,缩放因子$\sqrt{d_k}$用于防止点积值过大导致梯度消失。
多头注意力机制
多头注意力(Multi-Head Attention)通过并行运行多组自注意力层,增强模型捕捉不同子空间特征的能力。公式如下:
$$ \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)W^O $$
每个注意力头的计算方式为:
$$ \text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V) $$
$W_i^Q, W_i^K, W_i^V$是可学习的投影矩阵,$W^O$是输出投影矩阵。
Transformer Encoder架构
Transformer Encoder由多层编码器堆叠而成,每层包含两个子模块:
- 多头自注意力层:处理输入序列的全局依赖关系。
- 前馈神经网络(FFN):对每个位置的表示进行非线性变换。
两个子模块均采用残差连接(Residual Connection)和层归一化(Layer Normalization),公式为:
$$ \text{Output} = \text{LayerNorm}(x + \text{Sublayer}(x)) $$
代码示例:实现Transformer Encoder
以下代码使用PyTorch实现一个简化版Transformer Encoder层:
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.d_model = d_model
self.num_heads = num_heads
self.head_dim = d_model // num_heads
self.qkv_linear = nn.Linear(d_model, 3 * d_model)
self.output_linear = nn.Linear(d_model, d_model)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
qkv = self.qkv_linear(x)
q, k, v = torch.chunk(qkv, 3, dim=-1)
q = q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
k = k.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
v = v.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
attn_weights = F.softmax(scores, dim=-1)
output = torch.matmul(attn_weights, v)
output = output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
return self.output_linear(output)
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, num_heads, ff_dim, dropout=0.1):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, num_heads)
self.ffn = nn.Sequential(
nn.Linear(d_model, ff_dim),
nn.ReLU(),
nn.Linear(ff_dim, d_model)
)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
attn_output = self.self_attn(x, mask)
x = self.norm1(x + self.dropout(attn_output))
ffn_output = self.ffn(x)
return self.norm2(x + self.dropout(ffn_output))
位置编码与输入处理
Transformer缺乏卷积或循环结构的时序处理能力,需通过位置编码(Positional Encoding)注入序列位置信息。常用正弦余弦函数生成固定编码:
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe.unsqueeze(0))
def forward(self, x):
return x + self.pe[:, :x.size(1)]
应用场景与优化技巧
- 长序列处理:通过稀疏注意力或分块机制降低计算复杂度。
- 预训练模型:BERT、GPT等均基于Transformer Encoder或Decoder架构。
- 超参数选择:头数$h$通常取8-16,前馈层维度$d_{ff}$一般为$4d_{model}$。
通过组合上述模块,可构建完整的Transformer模型,适用于机器翻译、文本分类等任务。
fcng5sjpybk8.feishu.cn/wiki/UAhQwjyPbikNBBku2QPc11bTnTh?from=from_copylink
fcng5sjpybk8.feishu.cn/wiki/DlypwJZITicDcMkUGmucOlWWnUf?from=from_copylink
fcng5sjpybk8.feishu.cn/wiki/BXzxwhKW0ibLirkx1VPc3o66nmb?from=from_copylink
fcng5sjpybk8.feishu.cn/wiki/MsvGw9sqTilXZVkZesBcOTmlnnc?from=from_copylink
fcng5sjpybk8.feishu.cn/wiki/Yj5MwhrXbiHygakTVdLcGznankh?from=from_copylink
986

被折叠的 条评论
为什么被折叠?



