Transformer 面试题及答案详解
一、基础原理与数学模型
1. Transformer为何使用多头注意力机制?(为什么不用一个头)
答案:
多头注意力机制的优势:
-
捕获不同子空间的信息:不同的注意力头可以关注输入序列的不同方面和特征表示,类似于CNN中使用多个卷积核捕获不同特征。
-
增强模型的表达能力:单头注意力只能学习一种注意力模式,多头可以并行学习多种注意力模式,从不同角度理解输入。
-
降低过拟合风险:多个头之间相互独立,类似于集成学习的效果,提高模型鲁棒性。
-
允许模型关注不同位置:
- 某些头可能关注局部信息(相邻词)
- 某些头可能关注长距离依赖
- 某些头可能关注语法结构
- 某些头可能关注语义关系
数学表达:
MultiHead(Q,K,V) = Concat(head₁,...,headₕ)W^O
其中 headᵢ = Attention(QWᵢᵠ, KWᵢᴷ, VWᵢⱽ)
2. Transformer为什么Q和K使用不同的权重矩阵生成?为何不能使用同一个值进行自身的点乘?
答案:
使用不同权重矩阵的原因:
-
增加模型灵活性:Q和K使用不同的权重矩阵,使得”查询”和”键”可以在不同的语义空间中表示,增强了模型的表达能力。
-
避免退化问题:如果使用相同的矩阵,即 Q = K = XW,则注意力分数变为:
Attention(Q,K) = softmax(XW(XW)ᵀ/√dₖ)这会导致注意力矩阵变成对称矩阵,限制了模型的表达能力。
-
非对称关系建模:在实际语言中,词与词之间的关系往往是非对称的。例如”猫”对”动物”的关系和”动物”对”猫”的关系是不同的。
-
打破对称性:
- 如果 Q = K,则 Attention(i,j) = Attention(j,i)
- 这意味着词i对词j的注意力等于词j对词i的注意力
- 这在很多场景下是不合理的
示例:
在句子”The cat sat on the mat”中:
- “cat”查询”sat”(主语-谓语关系)
- “sat”查询”cat”(谓语-主语关系)
这两个方向的语义关系不同,需要不同的权重矩阵来捕获。
3. Transformer计算attention的时候为何选择点乘而不是加法?两者计算复杂度和效果上有什么区别?
答案:
选择点乘的原因:
-
计算效率:
- 点乘注意力:可以利用高度优化的矩阵乘法运算,GPU加速效果好
- 加法注意力:需要先广播拼接,再通过前馈网络,计算开销更大
-
复杂度比较:
- 点乘注意力:O(n² · dₖ)
Score = QKᵀ/√dₖ # 矩阵乘法 - 加法注意力:O(n² · dₖ)(理论上相同)
Score = vᵀ·tanh(W₁Q + W₂K) # 需要更多参数
- 点乘注意力:O(n² · dₖ)
-
参数效率:
- 点乘不需要额外的可学习参数
- 加法注意力需要权重矩阵W₁、W₂和向量v
-
实验效果:
- 当dₖ较小时,两者性能相当
- 当dₖ较大时,点乘注意力表现更好(经过scaled后)
- 点乘操作在现代硬件上有更好的优化
两种注意力的公式:
点乘注意力(Scaled Dot-Product):
Attention(Q,K,V) = softmax(QKᵀ/√dₖ)V
加法注意力(Additive Attention):
Attention(Q,K,V) = softmax(vᵀ·tanh(W₁Q + W₂K))V
4. 为什么在进行softmax之前需要对attention进行scaled?(为什么除以dk的平方根),并使用公式推导进行讲解
答案:
Scaling的必要性:
当dₖ(键向量维度)较大时,点积结果的方差会变大,导致softmax函数进入饱和区,梯度消失。
数学推导:
假设Q和K的元素是独立同分布的随机变量,均值为0,方差为1。
-
点积的方差分析:
对于向量 q = [q₁, q₂, ..., qₐₖ] 和 k = [k₁, k₂, ..., kₐₖ] 点积 q·k = Σᵢ qᵢkᵢ E[qᵢkᵢ] = E[qᵢ]E[kᵢ] = 0 (独立性) Var(qᵢkᵢ) = E[qᵢ²]E[kᵢ²] = 1 因此: E[q·k] = 0 Var(q·k) = Σᵢ Var(qᵢkᵢ) = dₖ -
标准差的增长:
σ(q·k) = √Var(q·k) = √dₖ当dₖ很大时,点积值的标准差也很大,可能达到很大的正值或负值。
-
Softmax饱和问题:
当输入 x 很大时:softmax([x₁,...,xₙ]) ≈ [1,0,...,0] 当输入 x 很小时:softmax([x₁,...,xₙ]) ≈ [0,0,...,1]这导致梯度接近0,训练困难。
-
Scaling解决方案:
将点积除以 √dₖ: q·k/√dₖ Var(q·k/√dₖ) = Var(q·k)/dₖ = dₖ/dₖ = 1通过除以√dₖ,使得点积结果的方差保持在1左右,避免进入softmax的饱和区。
示例:
假设dₖ = 64:
- 不scaling:点积值可能在 [-25, 25] 范围内
softmax([25, 1, 0, -2]) ≈ [1.0, 0, 0, 0] # 饱和 - scaling后:点积值在 [-3, 3] 范围内
softmax([3.125, 0.125, 0, -0.25]) ≈ [0.91, 0.05, 0.02, 0.02] # 正常
5. 在计算attention score的时候如何对padding做mask操作?
答案:
Padding Mask的目的:
防止模型关注到填充位置(padding tokens),这些位置不包含实际的语义信息。
实现方法:
-
创建Mask矩阵:
# 假设输入序列:["Hello", "World", "<PAD>", "<PAD>"] # 对应的mask(1表示真实token,0表示padding) mask = [1, 1, 0, 0] # 将mask扩展为attention矩阵的形状 # shape: (seq_len, seq_len) attention_mask = mask.unsqueeze(1) * mask.unsqueeze(0) -
应用Mask:
# 计算原始attention scores scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k) # shape: (batch, heads, seq_len, seq_len) # 将padding位置的score设置为负无穷 scores = scores.masked_fill(mask == 0, -1e9) # 应用softmax attention_weights = F.softmax(scores, dim=-1) # padding位置的权重会变成0 -
Mask的作用:
- 在softmax之前,将mask位置的score设为-∞(实际为-1e9)
- softmax后,这些位置的权重变为0
- 确保padding位置不会影响实际内容的表示
代码示例:
def attention_with_mask(Q, K, V, mask=None):
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
# mask shape: (batch, 1, 1, seq_len) or (batch, 1, seq_len, seq_len)
scores = scores.masked_fill(mask == 0, -1e9)
attention = F.softmax(scores, dim=-1)
output = torch.matmul(attention, V)
return output, attention注意事项:
- Encoder中:双向mask,padding位置对所有位置都不可见
- Decoder中:需要同时考虑padding mask和causal mask(未来位置mask)
6. 为什么在进行多头注意力的时候需要对每个head进行降维?
答案:
降维的原因:
-
保持计算复杂度:
假设原始维度 d_model = 512,使用8个头 不降维: - 每个头的维度:512 - 总参数量:8 × (512×512×3) ≈ 6M(Q,K,V三个矩阵) - 计算复杂度:8 × O(n²·512) 降维(每个头 d_k = 64): - 每个头的维度:512/8 = 64 - 总参数量:512×512×3 ≈ 0.75M - 计算复杂度:8 × O(n²·64) = O(n²·512) -
参数效率:
设 d_model = 512, h = 8(头数) d_k = d_v = d_model/h = 64 多头注意力的参数量: W^Q, W^K, W^V: 3 × (d_model × d_model) = 3 × 512² W^O: d_model × d_model = 512² 总计:4 × 512² ≈ 1M 如果不降维(每个头都是512维): 8头 × 3 × 512² + 512² = 25 × 512² ≈ 6.5M -
多样性和专注性:
- 降维迫使每个头关注不同的特征子空间
- 每个头在低维空间中专注于特定模式
- 避免不同头学习到相似的注意力模式
-
信息互补性:
多个低维头的拼接:Concat(head₁,...,head₈) 每个头在不同子空间学习: - head₁可能关注句法结构 - head₂可能关注语义关系 - head₃可能关注位置信息 等等
具体实现:
class MultiHeadAttention(nn.Module):
def __init__(self, d_model=512, num_heads=8):
super().__init__()
assert d_model % num_heads == 0
self.d_k = d_model // num_heads # 64
self.num_heads = num_heads
# 投影矩阵:512 -> 512(内部分割成8个64维)
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)总结:
降维是在保持总计算量和参数量不变的前提下,实现多头并行学习,增强模型的表达能力。
7. 讲一下Transformer的Encoder模块?
答案:
Encoder结构组成:
Transformer的Encoder由N个相同的层堆叠而成(原论文N=6),每层包含两个子层:
- 多头自注意力机制(Multi-Head Self-Attention)
- 位置全连接前馈网络(Position-wise Feed-Forward Network)
详细架构:
输入 (Input Embeddings + Positional Encoding)
↓
┌─────────────────────────────┐
│ Encoder Layer × N │
│ ┌─────────────────────┐ │
│ │ Multi-Head │ │
│ │ Self-Attention │ │
│ └─────────────────────┘ │
│ ↓ │
│ Add & Norm │
│ ↓ │
│ ┌─────────────────────┐ │
│ │ Feed Forward │ │
│ │ Network │ │
│ └─────────────────────┘ │
│ ↓ │
│ Add & Norm │
└─────────────────────────────┘
↓
输出 (Encoder Output)
各组件详解:
-
输入处理:
Input = Token Embeddings + Positional Encoding - Token Embeddings: 词嵌入矩阵,维度 (seq_len, d_model) - Positional Encoding: 位置编码,维度 (seq_len, d_model) -
Multi-Head Self-Attention:
# Q, K, V都来自同一输入 Q = K = V = Input # 多头注意力 MultiHead(Q,K,V) = Concat(head₁,...,headₕ)W^O head_i = Attention(QW_i^Q, KW_i^K, VW_i^V) -
Add & Norm(残差连接+层归一化):
# 残差连接 output = LayerNorm(input + Sublayer(input)) # 防止梯度消失,加速训练 -
Feed-Forward Network:
FFN(x) = max(0, xW₁ + b₁)W₂ + b₂ # 两层全连接,中间用ReLU激活 # 第一层:d_model -> d_ff (通常d_ff = 4*d_model) # 第二层:d_ff -> d_model
关键特性:
- 残差连接:帮助梯度传播,允许堆叠更深的网络
- 层归一化:稳定训练,加速收敛
- 并行计算:所有位置可以同时计算,不像RNN需要序列处理
- 位置无关:每个位置的FFN参数共享,但独立计算
参数规模(d_model=512, d_ff=2048, h=8):
单层Encoder参数量:
- Multi-Head Attention: 4 × 512² ≈ 1M
- FFN: 512×2048 + 2048×512 ≈ 2M
- 总计:≈ 3M
6层Encoder总参数:≈ 18M
8. 为何在获取输入向量之后需要对矩阵乘以embedding size的开方?
答案:
问题背景:
在Transformer的实现中,输入嵌入后会乘以√d_model:
x = self.embedding(input) * math.sqrt(self.d_model)
x = x + self.positional_encoding原因分析:
-
保持数值稳定性:
Embedding初始化通常使用正态分布:N(0, 1) Positional Encoding的值范围:[-1, 1] 不scaling: - Embedding: 方差为1,数值范围较大 - PE: 固定范围[-1,1],相对较小 - 相加时PE的贡献被淹没 Scaling后(乘以√d_model): - Embedding: 方差变为d_model,数值量级增大 - 与PE的数值量级相当,PE的作用得以体现 -
平衡Embedding和Positional Encoding的贡献:
d_model = 512 # 不scaling emb = embedding(x) # 标准差 ≈ 1 pe = positional_encoding() # 值域 [-1, 1] output = emb + pe # PE贡献很小 # scaling后 emb = embedding(x) * sqrt(512) # 标准差 ≈ 22.6 pe = positional_encoding() # 值域 [-1, 1] output = emb + pe # PE贡献合理 -
与Xavier初始化一致:
Xavier初始化方差:Var(W) = 1/n Embedding层相当于一个查找表,需要手动调整尺度 乘以√d_model使得输出方差与标准初始化一致 -
实验验证:
- 原论文实验表明,这个scaling factor能提升模型性能
- 帮助模型更好地学习位置信息
- 训练更稳定,收敛更快
代码示例:
class TransformerEmbedding(nn.Module):
def __init__(self, vocab_size, d_model, max_len=5000):
super().__init__()
self.d_model = d_model
self.embedding = nn.Embedding(vocab_size, d_model)
self.pos_encoding = PositionalEncoding(d_model, max_len)
def forward(self, x):
# 关键:乘以sqrt(d_model)
emb = self.embedding(x) * math.sqrt(self.d_model)
return self.pos_encoding(emb)总结:
这个scaling因子确保了词嵌入和位置编码在相同的数值尺度上,使得位置信息能够有效地融入到模型中。
9. 简单介绍Transformer的位置编码?
答案:
位置编码的必要性:
Transformer的自注意力机制本身是位置无关的,它把输入序列看作一个集合。为了让模型感知词的顺序信息,需要添加位置编码。
原始Transformer的位置编码(Sinusoidal Positional Encoding):
公式:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
其中:
- pos: 词在序列中的位置(0, 1, 2, ...)
- i: 维度索引(0, 1, 2, ..., d_model/2-1)
- d_model: 模型维度
特点:
-
固定且可预测:
- 位置编码是固定的,不需要学习
- 对于任意长度的序列都适用
- 推理时可以处理比训练时更长的序列
-
周期性变化:
- 低维度(i小):频率高,变化快,捕获局部位置信息 - 高维度(i大):频率低,变化慢,捕获全局位置信息 -
相对位置关系:
PE(pos+k) 可以表示为PE(pos)的线性函数 这使得模型容易学习相对位置关系
可视化示例(d_model=128):
位置0: [sin(0/10000^0), cos(0/10000^0), sin(0/10000^(2/128)), ...]
位置1: [sin(1/10000^0), cos(1/10000^0), sin(1/10000^(2/128)), ...]
...
代码实现:
import torch
import math
def get_positional_encoding(max_len, d_model):
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)
return pe
# 使用
pos_encoding = get_positional_encoding(max_len=100, d_model=512)
# shape: (100, 512)使用方式:
# 与词嵌入相加
output = token_embedding + positional_encoding优点:
- 不增加参数量
- 可以外推到更长序列
- 提供了丰富的位置信息
缺点:
- 对于某些任务,学习式位置编码可能效果更好
- 固定函数可能限制了模型的灵活性
10. 了解哪些关于位置编码的技术?
答案:
1. Sinusoidal Positional Encoding(正弦位置编码)
- 来源:原始Transformer论文
- 特点:固定的、基于三角函数的编码
- 公式:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model)) - 优点:不需要学习,可外推到任意长度
- 缺点:不够灵活,可能不是最优
2. Learned Positional Embedding(学习式位置编码)
- 来源:BERT等模型
- 特点:位置编码作为可学习参数
- 实现:
self.pos_embedding = nn.Embedding(max_len, d_model) pos_enc = self.pos_embedding(position_ids) - 优点:更灵活,可以针对特定任务优化
- 缺点:无法外推到更长序列,需要额外参数
3. Relative Positional Encoding(相对位置编码)
- 来源:Self-Attention with Relative Position Representations
- 特点:关注词之间的相对距离而非绝对位置
- 核心思想:
attention(i,j) = f(x_i, x_j, i-j) 而不是 f(x_i + PE(i), x_j + PE(j)) - 应用:Transformer-XL, T5等模型
- 优点:更好地捕获相对关系,泛化能力强
4. Rotary Position Embedding (RoPE)
- 来源:RoFormer, 后被LLaMA等采用
- 特点:通过旋转矩阵编码位置信息
- 核心思想:
# 将位置信息编码到Q和K的旋转中 Q_rot = rotate(Q, position) K_rot = rotate(K, position) attention = Q_rot @ K_rot^T - 优点:
- 自然地编码相对位置信息
- 外推性能好
- 计算效率高
- 应用:GPT-Neo, LLaMA, PaLM等
5. ALiBi (Attention with Linear Biases)
- 来源:Train Short, Test Long
- 特点:不添加位置编码,而是在attention score上加bias
- 公式:
attention(i,j) = softmax(Q_i·K_j + bias(i-j)) bias(i-j) = -m·|i-j| (m是预设常数) - 优点:
- 极简实现
- 外推性能极好
- 不增加额外参数
- 应用:BLOOM等模型
6. Conditional Position Encoding (CPE)
- 来源:用于Vision Transformer
- 特点:位置编码是输入的函数
- 实现:通过深度卷积动态生成位置编码
7. FIRE (Functional Interpolation for Relative Embeddings)
- 特点:改进的相对位置编码方案
- 优点:更好的外推能力
8. NoPE (No Position Encoding)
- 来源:一些研究表明位置编码可能不是必需的
- 条件:
- 使用因果注意力
- 模型足够大
- 数据足够多
- 例子:某些GPT变体
不同位置编码对比:
| 方法 | 可学习 | 外推能力 | 参数量 | 相对位置 |
|---|---|---|---|---|
| Sinusoidal | ✗ | ✓ | 0 | 间接 |
| Learned | ✓ | ✗ | O(L·d) | ✗ |
| Relative | ✓ | ✓ | O(L) | ✓ |
| RoPE | ✗ | ✓ | 0 | ✓ |
| ALiBi | ✗ | ✓✓ | 0 | ✓ |
选择建议:
- 固定长度任务:Learned PE
- 需要外推:RoPE或ALiBi
- 相对位置重要:Relative PE或RoPE
- 大模型:RoPE(LLaMA)或ALiBi(BLOOM)
11. 简单介绍一下Transformer中的残差结构以及意义
答案:
残差结构(Residual Connection):
定义:
输出 = LayerNorm(输入 + Sublayer(输入))
在Transformer中的每个子层(Multi-Head Attention和FFN)后都使用。
结构示意:
输入 x
├──→ [Multi-Head Attention] ──→ output
└────────────────┬─────────────────┘
↓ (相加)
LayerNorm(x + output)
↓
下一层输入
意义和作用:
-
缓解梯度消失问题:
反向传播时: ∂L/∂x = ∂L/∂y · (1 + ∂F(x)/∂x) 即使 ∂F(x)/∂x 很小,梯度仍能通过 "1" 这条路径传播 -
允许更深的网络:
- 原始Transformer:6层Encoder + 6层Decoder
- GPT-3:96层
- 没有残差连接,很难训练如此深的网络
-
加速训练收敛:
- 初始时,如果子层学习不充分,残差连接保证信息传递
- 网络可以选择性地学习残差 F(x),而不是完整映射 H(x)
- 学习 H(x) = F(x) + x 通常比直接学习 H(x) 更容易
-
恒等映射的保护:
如果某一层的最优函数是恒等映射:H(x) = x 有残差:F(x) = 0 即可(容易学习) 无残差:需要学习完整的恒等映射(困难) -
特征复用:
- 浅层学到的特征可以直接传递到深层
- 每层只需要学习增量信息
Transformer中的两处残差连接:
# 第一个残差:Multi-Head Attention
attention_output = MultiHeadAttention(x)
x = LayerNorm(x + attention_output)
# 第二个残差:Feed Forward
ff_output = FeedForward(x)
x = LayerNorm(x + ff_output)Pre-LN vs Post-LN:
原始Transformer使用Post-LN(先子层,后加和归一化):
# Post-LN (原始)
x = LayerNorm(x + Sublayer(x))现代实现常用Pre-LN(先归一化,后子层):
# Pre-LN (更稳定)
x = x + Sublayer(LayerNorm(x))Pre-LN的优势:
- 训练更稳定
- 梯度传播更好
- 不需要warm-up
- GPT-2/3、LLaMA等都使用Pre-LN
数学直观:
设网络有L层,输入为x₀:
无残差:y = F_L(F_{L-1}(...F_1(x₀)))
有残差:y = x₀ + ΣF_i(x_i)
残差形式更像是在原始输入上”打补丁”,而不是完全重新学习。
总结:
残差连接是Transformer能够训练深层网络的关键技术之一,它通过提供梯度的”高速公路”,使得信息和梯度能够有效地在网络中流动。
12. 为什么transformer块使用LayerNorm而不是BatchNorm?
答案:
BatchNorm vs LayerNorm对比:
1. 归一化维度不同:
# BatchNorm: 对batch维度归一化
# 输入shape: (batch_size, seq_len, d_model)
# 对每个特征维度,在batch上计算均值和方差
mean = x.mean(dim=0) # shape: (seq_len, d_model)
var = x.var(dim=0)
# LayerNorm: 对特征维度归一化
# 对每个样本,在特征维度上计算均值和方差
mean = x.mean(dim=-1) # shape: (batch_size, seq_len)
var = x.var(dim=-1)2. Transformer选择LayerNorm的原因:
(1)序列长度可变:
- BatchNorm假设每个样本的特征具有相同的维度
- NLP任务中,不同句子长度不同
- LayerNorm对每个token独立归一化,不受序列长度影响
(2)Batch size敏感性:
BatchNorm问题:
- 小batch size时,统计量不准确
- 训练和推理时的统计量不一致
- NLP任务的batch size通常较小(受显存限制)
LayerNorm优势:
- 不依赖batch size
- 训练和推理完全一致
- 单样本推理也没问题
(3)序列建模的特点:
NLP任务中:
- 每个位置的表示应该相对独立
- 不同位置的词嵌入含义不同("猫"在位置1和位置5是不同的语义)
- BatchNorm会混淆不同位置的信息
LayerNorm:
- 对每个位置独立归一化
- 保持位置之间的相对关系
(4)Attention机制的需求:
Attention计算:softmax(QK^T / √d)
需要特征在相同尺度上:
- LayerNorm确保每个token的特征在相似尺度
- BatchNorm可能导致不同样本间的尺度差异
3. 数值示例:
# 输入: (batch=2, seq_len=3, d_model=4)
x = torch.randn(2, 3, 4)
# BatchNorm: 每个位置在batch维度归一化
bn = nn.BatchNorm1d(3) # 3个位置
# 问题:不同batch的同一位置可能含义完全不同
# LayerNorm: 每个样本的每个位置在特征维度归一化
ln = nn.LayerNorm(4) # 4个特征
# 优势:每个token独立,不受其他样本影响4. 实验对比:
| 特性 | BatchNorm | LayerNorm |
|---|---|---|
| Batch依赖 | 强 | 无 |
| 序列长度 | 固定 | 任意 |
| 小batch | 不稳定 | 稳定 |
| 推理一致性 | 需要running stats | 完全一致 |
| NLP效果 | 差 | 好 |
| CV效果 | 好 | 一般 |
5. LayerNorm的公式:
def layer_norm(x, gamma, beta, eps=1e-5):
# x: (batch, seq_len, d_model)
mean = x.mean(dim=-1, keepdim=True) # (batch, seq_len, 1)
var = x.var(dim=-1, keepdim=True) # (batch, seq_len, 1)
x_norm = (x - mean) / sqrt(var + eps)
output = gamma * x_norm + beta
return output总结:
Transformer使用LayerNorm是因为:
- 适应可变序列长度
- 不依赖batch size
- 训练推理一致
- 更符合序列建模的需求
- 与Attention机制配合更好
这些特性使得LayerNorm成为NLP任务的自然选择。
13. 讲一下BatchNorm技术及其优缺点?
答案:
BatchNorm(批归一化)定义:
对一个batch的数据在每个特征维度上进行归一化。
公式:
1. 计算batch均值和方差:
μ_B = (1/m) Σx_i
σ²_B = (1/m) Σ(x_i - μ_B)²
2. 归一化:
x̂_i = (x_i - μ_B) / √(σ²_B + ε)
3. 缩放和平移(可学习参数):
y_i = γx̂_i + β
其中:
- m: batch size
- γ, β: 可学习参数
- ε: 防止除零的小常数
工作原理:
class BatchNorm1d(nn.Module):
def __init__(self, num_features):
super().__init__()
self.gamma = nn.Parameter(torch.ones(num_features))
self.beta = nn.Parameter(torch.zeros(num_features))
# 用于推理的running统计量
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
def forward(self, x):
# x shape: (batch, features)
if self.training:
mean = x.mean(dim=0)
var = x.var(dim=0)
# 更新running统计量(用于推理)
self.running_mean = 0.9 * self.running_mean + 0.1 * mean
self.running_var = 0.9 * self.running_var + 0.1 * var
else:
mean = self.running_mean
var = self.running_var
x_norm = (x - mean) / torch.sqrt(var + 1e-5)
return self.gamma * x_norm + self.beta优点:
-
加速训练收敛:
- 减少内部协变量偏移(Internal Covariate Shift)
- 允许使用更大的学习率
- 训练速度可提升2-3倍
-
提高模型性能:
- 通常能提升1-2%的准确率
- 使模型对初始化不敏感
-
正则化效果:
- 由于使用batch统计量,引入噪声
- 有类似dropout的正则化作用
- 可以减少或去除dropout
-
允许更深的网络:
- 缓解梯度消失/爆炸
- 成功训练100+层的网络(ResNet等)
-
参数初始化不敏感:
- 即使权重初始化不佳,BN也能缓解
缺点:
-
Batch size依赖性:
小batch问题: - batch size < 16时,统计量不准确 - 性能显著下降 - NLP任务常遇到(受显存限制) -
训练和推理不一致:
训练时:使用当前batch的统计量 推理时:使用running统计量(训练时累积) 问题: - 训练和推理的分布可能不同 - 需要额外存储running mean/var -
RNN/Transformer不适用:
序列任务问题: - 序列长度可变 - 不同位置的语义不同 - BatchNorm会混淆位置信息 -
分布式训练复杂:
多GPU训练: - 每个GPU的batch size更小 - 需要跨GPU同步统计量(SyncBatchNorm) - 增加通信开销 -
对小batch/单样本推理不友好:
问题场景: - 在线推理(batch=1) - 小batch微调 - 统计量不稳定
适用场景:
适合使用BatchNorm:
- CV任务(CNN)
- 大batch size训练
- 图像分类、目标检测
- batch size ≥ 16
不适合使用BatchNorm:
- NLP任务(使用LayerNorm)
- 小batch训练
- RNN、Transformer
- 序列长度可变的任务
替代方案:
| 归一化方法 | 适用场景 | 特点 |
|---|---|---|
| BatchNorm | CNN, 大batch | batch依赖 |
| LayerNorm | Transformer, RNN | batch无关 |
| InstanceNorm | 风格迁移 | 每个样本独立 |
| GroupNorm | 小batch CV | 折中方案 |
代码示例:
# CNN中使用BatchNorm
model = nn.Sequential(
nn.Conv2d(3, 64, 3),
nn.BatchNorm2d(64), # 对64个通道归一化
nn.ReLU(),
nn.Conv2d(64, 128, 3),
nn.BatchNorm2d(128),
nn.ReLU()
)
# Transformer中使用LayerNorm
class TransformerBlock(nn.Module):
def __init__(self, d_model):
super().__init__()
self.attention = MultiHeadAttention(d_model)
self.norm1 = nn.LayerNorm(d_model) # 不是BatchNorm
self.ffn = FeedForward(d_model)
self.norm2 = nn.LayerNorm(d_model)总结:
BatchNorm是CV领域的重要突破,但在NLP任务中,LayerNorm更适合。选择哪种归一化方法应该根据具体任务、网络结构和batch size来决定。
14. 简单描述一下Transformer的前馈神经网络?使用了什么激活函数?相关优缺点?
答案:
Feed-Forward Network (FFN) 结构:
架构:
FFN(x) = max(0, xW₁ + b₁)W₂ + b₂
具体来说:
输入维度: d_model (如512)
↓
第一层全连接 + ReLU
中间维度: d_ff (如2048, 通常 = 4×d_model)
↓
第二层全连接
输出维度: d_model (如512)
代码实现:
class FeedForward(nn.Module):
def __init__(self, d_model=512, d_ff=2048, dropout=0.1):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ff)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ff, d_model)
def forward(self, x):
# x shape: (batch, seq_len, d_model)
x = F.relu(self.linear1(x)) # (batch, seq_len, d_ff)
x = self.dropout(x)
x = self.linear2(x) # (batch, seq_len, d_model)
return x激活函数:ReLU
1. ReLU (Rectified Linear Unit):
ReLU(x) = max(0, x)
# 优点:
- 计算简单高效
- 缓解梯度消失(正区域梯度为1)
- 稀疏激活(部分神经元输出0)
# 缺点:
- Dead ReLU问题(神经元永久死亡)
- 梯度为0时无法学习2. 其他激活函数变体:
GELU (Gaussian Error Linear Unit):
GELU(x) = x·Φ(x)
其中 Φ(x) 是标准正态分布的累积分布函数
# 特点:
- 平滑版本的ReLU
- 在x=0附近有梯度
- BERT、GPT等模型使用
- 效果通常优于ReLUSwish:
Swish(x) = x·sigmoid(βx)
# 特点:
- 自门控激活函数
- 平滑且非单调
- 某些任务效果更好GLU (Gated Linear Unit)变体:
# 在GPT-3、PaLM等模型中使用
FFN_GLU(x) = (xW₁)⊙σ(xW₂)·W₃
# 其中 ⊙ 是逐元素乘法,σ是sigmoidFFN的特点:
1. Position-wise(位置独立):
# 对序列的每个位置应用相同的FFN
for i in range(seq_len):
output[i] = FFN(input[i])
# 等价于1×1卷积
conv1d(kernel_size=1)2. 参数不共享across层:
每个Transformer层都有自己的FFN参数
Layer 1的FFN ≠ Layer 2的FFN
3. 维度扩展-压缩:
d_model (512) → d_ff (2048) → d_model (512)
扩展4倍 压缩回原始维度
作用:
- 增加非线性表达能力
- 提供更大的特征空间
- 类似于信息的临时扩展和整合
FFN的作用:
-
增加模型容量:
- 占据Transformer约2/3的参数量
- 提供强大的非线性变换能力
-
特征转换:
- Attention关注”位置间”的交互
- FFN处理”位置内”的特征变换
-
信息整合:
Attention提取的信息 → FFN → 更高级的特征表示
参数量分析:
d_model = 512, d_ff = 2048
FFN参数量:
W₁: 512 × 2048 = 1,048,576
b₁: 2048
W₂: 2048 × 512 = 1,048,576
b₂: 512
总计:≈ 2.1M参数
对比Multi-Head Attention:
Wq, Wk, Wv, Wo: 4 × 512² ≈ 1M参数
FFN参数量约是Attention的2倍!现代变体:
1. Sparse FFN:
# Mixture of Experts (MoE)
# 每次只激活部分FFN专家
output = Σ gate_i * Expert_i(x)2. Gated FFN:
# GLU, SwiGLU等
gate = sigmoid(x @ W_gate)
output = (x @ W_1) * gate @ W_23. Adaptive FFN:
# 根据输入动态调整中间维度
d_ff = dynamic_size(x)优缺点总结:
优点:
- 简单有效的非线性变换
- 提供大量模型容量
- Position-wise独立,易于并行
缺点:
- 参数量大(约占模型2/3)
- 计算量大(尤其d_ff很大时)
- 所有位置共享参数,可能不够灵活
改进方向:
- 使用更高效的激活函数(GELU, Swish)
- 引入门控机制(GLU)
- 稀疏化(MoE)
- 动态调整(Adaptive FFN)
15. Encoder端和Decoder端是如何进行交互的?
答案:
交互机制:Cross-Attention(交叉注意力)
Encoder和Decoder通过Cross-Attention层进行交互,这是Decoder中的第二个注意力子层。
整体流程:
Encoder端:
输入序列 → Self-Attention → FFN → 输出(Memory)
Decoder端:
目标序列 → Masked Self-Attention
→ Cross-Attention (使用Encoder输出)
→ FFN
→ 输出
详细结构:
┌─────────────┐
│ Encoder │
│ ┌───────┐ │
│ │ Self │ │
│ │ Attn │ │
│ └───────┘ │
│ ↓ │
│ ┌───────┐ │
│ │ FFN │ │
│ └───────┘ │
└──────┬──────┘
│ Memory (K, V)
│
├──────────────┐
│ │
↓ ↓
┌─────────────────────────┐
│ Decoder │
│ ┌──────────────────┐ │
│ │ Masked Self-Attn │ │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ Cross-Attention │ │ ← 交互发生在这里
│ │ Q from Decoder │ │
│ │ K,V from Encoder │ │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ FFN │ │
│ └──────────────────┘ │
└─────────────────────────┘
Cross-Attention的数学实现:
# Encoder输出(称为Memory)
encoder_output = Encoder(source_sequence)
# shape: (batch, source_len, d_model)
# Decoder中的Cross-Attention
class CrossAttention:
def forward(self, decoder_hidden, encoder_output):
# Query来自Decoder的前一层输出
Q = decoder_hidden @ W_Q
# shape: (batch, target_len, d_model)
# Key和Value来自Encoder输出
K = encoder_output @ W_K
V = encoder_output @ W_V
# shape: (batch, source_len, d_model)
# 计算注意力
scores = Q @ K.transpose(-2, -1) / sqrt(d_k)
# shape: (batch, target_len, source_len)
attention_weights = softmax(scores, dim=-1)
output = attention_weights @ V
# shape: (batch, target_len, d_model)
return output具体交互过程:
1. Encoder处理源序列:
# 例如:翻译任务
source = ["I", "love", "AI"]
encoder_output = Encoder(source)
# encoder_output作为Memory,包含源序列的完整信息2. Decoder逐步生成:
# 生成目标序列: ["我", "爱", "AI"]
# Step 1: 生成"我"
target = ["<START>"]
decoder_hidden = MaskedSelfAttention(target)
# Cross-Attention:
# Q from "我" (decoder)
# K,V from ["I", "love", "AI"] (encoder)
# Decoder可以看到所有源词来决定生成什么
# Step 2: 生成"爱"
target = ["<START>", "我"]
# Cross-Attention:
# Q from "我", "爱" 的位置 (decoder)
# K,V from ["I", "love", "AI"] (encoder)3. Attention Weights的含义:
# Cross-Attention的权重矩阵
attention_weights.shape = (target_len, source_len)
例如翻译 "I love AI" → "我爱AI"
I love AI
我 [0.7 0.2 0.1] # "我"主要关注"I"
爱 [0.1 0.8 0.1] # "爱"主要关注"love"
AI [0.1 0.1 0.8] # "AI"主要关注"AI"交互的三种注意力对比:
| 注意力类型 | Q来源 | K来源 | V来源 | 作用 |
|---|---|---|---|---|
| Encoder Self-Attention | Encoder输入 | Encoder输入 | Encoder输入 | 理解源序列内部关系 |
| Decoder Self-Attention | Decoder输入 | Decoder输入 | Decoder输入 | 理解目标序列内部关系 |
| Cross-Attention | Decoder | Encoder | Encoder | 连接源和目标序列 |
代码实现完整示例:
class DecoderLayer(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
# 1. Masked Self-Attention
self.self_attn = MultiHeadAttention(d_model, num_heads)
self.norm1 = nn.LayerNorm(d_model)
# 2. Cross-Attention (交互发生在这里)
self.cross_attn = MultiHeadAttention(d_model, num_heads)
self.norm2 = nn.LayerNorm(d_model)
# 3. Feed-Forward
self.ffn = FeedForward(d_model)
self.norm3 = nn.LayerNorm(d_model)
def forward(self, x, encoder_output, src_mask=None, tgt_mask=None):
# 1. Masked Self-Attention
attn_output = self.self_attn(x, x, x, tgt_mask)
x = self.norm1(x + attn_output)
# 2. Cross-Attention (关键交互)
# Q from decoder, K,V from encoder
cross_output = self.cross_attn(
query=x, # 来自Decoder
key=encoder_output, # 来自Encoder
value=encoder_output, # 来自Encoder
mask=src_mask
)
x = self.norm2(x + cross_output)
# 3. Feed-Forward
ff_output = self.ffn(x)
x = self.norm3(x + ff_output)
return x实际应用场景:
-
机器翻译:
- Encoder: 理解源语言
- Cross-Attention: 对齐源语言和目标语言
- Decoder: 生成目标语言
-
文本摘要:
- Encoder: 编码原文
- Cross-Attention: 选择重要信息
- Decoder: 生成摘要
-
问答系统:
- Encoder: 编码问题
- Cross-Attention: 在上下文中查找答案
- Decoder: 生成回答
总结:
Encoder和Decoder的交互核心是Cross-Attention机制:
- Decoder的Query询问”我现在应该关注源序列的哪部分”
- Encoder的Key和Value提供”源序列的信息”
- 通过注意力权重实现动态的、软性的对齐
- 这是Seq2Seq任务的关键,使得Decoder能够”看到”并利用源序列信息
16. Transformer的并行化体现在哪个地方?Decoder端可以做并行化吗?
答案:
Transformer的并行化体现:
1. Encoder端的完全并行化:
Self-Attention的并行:
# 传统RNN:必须序列处理
for t in range(seq_len):
h_t = RNN(x_t, h_{t-1}) # 依赖前一时刻
# 无法并行!
# Transformer Self-Attention:完全并行
Q = X @ W_Q # 所有位置同时计算
K = X @ W_K # 矩阵乘法,GPU高度优化
V = X @ W_V
Attention = softmax(QK^T / √d_k) @ V
# 一次性计算所有位置的注意力,完全并行!并行的维度:
输入: (batch_size, seq_len, d_model)
并行维度1: batch_size 维度
- 不同样本可以并行处理
并行维度2: seq_len 维度
- 序列中所有位置可以并行处理(关键优势)
- 与RNN的最大区别
并行维度3: num_heads 维度
- 多个注意力头并行计算
2. Decoder端的并行化:
训练时(Training):可以并行化
使用Teacher Forcing和Masked Self-Attention实现并行:
# 训练时的输入输出
# 源序列: "I love AI"
# 目标序列: "<START> 我 爱 AI <END>"
# 传统RNN Decoder:序列处理
t=0: generate("我" | "<START>")
t=1: generate("爱" | "<START>", "我")
t=2: generate("AI" | "<START>", "我", "爱")
# 无法并行
# Transformer Decoder:并行处理(训练时)
target_input = ["<START>", "我", "爱", "AI"]
target_output = ["我", "爱", "AI", "<END>"]
# 一次性计算所有位置!
logits = Decoder(target_input, encoder_output)
# shape: (batch, target_len, vocab_size)
loss = CrossEntropy(logits, target_output)关键:Masked Self-Attention
# Mask矩阵确保每个位置只能看到之前的位置
# 例如seq_len=4的mask:
mask = [
[1, 0, 0, 0], # 位置0只能看到自己
[1, 1, 0, 0], # 位置1可以看到0,1
[1, 1, 1, 0], # 位置2可以看到0,1,2
[1, 1, 1, 1] # 位置3可以看到0,1,2,3
]
# 在attention计算时应用
scores = scores.masked_fill(mask == 0, -1e9)
attention = softmax(scores)
# 这样虽然并行计算,但保证了因果性!训练时的并行流程:
def train_step(source, target):
# 1. Encoder并行处理源序列
encoder_output = Encoder(source) # 完全并行
# 2. Decoder并行处理目标序列
# 使用mask确保因果性
target_input = target[:-1] # 去掉<END>
decoder_output = Decoder(
target_input,
encoder_output,
tgt_mask=create_causal_mask(len(target_input))
) # 并行计算所有位置!
# 3. 并行计算所有位置的loss
target_output = target[1:] # 去掉<START>
loss = criterion(decoder_output.reshape(-1, vocab_size),
target_output.reshape(-1))
return loss推理时(Inference):无法完全并行化
# 推理时必须自回归生成
def generate(source, max_len=100):
encoder_output = Encoder(source)
# 从<START>开始
generated = ["<START>"]
# 必须逐个生成token
for _ in range(max_len):
# 每次都需要等待前一个token生成
decoder_output = Decoder(generated, encoder_output)
# 预测下一个token
next_token = argmax(decoder_output[-1])
generated.append(next_token)
if next_token == "<END>":
break
return generated
# 无法并行:必须等第t步完成才能进行t+1步并行化对比总结:
| 模块 | 训练时 | 推理时 | 原因 |
|---|---|---|---|
| Encoder | ✓ 完全并行 | ✓ 完全并行 | 无依赖关系 |
| Decoder | ✓ 并行(有mask) | ✗ 串行 | 推理时自回归 |
为什么推理时Decoder不能并行:
推理过程:
t=0: 预测token_1,需要依赖:<START>
t=1: 预测token_2,需要依赖:<START>, token_1 ← 必须等token_1生成
t=2: 预测token_3,需要依赖:<START>, token_1, token_2 ← 必须等token_2生成
...
问题:不知道token_1是什么,就无法预测token_2
不知道token_2是什么,就无法预测token_3
结论:必须串行生成
加速推理的方法:
-
Batch Inference:
# 虽然单个序列串行,但可以并行处理多个序列 outputs = [] for batch in batches: outputs.append(generate(batch)) # batch内并行 -
KV Cache:
# 缓存已计算的Key和Value # 避免重复计算 cached_k, cached_v = [], [] for step in range(max_len): new_k, new_v = compute_kv(current_token) cached_k.append(new_k) cached_v.append(new_v) # 下一步直接使用缓存 -
Speculative Decoding:
# 使用小模型预测多个token # 用大模型验证 # 可以实现一定程度的并行
为什么Transformer比RNN快:
训练速度对比:
RNN:
- Encoder: 串行 (seq_len步)
- Decoder: 串行 (seq_len步)
- 总时间: O(seq_len)
Transformer:
- Encoder: 并行 (1步)
- Decoder: 并行 (1步,训练时)
- 总时间: O(1)
加速比: seq_len倍!(训练时)
总结:
- Encoder:完全并行化(训练和推理)
- Decoder训练:使用masked attention实现并行,但保证因果性
- Decoder推理:必须串行,这是自回归生成的本质限制
- 核心优势:训练时的大规模并行化,使得Transformer能够高效利用GPU
这就是为什么Transformer能够成功取代RNN——训练效率的巨大提升!
17. 描述一下wordpiece model和byte pair encoding?Dropout是如何设定的,位置在哪里?Dropout在测试时需要有什么需要注意的吗?
答案部分1:Tokenization方法
1. Byte Pair Encoding (BPE):
基本原理:
- 最初由数据压缩算法演化而来
- 迭代地合并最频繁出现的字节对
算法流程:
1. 初始化:每个字符作为一个token
"low" → ["l", "o", "w"]
"lower" → ["l", "o", "w", "e", "r"]
2. 统计相邻token对的频率
"lo": 出现2次
"ow": 出现2次
...
3. 合并最频繁的pair
假设"lo"最频繁 → 合并为"lo"
"low" → ["lo", "w"]
"lower" → ["lo", "w", "e", "r"]
4. 重复步骤2-3,直到词表大小达到预设值(如32K)
最终词表:
["l", "o", "w", "e", "r", "lo", "low", "er", "lower", ...]
代码示例:
# BPE编码示例
vocab = ["l", "o", "w", "lo", "low", "er"]
def bpe_encode(word, vocab):
# "lower" → ["l", "o", "w", "e", "r"]
tokens = list(word)
while True:
pairs = get_pairs(tokens)
if not pairs:
break
# 找到词表中最优的pair
best_pair = min(pairs, key=lambda p: vocab.index(p) if p in vocab else float('inf'))
if best_pair not in vocab:
break
tokens = merge(tokens, best_pair)
return tokens
# "lower" → ["low", "er"]优点:
- 平衡字符级和词级
- 可以处理OOV(未登录词)
- GPT-2, GPT-3使用
2. WordPiece Model:
与BPE的区别:
- BPE基于频率合并
- WordPiece基于似然概率合并
算法流程:
1. 初始化同BPE
2. 计算合并后的似然增益
Score(pair) = P(pair) / (P(first) × P(second))
例如:
P("lo") = 100/1000
P("l") = 200/1000
P("o") = 200/1000
Score = 0.1 / (0.2 × 0.2) = 2.5
3. 选择Score最高的pair合并
4. 重复直到达到词表大小
特点:
# WordPiece使用##前缀标记子词
"playing" → ["play", "##ing"]
"unwanted" → ["un", "##want", "##ed"]
# ##表示这不是词的开始代码示例:
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
text = "unwanted playing"
tokens = tokenizer.tokenize(text)
# ['un', '##want', '##ed', 'play', '##ing']
ids = tokenizer.convert_tokens_to_ids(tokens)
# [2618, 17765, 2098, 2377, 2075]应用:
- BERT使用WordPiece
- 词表大小通常30K
3. BPE vs WordPiece对比:
| 特性 | BPE | WordPiece |
|---|---|---|
| 合并标准 | 频率 | 似然 |
| 子词标记 | 无特殊标记 | ##前缀 |
| 实现复杂度 | 简单 | 稍复杂 |
| 应用模型 | GPT系列 | BERT, ALBERT |
| 效果 | 相近 | 相近 |
答案部分2:Dropout设定
Dropout的位置:
1. Attention层的Dropout:
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads, dropout=0.1):
super().__init__()
self.dropout = nn.Dropout(dropout)
def forward(self, Q, K, V, mask=None):
# 计算attention scores
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# Attention weights dropout
attention = F.softmax(scores, dim=-1)
attention = self.dropout(attention) # ← Dropout位置1
output = torch.matmul(attention, V)
return output2. Feed-Forward层的Dropout:
class FeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ff)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ff, d_model)
def forward(self, x):
x = F.relu(self.linear1(x))
x = self.dropout(x) # ← Dropout位置2
x = self.linear2(x)
return x3. 残差连接后的Dropout:
class TransformerLayer(nn.Module):
def forward(self, x):
# Multi-Head Attention
attn_output = self.attention(x)
attn_output = self.dropout(attn_output) # ← Dropout位置3
x = self.norm1(x + attn_output)
# Feed-Forward
ff_output = self.ffn(x)
ff_output = self.dropout(ff_output) # ← Dropout位置4
x = self.norm2(x + ff_output)
return x4. Embedding层的Dropout(可选):
class TransformerEmbedding(nn.Module):
def __init__(self, vocab_size, d_model, dropout=0.1):
super().__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.pos_encoding = PositionalEncoding(d_model)
self.dropout = nn.Dropout(dropout) # ← Dropout位置5
def forward(self, x):
x = self.embedding(x) * math.sqrt(self.d_model)
x = self.pos_encoding(x)
x = self.dropout(x) # ← 应用dropout
return xDropout率设定:
# 典型设置(原始Transformer论文)
dropout_rate = 0.1 # 10%
# BERT的设置
dropout_attention = 0.1 # attention dropout
dropout_hidden = 0.1 # hidden层dropout
# GPT系列
dropout_rate = 0.1 # 或更高,如0.2
# 大模型训练
dropout_rate = 0.0 # 很多大模型不用dropout,依靠大数据量Dropout在测试时的注意事项:
1. 关闭Dropout:
# 训练模式
model.train()
output = model(input) # Dropout激活
# 评估/测试模式
model.eval()
output = model(input) # Dropout关闭2. Dropout的数学原理:
训练时:
def dropout_train(x, p=0.1):
# 以概率p随机置0
mask = (torch.rand_like(x) > p).float()
# 缩放保持期望不变
return x * mask / (1 - p)
# 期望:E[output] = E[x * mask / (1-p)]
# = x * p*0/(1-p) + x * (1-p)*1/(1-p)
# = x测试时:
def dropout_test(x, p=0.1):
# 直接返回输入,不做任何处理
return x
# 因为训练时已经缩放过,测试时期望自然匹配3. 实现示例:
class Dropout(nn.Module):
def __init__(self, p=0.1):
super().__init__()
self.p = p
def forward(self, x):
if not self.training: # 测试模式
return x
# 训练模式
keep_prob = 1 - self.p
mask = (torch.rand_like(x) < keep_prob).float()
return x * mask / keep_prob # 缩放4. 常见错误:
# ❌ 错误:测试时忘记关闭dropout
model.eval() # 必须调用!
with torch.no_grad():
output = model(input)
# ❌ 错误:手动实现dropout但忘记缩放
def wrong_dropout(x, p=0.1):
mask = (torch.rand_like(x) > p).float()
return x * mask # 缺少 / (1-p),会导致测试时输出偏小
# ✓ 正确
def correct_dropout(x, p=0.1):
if not training:
return x
mask = (torch.rand_like(x) > p).float()
return x * mask / (1 - p) # 正确缩放5. PyTorch自动处理:
# PyTorch的nn.Dropout自动处理训练/测试模式
dropout = nn.Dropout(p=0.1)
# 训练
model.train()
x_train = dropout(x) # 随机置0 + 缩放
# 测试
model.eval()
x_test = dropout(x) # 恒等映射,不做任何处理总结:
Tokenization:
- BPE:基于频率,简单有效
- WordPiece:基于似然,效果相近
- 都能处理OOV,平衡词级和字符级
Dropout:
- 位置:attention权重、FFN隐层、残差连接、embedding
- 训练:随机置0并缩放
- 测试:必须关闭(model.eval())
- 忘记切换模式会导致性能下降!
18. Transformer训练的时候学习率是如何设定的?
答案:
Transformer使用特殊的学习率调度策略,核心是Warm-up + Decay机制。
原论文的学习率调度(Noam Scheduler):
公式:
lr = d_model^(-0.5) × min(step^(-0.5), step × warmup_steps^(-1.5))
其中:
- d_model: 模型维度(如512)
- step: 当前训练步数
- warmup_steps: 预热步数(通常4000-8000)
两个阶段:
1. Warm-up阶段(step < warmup_steps):
lr = d_model^(-0.5) × step × warmup_steps^(-1.5)
= d_model^(-0.5) × (step / warmup_steps^1.5)
特点:学习率线性增长
2. Decay阶段(step ≥ warmup_steps):
lr = d_model^(-0.5) × step^(-0.5)
= d_model^(-0.5) / sqrt(step)
特点:学习率按平方根衰减
可视化示例:
import matplotlib.pyplot as plt
import numpy as np
def noam_scheduler(step, d_model=512, warmup_steps=4000):
step = max(step, 1) # 避免除零
lr = d_model**(-0.5) * min(
step**(-0.5),
step * warmup_steps**(-1.5)
)
return lr
steps = np.arange(1, 20000)
lrs = [noam_scheduler(s) for s in steps]
plt.plot(steps, lrs)
plt.xlabel('Step')
plt.ylabel('Learning Rate')
plt.title('Noam Learning Rate Schedule')
# 学习率曲线:
# 0-4000步:快速上升
# 4000步后:缓慢下降代码实现:
class NoamScheduler:
def __init__(self, d_model, warmup_steps=4000):
self.d_model = d_model
self.warmup_steps = warmup_steps
self.step_num = 0
def step(self):
self.step_num += 1
lr = self._get_lr()
return lr
def _get_lr(self):
step = self.step_num
arg1 = step ** (-0.5)
arg2 = step * (self.warmup_steps ** (-1.5))
return (self.d_model ** (-0.5)) * min(arg1, arg2)
# 使用
scheduler = NoamScheduler(d_model=512, warmup_steps=4000)
for epoch in range(num_epochs):
for batch in dataloader:
optimizer.zero_grad()
loss = model(batch)
loss.backward()
optimizer.step()
# 更新学习率
lr = scheduler.step()
for param_group in optimizer.param_groups:
param_group['lr'] = lrPyTorch实现:
import torch.optim as optim
# 方法1:手动实现
optimizer = optim.Adam(model.parameters(), lr=1.0, betas=(0.9, 0.98), eps=1e-9)
def get_lr(step, d_model=512, warmup_steps=4000):
step = max(step, 1)
return d_model**(-0.5) * min(step**(-0.5), step * warmup_steps**(-1.5))
# 训练循环
for step in range(max_steps):
lr = get_lr(step)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
# 训练代码...
# 方法2:使用LambdaLR
from torch.optim.lr_scheduler import LambdaLR
def lr_lambda(step):
d_model = 512
warmup_steps = 4000
step = max(step, 1)
return (d_model ** -0.5) * min(step ** -0.5, step * warmup_steps ** -1.5)
optimizer = optim.Adam(model.parameters(), lr=1.0)
scheduler = LambdaLR(optimizer, lr_lambda)
for epoch in range(num_epochs):
for batch in dataloader:
# 训练代码
optimizer.step()
scheduler.step() # 更新学习率为什么需要Warm-up?
1. 避免训练初期的不稳定:
问题:
- 参数初始化是随机的
- 初始梯度可能很大
- 大学习率 + 大梯度 = 梯度爆炸
解决:
- Warm-up从小学习率开始
- 逐步增加到最大值
- 让模型"热身"
2. 适应Adam优化器:
Adam优化器:
- 维护梯度的一阶矩(均值)和二阶矩(方差)
- 初期这些统计量不准确
- Warm-up给予时间让统计量稳定
3. 避免陷入局部最优:
小学习率开始:
- 温和地探索参数空间
- 避免直接跳到糟糕的局部最优
典型参数设置:
原始Transformer(Base):
d_model = 512
warmup_steps = 4000
optimizer = Adam(
lr=1.0, # 会被scheduler调整
betas=(0.9, 0.98),
eps=1e-9
)BERT:
# BERT使用不同的策略
warmup_ratio = 0.1 # 总步数的10%用于warm-up
total_steps = len(dataloader) * num_epochs
warmup_steps = int(total_steps * warmup_ratio)
learning_rate = 5e-5 # 峰值学习率
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=total_steps
)GPT系列:
# GPT也使用cosine decay
learning_rate = 6e-4
warmup_iters = 2000
lr_decay_iters = 600000
# Cosine annealing with warmup
def get_lr(step):
if step < warmup_iters:
return learning_rate * step / warmup_iters
if step > lr_decay_iters:
return min_lr
# Cosine decay
decay_ratio = (step - warmup_iters) / (lr_decay_iters - warmup_iters)
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
return min_lr + coeff * (learning_rate - min_lr)现代实践中的变体:
1. Linear Warmup + Linear Decay:
from transformers import get_linear_schedule_with_warmup
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=1000,
num_training_steps=10000
)
# 学习率变化:
# 0-1000步:0 → peak
# 1000-10000步:peak → 0(线性)2. Cosine Annealing with Warmup:
from transformers import get_cosine_schedule_with_warmup
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=1000,
num_training_steps=10000
)
# 学习率变化:
# 0-1000步:0 → peak(线性)
# 1000-10000步:peak → min(余弦曲线)调参建议:
# 小模型/小数据集
warmup_steps = 500 - 2000
peak_lr = 1e-4 to 5e-4
# 大模型/大数据集
warmup_steps = 2000 - 10000
peak_lr = 1e-4 to 1e-3
# BERT风格微调
warmup_ratio = 0.1 # 10% warmup
peak_lr = 2e-5 to 5e-5
# GPT风格预训练
warmup_iters = 2000
peak_lr = 6e-4总结:
Transformer学习率调度的关键点:
- Warm-up:从0逐步增加到峰值(避免初期不稳定)
- Decay:从峰值逐步衰减(平滑收敛)
- 具体策略:
- 原始Transformer:Noam(平方根衰减)
- BERT:Linear warmup + Linear decay
- GPT:Linear warmup + Cosine decay
- 核心思想:先热身,再稳定训练,最后精细调优
这种策略是Transformer训练成功的重要因素之一!
19. Dropout是如何设定的?
答案:
(此问题与第17题重复,这里提供简化版本)
Dropout在Transformer中的设定:
1. Dropout位置(5个关键位置):
class TransformerLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout=0.1):
super().__init__()
self.attention = MultiHeadAttention(d_model, num_heads)
self.ffn = FeedForward(d_model, d_ff)
# 位置1: Attention权重dropout
self.attn_dropout = nn.Dropout(dropout)
# 位置2: Attention输出dropout
self.attn_output_dropout = nn.Dropout(dropout)
# 位置3: FFN中间层dropout
self.ffn_dropout = nn.Dropout(dropout)
# 位置4: FFN输出dropout
self.ffn_output_dropout = nn.Dropout(dropout)
# 位置5: Embedding dropout(在Embedding层)
# self.emb_dropout = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x, mask=None):
# 1. Multi-Head Attention
attn_output = self.attention(x, x, x, mask)
attn_output = self.attn_output_dropout(attn_output) # Dropout
x = self.norm1(x + attn_output)
# 2. Feed-Forward
ff_output = self.ffn(x) # 内部有dropout
ff_output = self.ffn_output_dropout(ff_output) # Dropout
x = self.norm2(x + ff_output)
return x2. 典型Dropout率设置:
# 原始Transformer论文
dropout = 0.1 # 所有位置统一使用10%
# BERT
hidden_dropout_prob = 0.1
attention_probs_dropout_prob = 0.1
# GPT-2
dropout = 0.1
attn_dropout = 0.1
resid_dropout = 0.1 # 残差连接dropout
# GPT-3 (175B)
dropout = 0.0 # 超大模型不用dropout
# RoBERTa
dropout = 0.1
# ALBERT
dropout = 0.13. 不同模型大小的设置:
| 模型规模 | Dropout率 | 原因 |
|---|---|---|
| 小模型 (<100M) | 0.1-0.3 | 防止过拟合 |
| 中等模型 (100M-1B) | 0.1 | 标准设置 |
| 大模型 (>10B) | 0.0-0.1 | 大数据量,regularization需求小 |
4. 完整实现示例:
class Transformer(nn.Module):
def __init__(self, vocab_size, d_model=512, num_heads=8,
num_layers=6, d_ff=2048, dropout=0.1):
super().__init__()
# Embedding + Dropout
self.embedding = nn.Embedding(vocab_size, d_model)
self.pos_encoding = PositionalEncoding(d_model)
self.emb_dropout = nn.Dropout(dropout) # 位置5
# Transformer Layers
self.layers = nn.ModuleList([
TransformerLayer(d_model, num_heads, d_ff, dropout)
for _ in range(num_layers)
])
def forward(self, x, mask=None):
# Embedding
x = self.embedding(x) * math.sqrt(self.d_model)
x = self.pos_encoding(x)
x = self.emb_dropout(x) # Embedding dropout
# Transformer layers
for layer in self.layers:
x = layer(x, mask)
return x5. Attention中的Dropout:
def scaled_dot_product_attention(Q, K, V, mask=None, dropout=0.1):
d_k = Q.size(-1)
# 计算attention scores
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# Softmax + Dropout
attention = F.softmax(scores, dim=-1)
if dropout is not None:
attention = F.dropout(attention, p=dropout, training=True) # 关键
output = torch.matmul(attention, V)
return output, attention6. 训练vs测试模式:
# 训练模式
model.train()
output = model(input) # Dropout激活(随机置0)
# 测试模式
model.eval()
with torch.no_grad():
output = model(input) # Dropout关闭(恒等映射)
# 必须切换模式,否则结果不正确!7. 调参建议:
根据数据量:
if dataset_size < 10K:
dropout = 0.2 - 0.3 # 较大dropout
elif dataset_size < 100K:
dropout = 0.1 - 0.2 # 中等dropout
else:
dropout = 0.1 # 标准dropout根据任务:
# 分类任务(容易过拟合)
dropout = 0.1 - 0.2
# 生成任务(需要多样性)
dropout = 0.1
# 预训练(大数据)
dropout = 0.0 - 0.1根据模型深度:
if num_layers < 6:
dropout = 0.1
elif num_layers < 12:
dropout = 0.1 - 0.15
else: # 很深的模型
dropout = 0.1 - 0.28. 现代改进:
DropPath(Stochastic Depth):
# 随机丢弃整个layer
def drop_path(x, drop_prob=0.1, training=True):
if not training or drop_prob == 0:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, device=x.device)
random_tensor.floor_()
return x.div(keep_prob) * random_tensorLayerDrop:
# 训练时随机跳过某些层
# 推理时使用所有层或子集
class TransformerWithLayerDrop(nn.Module):
def forward(self, x, layerdrop_prob=0.1):
for layer in self.layers:
if not self.training or random.random() > layerdrop_prob:
x = layer(x)
return x总结:
Dropout设定原则:
- 标准值:0.1(10%)适用于大多数情况
- 小数据:增大到0.2-0.3
- 大模型:减小到0或很小值
- 位置:5个关键位置都使用
- 一致性:通常所有位置使用相同的dropout率
- 模式切换:训练和测试必须正确切换(model.train()/model.eval())
Dropout是防止过拟合的重要手段,但在超大模型和海量数据的时代,其重要性有所下降。
20. Bert的mask为何不学习transformer在attention处进行屏蔽score的技巧?
答案:
这是一个关于BERT的Masked Language Model (MLM)和Transformer Decoder的Causal Masking区别的问题。
两种Mask的本质区别:
1. Transformer Decoder的Causal Mask:
目的:防止看到未来的信息(自回归生成)
实现:在attention score上mask
# Causal Mask: 只能看到当前和之前的位置
mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1)
# mask = [[0, 1, 1, 1],
# [0, 0, 1, 1],
# [0, 0, 0, 1],
# [0, 0, 0, 0]] # 1表示mask掉
scores = scores.masked_fill(mask == 1, -1e9)
attention = softmax(scores) # 未来位置的权重变为0特点:
- 所有token都参与计算
- 只是attention权重被约束
- 用于自回归生成
2. BERT的Masked Language Model:
目的:通过预测被mask的词来学习语言表示
实现:在输入层直接替换token
# MLM: 随机替换15%的token
input = ["The", "cat", "sat", "on", "mat"]
# 80%概率替换为[MASK]
masked = ["The", "[MASK]", "sat", "on", "mat"]
# 10%概率替换为随机词
masked = ["The", "dog", "sat", "on", "mat"]
# 10%概率保持不变
masked = ["The", "cat", "sat", "on", "mat"]特点:
- 被mask的token在输入时就不可见
- Attention可以看到所有位置(双向)
- 用于预训练表示学习
为什么BERT不用Attention Masking:
1. 训练目标不同:
Transformer Decoder (GPT):
- 任务:自回归生成
- 目标:P(w_t | w_1, ..., w_{t-1})
- 需求:严格的因果约束
- 方法:Attention mask
BERT:
- 任务:完形填空
- 目标:P(w_masked | context)
- 需求:双向上下文
- 方法:Input masking
2. 双向上下文的需求:
# BERT需要利用双向信息
sentence = "The cat sat on the mat"
mask = "The [MASK] sat on the mat"
# 预测[MASK]需要:
# - 左侧上下文:"The"
# - 右侧上下文:"sat on the mat"
# ← 双向!
# 如果使用Causal Mask,只能看到左侧:
# "The [MASK]" ← 信息不足,难以预测3. 技术实现的差异:
Transformer Decoder (Attention Masking):
# 所有token都在输入中
input = ["The", "cat", "sat", "on", "mat"]
Q = K = V = embed(input)
# 在attention计算时mask
scores = Q @ K.T / sqrt(d_k)
scores = scores.masked_fill(causal_mask, -1e9)
attention = softmax(scores) # 未来位置权重为0
# 所有位置都有梯度,都在学习BERT (Input Masking):
# 部分token被替换
input = ["The", "[MASK]", "sat", "on", "mat"]
embeddings = embed(input) # [MASK]有自己的embedding
# Attention可以看到所有位置
scores = Q @ K.T / sqrt(d_k)
attention = softmax(scores) # 全局attention,无mask
# 只有被mask的位置有预测任务
loss = CrossEntropy(output[1], target="cat") # 只计算位置1的loss4. 为什么这样设计更好:
BERT的优势(Input Masking + Bidirectional):
1. 充分利用上下文:
"The [MASK] sat on the mat"
- 左侧:"The" → 可能是名词
- 右侧:"sat" → 是动物或人
→ 双向信息帮助预测
2. 更强的表示能力:
- BERT在很多NLU任务上优于GPT
- 双向上下文提供更丰富的语义
3. 适合下游任务:
- 分类、问答、NER等都需要双向理解
- BERT预训练的表示可以直接使用
GPT的优势(Attention Masking + Causal):
1. 适合生成任务:
- 自回归生成需要因果约束
- 训练和推理一致
2. 简单直接:
- 不需要特殊的mask token
- 所有位置都在学习
3. Zero-shot能力:
- 大模型可以直接做任务
- 不需要微调
实验对比:
| 特性 | BERT (Input Mask) | GPT (Attention Mask) |
|---|---|---|
| 上下文 | 双向 | 单向(从左到右) |
| 预训练任务 | MLM | 自回归语言模型 |
| 适合任务 | NLU(理解) | NLG(生成) |
| GLUE分数 | 更高 | 较低 |
| 生成质量 | 不适合 | 更好 |
如果BERT使用Attention Mask会怎样?
# 假设BERT使用Causal Mask
input = ["The", "[MASK]", "sat", "on", "mat"]
# 位置1([MASK])只能看到位置0
attention_context = ["The"] # 只有左侧
# 预测难度大大增加,效果会变差总结:
为什么BERT不用Attention Masking:
-
任务需求不同:
- BERT:完形填空,需要双向上下文
- GPT:自回归生成,需要因果约束
-
设计理念不同:
- BERT:通过input masking + 双向attention学习表示
- GPT:通过attention masking保持因果性
-
效果验证:
- BERT的双向设计在NLU任务上表现更好
- 证明了input masking的有效性
两者是针对不同目标的不同设计选择,都是合理且有效的。
关键insight:
- GPT:Mask未来→适合生成
- BERT:Mask输入→适合理解