别再死记硬背了!用Python+PyTorch手把手图解Transformer自注意力(附完整代码)
从零实现Transformer自注意力PyTorch实战与矩阵级可视化当你第一次看到自注意力机制的数学公式时是否觉得那些矩阵运算像天书般难以捉摸作为Transformer架构的核心自注意力机制的理解深度直接决定了你能否驾驭BERT、GPT等前沿模型。本文将用PyTorch从零搭建自注意力模块通过矩阵级可视化让你真正看到Q/K/V的生成、分数计算和加权求和的全过程。1. 环境准备与数据建模1.1 配置开发环境推荐使用Google Colab的GPU环境运行本实验确保已安装最新版PyTorchimport torch import torch.nn as nn import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt print(fPyTorch版本: {torch.__version__}) print(fCUDA可用: {torch.cuda.is_available()})1.2 构建示例数据我们模拟一个包含4个token的输入序列每个token的嵌入维度为8batch_size 1 seq_len 4 embed_dim 8 # 生成随机输入张量 (batch_size, seq_len, embed_dim) inputs torch.randn(batch_size, seq_len, embed_dim) print(输入张量形状:, inputs.shape)2. 自注意力核心实现2.1 初始化权重矩阵自注意力的第一步是创建Query、Key、Value的投影矩阵def initialize_weights(embed_dim): 初始化Q/K/V投影矩阵 W_Q nn.Parameter(torch.randn(embed_dim, embed_dim)) W_K nn.Parameter(torch.randn(embed_dim, embed_dim)) W_V nn.Parameter(torch.randn(embed_dim, embed_dim)) return W_Q, W_K, W_V W_Q, W_K, W_V initialize_weights(embed_dim)2.2 计算Q/K/V矩阵通过矩阵乘法得到Query、Key、Value表示def compute_qkv(inputs, W_Q, W_K, W_V): 计算Q/K/V矩阵 Q torch.matmul(inputs, W_Q) K torch.matmul(inputs, W_K) V torch.matmul(inputs, W_V) return Q, K, V Q, K, V compute_qkv(inputs, W_Q, W_K, W_V) print(fQ形状: {Q.shape}, K形状: {K.shape}, V形状: {V.shape})2.3 注意力分数计算与可视化实现缩放点积注意力并可视化分数矩阵def scaled_dot_product_attention(Q, K, V): 计算缩放点积注意力 d_k K.size(-1) scores torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(d_k)) attn_weights F.softmax(scores, dim-1) output torch.matmul(attn_weights, V) return output, attn_weights output, attn_weights scaled_dot_product_attention(Q, K, V) # 可视化注意力权重 plt.matshow(attn_weights.detach().numpy()[0]) plt.title(注意力权重矩阵) plt.colorbar() plt.show()3. 多头注意力机制实现3.1 划分注意力头将Q/K/V拆分为多个头实现并行计算def split_heads(tensor, num_heads): 将张量拆分为多头 batch_size, seq_len, embed_dim tensor.shape head_dim embed_dim // num_heads return tensor.view(batch_size, seq_len, num_heads, head_dim).transpose(1, 2) num_heads 2 Q_heads split_heads(Q, num_heads) K_heads split_heads(K, num_heads) V_heads split_heads(V, num_heads) print(f多头Q形状: {Q_heads.shape})3.2 多头注意力合并独立计算每个头的注意力后合并结果def multi_head_attention(Q, K, V, num_heads): 实现多头注意力 Q_heads split_heads(Q, num_heads) K_heads split_heads(K, num_heads) V_heads split_heads(V, num_heads) # 每个头独立计算注意力 attention_outputs [] for i in range(num_heads): head_output, _ scaled_dot_product_attention( Q_heads[:, i], K_heads[:, i], V_heads[:, i]) attention_outputs.append(head_output) # 合并多头结果 combined torch.cat(attention_outputs, dim-1) return combined multi_head_output multi_head_attention(Q, K, V, num_heads) print(多头注意力输出形状:, multi_head_output.shape)4. 完整自注意力模块封装4.1 添加残差连接与LayerNorm构建工业级可用的自注意力模块class SelfAttention(nn.Module): def __init__(self, embed_dim, num_heads): super().__init__() self.embed_dim embed_dim self.num_heads num_heads self.head_dim embed_dim // num_heads self.W_Q nn.Linear(embed_dim, embed_dim) self.W_K nn.Linear(embed_dim, embed_dim) self.W_V nn.Linear(embed_dim, embed_dim) self.fc_out nn.Linear(embed_dim, embed_dim) self.layer_norm nn.LayerNorm(embed_dim) def forward(self, x): residual x batch_size, seq_len, _ x.shape # 计算Q/K/V Q self.W_Q(x) K self.W_K(x) V self.W_V(x) # 拆分多头 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)) / torch.sqrt(torch.tensor(self.head_dim)) attn_weights F.softmax(scores, dim-1) output torch.matmul(attn_weights, V) # 合并多头 output output.transpose(1, 2).contiguous().view(batch_size, seq_len, -1) output self.fc_out(output) # 残差连接与LayerNorm output self.layer_norm(output residual) return output, attn_weights # 测试完整模块 attention_layer SelfAttention(embed_dim, num_heads) final_output, attn_weights attention_layer(inputs) print(最终输出形状:, final_output.shape)4.2 可视化注意力模式通过热力图展示不同token间的注意力分布def plot_attention_patterns(attn_weights, layer_name): 绘制多层注意力权重热力图 plt.figure(figsize(10, 5)) for i in range(attn_weights.shape[1]): # 遍历每个头 plt.subplot(1, attn_weights.shape[1], i1) plt.matshow(attn_weights[0, i].detach().numpy(), fignumFalse) plt.title(f头 {i1}) plt.colorbar() plt.suptitle(f{layer_name}注意力模式) plt.tight_layout() plt.show() plot_attention_patterns(attn_weights, 自注意力层)5. 进阶应用与调试技巧5.1 处理不同序列长度实现动态掩码处理变长输入序列def create_padding_mask(seq_len, valid_lens): 创建填充掩码 mask torch.ones(seq_len, seq_len) for i, valid_len in enumerate(valid_lens): mask[i, valid_len:] 0 mask[i, :, valid_len:] 0 return mask.bool() valid_lens [4, 2] # 第一个样本全有效第二个样本前2个token有效 mask create_padding_mask(2, valid_lens) print(填充掩码矩阵:\n, mask)5.2 梯度检查与数值稳定添加梯度监控确保训练稳定性def check_gradients(model): 检查各层梯度分布 for name, param in model.named_parameters(): if param.grad is not None: print(f{name} - 梯度均值: {param.grad.mean():.6f}, 梯度标准差: {param.grad.std():.6f}) # 模拟训练步骤 optimizer torch.optim.Adam(attention_layer.parameters()) loss final_output.sum() # 模拟损失 loss.backward() check_gradients(attention_layer)在实现过程中我发现将注意力权重可视化是理解模型行为的关键。特别是在调试多头注意力时通过观察不同头的注意力模式能快速发现是否出现梯度消失或过度关注特定位置的问题。建议在开发初期就建立完善的可视化监控这比单纯看数值指标更直观有效。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2549984.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!