transformer 是怎么算的,原理是什么?
- User
transformer 是怎么算的,原理是什么?
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
transformer 是怎么算的,原理是什么?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
下面给你一个由浅入深、但尽量不啰嗦的 Transformer 原理速览。如果你已经知道其中某些部分,可以直接跳读~🚀
传统 RNN / LSTM:
• 逐步读序列,时间长、难并行
• 长距离依赖难学(梯度消失/爆炸)
Transformer(2017 “Attention is All You Need”):
• 全注意力(self-attention),一次就能看全局
• 序列各位置可并行计算 → GPU 吃得爽
• 通过多层堆叠 + 多头,有效学习复杂关系
┌──────────── Encoder N 层 ────────────┐
Tokens → │ Self-Attn → FFN → … (×N) │
└───────────────────────────────────┘
↓ (上下文向量)
┌──────────── Decoder N 层 ────────────┐
│ Masked Self-Attn → Cross-Attn → FFN │
└───────────────────────────────────┘
↓
Softmax 预测
Encoder 和 Decoder 结构相似,只是 Decoder 多了:
• Masked Self-Attention(防“偷看”未来词)
• Cross-Attention(读 Encoder 输出,做翻译/生成)
把向量切成 份并行做 attention: 好处:不同头可关注不同关系(语法/实体/位置…)。
位置独立的 MLP,两层 + 激活: 一般 比 大 4 倍左右。
每步都包两层:
y = LayerNorm(x + SubLayer(x))
稳定训练、加速收敛。
• 语言建模(GPT):最大化
• Seq2Seq(翻译、摘要):最大化
通常用 Cross-Entropy + Teacher Forcing。
import torch.nn as nn
class MiniTransformerLayer(nn.Module):
def __init__(self, d_model=512, n_heads=8, d_ff=2048, p_drop=0.1):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_heads, dropout=p_drop, batch_first=True)
self.ffn = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.ReLU(),
nn.Linear(d_ff, d_model)
)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(p_drop)
def forward(self, x, mask=None):
# Self-Attention
attn_out, _ = self.attn(x, x, x, attn_mask=mask) # Q=K=V=x
x = self.norm1(x + self.dropout(attn_out))
# FFN
ffn_out = self.ffn(x)
x = self.norm2(x + self.dropout(ffn_out))
return x
• Sparse / Linear Attention(降低 )
• 相对/旋转位置编码 (RoPE)
• ALiBi, FlashAttention, Performer…
• Decoder-only(GPT 系列)、Encoder-only(BERT)变体
🎯 小结:
Transformer 核心只做一件事——“让序列里任何两个位置都能互相看见并学到权重”,再用多层+多头+残差+LayerNorm 组合,既强大又易并行;这就是它能成为 NLP 王炸、又扩展到 CV、音频、多模态的根本原因。
如果你想进一步深入(比如推理加速、蒸馏、或者具体某篇论文)随时告诉我!