Transformer基础架构详解(附图 + Python Demo)
一、为什么会有 Transformer在 Transformer 出现之前主流模型是RNN循环神经网络LSTM / GRUimport torch import torch.nn as nn # 定义RNN rnn nn.RNN(input_size128, hidden_size128) # 输入序列长度5 x torch.rand(5, 1, 128) h torch.zeros(1, 1, 128) # 初始隐藏状态 outputs [] for t in range(5): # ❗必须逐时间步计算串行 out, h rnn(x[t].unsqueeze(0), h) outputs.append(out) # outputs保存每个时间步结果import torch import torch.nn as nn # 定义LSTM lstm nn.LSTM(input_size128, hidden_size128) x torch.rand(5, 1, 128) h torch.zeros(1, 1, 128) # 隐藏状态 c torch.zeros(1, 1, 128) # 细胞状态关键 outputs [] for t in range(5): # ❗仍然是串行 out, (h, c) lstm(x[t].unsqueeze(0), (h, c)) outputs.append(out)# 此处是trasnformer案例 import torch import torch.nn as nn # 多头注意力 attn nn.MultiheadAttention(embed_dim128, num_heads8) # 一次性输入整个序列 x torch.rand(5, 1, 128) # Q K V x自注意力 output, weights attn(x, x, x)RNN和LSTM有两个致命问题❌无法并行计算太慢❌长距离依赖难以捕捉二、Transformer整体架构二、整体架构核心结构Input → Encoder → Decoder → Output┌───────────────┐ Input → │ Encoder × N │ └───────────────┘ ↓ ┌───────────────┐ Target → │ Decoder × N │ → 输出 └───────────────┘三、Encoder 结构重点每一层Encoder包含两个核心模块在 Transformer 中Encoder 是负责“理解输入”的部分。每一层 Encoder 都包含两个核心模块Self-Attention自注意力 Feed Forward前馈网络输入 ↓ Multi-Head Self-Attention ↓ Add LayerNorm ↓ Feed Forward Network ↓ Add LayerNorm ↓ 输出1️⃣ Self-Attention自注意力1. 本质作用:让每个词都能“看”到句子中所有词并决定关注谁2. 举个直觉例子:The animal didnt cross the street because it was too tired问题“it”指谁animal ❓street ❓ Self-Attention 会自动学到“it”更关注“animal”3. 数学计算过程核心Step 1生成 Q / K / V输入向量 x 通过线性变换Q xWqK xWkV xWvStep 2计算注意力权重Step 3加权求和4. Multi-Head Attention多头不是只做一次 Attention而是Head1: 学语法关系 Head2: 学语义关系 Head3: 学位置关系 ...最后拼接Concat(head1, head2, ...) → Linear 本质从多个“角度”理解句子5. PyTorch 简化实现import torch import torch.nn.functional as F def self_attention(x): d_model x.size(-1) Wq torch.rand(d_model, d_model) Wk torch.rand(d_model, d_model) Wv torch.rand(d_model, d_model) Q x Wq K x Wk V x Wv scores Q K.transpose(-2, -1) / (d_model ** 0.5) weights F.softmax(scores, dim-1) return weights V x torch.rand(1, 5, 64) out self_attention(x) print(out.shape)2️⃣ Feed Forward前馈网络待完善...
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2439422.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!