transformer核心模块
✅易于扩展:添加新层或替换子模块无需重写框架✅高效并行:各模块可独立计算(尤其是 Attention 和 FFN)✅支持创新:如 MoE、FlashAttention、稀疏注意力等可无缝集成✅利于部署:模块可单独量化、剪枝、蒸馏“分而治之,合而用之”—— 将复杂模型拆解为功能单一、接口统一、高度复用的模块,再通过堆叠与组合构建强大系统。这种设计不仅推动了大模型的发展,也为 AI 架构演进提供了范式
transformer本身是一种模块化设计/架构,包含核心四块,输入->编码->解码->输出,每块介绍如下:
1、核心模块
整体结构:① 输入处理模块-->② 编码器模块-->③ 解码器模块-->④输出模块
① 输入处理模块(Input Processing Module)
- Token Embedding Layer:将离散 token 映射为向量。
- Positional Encoding Layer:添加位置信息(可替换为 RoPE、ALiBi 等)。
- Optional: Segment Embedding(用于 BERT 等多句子任务)。
✅ 可独立训练或替换,不影响主干网络。
② 编码器模块(Encoder Module)
- 每个 Encoder Layer 包含:[LayerNorm] → [Multi-Head Self-Attention] → [Residual] → [LayerNorm] → [Feed-Forward Network] → [Residual]
-
子模块详解:
|
子模块 |
功能 |
接口标准 |
|---|---|---|
|
Multi-Head Self-Attention (MHSA) |
计算序列内元素依赖关系 |
输入/输出维度一致 |
|
Feed-Forward Network (FFN) |
非线性变换,增强表达能力 |
固定结构,可替换激活函数 |
|
LayerNorm |
归一化,稳定训练 |
常在子模块前后应用 |
|
Residual Connection |
加速梯度传播,防止梯度消失 |
输入直接加到输出 |
✅ 每个 Encoder Layer 是一个“黑盒”模块,可堆叠 N 层。
③ 解码器模块(Decoder Module)
- 每个 Decoder Layer 包含:[LayerNorm] → [Masked Multi-Head Self-Attention] → [Residual] → [LayerNorm] → [Multi-Head Cross-Attention] → [Residual] →[LayerNorm] → [Feed-Forward Network] → [Residual]
-
新增子模块:
- Masked Multi-Head Self-Attention:只允许当前 token 注意前面的 token(因果掩码)。
- Cross-Attention:使用 Encoder 输出作为 Key 和 Value,实现编码-解码交互。
✅ 解码器模块比编码器多了一个跨注意力机制,但结构仍保持模块化一致性。
④ 输出模块(Output Module)
结构:Decoder Output → Linear Projection → Softmax → Final Output
- Linear Layer:将隐藏状态映射到词汇表大小。
- Softmax:生成概率分布(用于分类或生成)。
✅ 可替换为其他输出头(如 MLP 分类头、对比学习头等)。
2、核心模块结构(文字版)
+-----------------------------+
| Transformer |
+-----------------------------+
| Input Processing Module |
| - Token Embedding |
| - Positional Encoding |
+-----------------------------+
| Encoder Stack |
| +-----------------------+ |
| | Encoder Layer 1 | |
| | - MHSA | |
| | - FFN | |
| | - LayerNorm + Residual| |
| +-----------------------+ |
| | Encoder Layer 2 | |
| | ... | |
| +-----------------------+ |
+-----------------------------+
| Decoder Stack |
| +-----------------------+ |
| | Decoder Layer 1 | |
| | - Masked MHSA | |
| | - Cross-Attention | |
| | - FFN | |
| | - LayerNorm + Residual| |
| +-----------------------+ |
| | Decoder Layer 2 | |
| | ... | |
| +-----------------------+ |
+-----------------------------+
| Output Module |
| - Linear Projection |
| - Softmax |
+-----------------------------+
3、模块间接口标准化
|
模块 |
输入维度 |
输出维度 |
是否可复用 |
|---|---|---|---|
|
Token Embedding |
(B, L) |
(B, L, D) |
✅ |
|
MHSA |
(B, L, D) |
(B, L, D) |
✅ |
|
FFN |
(B, L, D) |
(B, L, D) |
✅ |
|
LayerNorm |
(B, L, D) |
(B, L, D) |
✅ |
|
Cross-Attention |
(B, L, D) |
(B, L, D) |
✅ |
|
Linear Projection |
(B, L, D) |
(B, L, V) |
✅ |
✅ 所有模块均遵循统一的
(Batch, SeqLen, Dim)数据格式,便于组合。
4、典型变体中的模块化应用示例
|
模型类型 |
使用模块 |
替换/新增模块 |
|---|---|---|
|
BERT |
Encoder Stack + MLM Head(Masked Language Model Head 的缩写,即“掩码语言模型头”) |
去掉 Decoder;增加 MLM 头 |
|
GPT |
Decoder Stack + LM Head |
使用因果掩码;无 Cross-Attn |
|
T5 |
Full Encoder-Decoder |
添加 Task Prefix 模块 |
|
ViT |
Encoder Stack |
输入为图像 Patch Embedding |
|
LLaMA |
Encoder-Decoder-like |
RMSNorm, SwiGLU, RoPE |
5、模块化设计的优势总结
✅ 易于扩展:添加新层或替换子模块无需重写框架
✅ 高效并行:各模块可独立计算(尤其是 Attention 和 FFN)
✅ 支持创新:如 MoE、FlashAttention、稀疏注意力等可无缝集成
✅ 利于部署:模块可单独量化、剪枝、蒸馏
6、工程实现建议(PyTorch 示例)
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.num_heads = num_heads
self.d_k = d_model // num_heads
self.q_linear = nn.Linear(d_model, d_model)
self.k_linear = nn.Linear(d_model, d_model)
self.v_linear = nn.Linear(d_model, d_model)
self.out_linear = nn.Linear(d_model, d_model)
class FeedForward(nn.Module):
def __init__(self, d_model, d_ff):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.GELU(),
nn.Linear(d_ff, d_model)
)
class EncoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff):
super().__init__()
self.attn = MultiHeadAttention(d_model, num_heads)
self.ffn = FeedForward(d_model, d_ff)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x):
# Self-Attention
attn_out = self.attn(x)
x = x + attn_out # residual
x = self.norm1(x)
# FFN
ffn_out = self.ffn(x)
x = x + ffn_out # residual
x = self.norm2(x)
return x
📌 上述代码体现了模块化设计:每个类是一个独立模块,组合成完整的层。
✅ 总结:Transformer 模块化设计的核心思想
“分而治之,合而用之” —— 将复杂模型拆解为功能单一、接口统一、高度复用的模块,再通过堆叠与组合构建强大系统。
这种设计不仅推动了大模型的发展,也为 AI 架构演进提供了范式。
附:Q 、K、V的理解
Q/K/V 是 Transformer 最核心的组成部分,它藏在“Multi-Head Self-Attention”这个模块里
一句话summary下:
Q/K/V(Query/Key/Value)是 Multi-Head Self-Attention 模块内部的三个线性变换矩阵,它们的作用是:让每个 token 能够“提问”(Q)、“被问”(K)、“提供答案”(V),从而计算出它与其他 token 的相关性权重。
在上边提供的结构里:Encoder Layer: [LayerNorm] → [Multi-Head Self-Attention] → [Residual] → [LayerNorm] → [Feed-Forward Network] → [Residual]
Multi-Head Self-Attention 就是包含 Q/K/V 的地方!
伪代码展示下Q、K、V的地方:
class MultiHeadSelfAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.num_heads = num_heads
self.d_k = d_model // num_heads
# 这三个就是 Q/K/V 线性层!
self.q_linear = nn.Linear(d_model, d_model) # Query
self.k_linear = nn.Linear(d_model, d_model) # Key
self.v_linear = nn.Linear(d_model, d_model) # Value
self.out_linear = nn.Linear(d_model, d_model)
def forward(self, x):
# x: [B, L, D] —— batch, seq_len, dim
Q = self.q_linear(x) # [B, L, D] → 查询
K = self.k_linear(x) # [B, L, D] → 键
V = self.v_linear(x) # [B, L, D] → 值
# 计算注意力分数
attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(self.d_k)
attn_weights = torch.softmax(attn_scores, dim=-1)
# 加权求和
output = torch.matmul(attn_weights, V)
return output
如何理解 Q/K/V?
| 角色 | 含义 | 类比 |
|---|---|---|
| Query (Q) | “我想要关注谁?” | 你是听众,提出问题 |
| Key (K) | “我是什么身份?” | 别人举手说:“我是专家!” |
| Value (V) | “我有什么内容?” | 别人开始讲解具体内容 |
🎯 关键点:每个 token 都同时是 Q、K、V 的来源,它既“提问”也“回答”。
为什么需要多头(Multi-Head)?
因为单个注意力头只能捕捉一种关系(比如“语法依赖”),而多个头可以并行捕捉不同类型的依赖:
- 头1:关注主谓宾结构
- 头2:关注上下文语义
- 头3:关注指代关系
👉 所以叫“多头注意力”,就像一个人有多个大脑区域,分别处理不同任务。
补充:在 Qwen3-VL 中如何应用?
在视觉语言模型中:
- 文本 token 生成自己的 Q/K/V;
- 图像 token 也生成自己的 Q/K/V;
- 然后通过跨模态注意力(Cross-Attention)实现“文本看图”、“图理解文”。
例如:
# 文本 -> 图像 注意力
Q_text = text_q_linear(text_embeds)
K_image = image_k_linear(image_embeds)
V_image = image_v_linear(image_embeds)
attn_output = torch.matmul(Q_text, K_image.T) # 文本关注图像
总结一句话:
Q/K/V 是 Multi-Head Self-Attention 模块内部的三个线性变换层,它们让每个 token 能“提问”、“被问”、“提供信息”,从而计算出序列内元素之间的关联强度。
更多推荐
所有评论(0)