Transformer 架构
核对 Transformer 编码器-解码器四阶段流程、正弦位置编码相对旋转恒等式、Post-LN 与 O(n²) 显存增长实测,完整处置来源 3 处 KaTeX 嵌入脚本并绘制位置编码双联图。
学完这一章,你能够
- 核对 Transformer 编码器-解码器四阶段流程、正弦位置编码相对旋转恒等式、Post-LN 与 O(n²) 显存增长实测,完整处置来源 3 处 KaTeX 嵌入脚本并绘制位置编码双联图。
Transformer 架构总览与四阶段数据流
Transformer 架构由 Google 团队于 2017 年论文《Attention Is All You Need》(arXiv:1706.03762)提出,它完全摒弃循环与卷积结构,仅依赖自注意力机制即可并行处理整个序列并直接建立全局依赖,成为 BERT、GPT 等现代大语言模型的共同基石。在经典的左右双塔架构图中,左侧为编码器、右侧为解码器,数据首先经底部输入处理层的嵌入/投影(Embeddings/Projections)将离散 token 映射为携带语义的连续数字向量(如将“猫”映射为稠密实数向量)。
编码器(左侧)由多层相同子块堆叠:多头自注意力并行计算序列所有词之间的关联(例如在“猫追老鼠”中区分实体与动词的依存强度),层归一化(LayerNorm)把激活尺度稳定在合适区间,前馈神经网络(FFN)对每个位置独立做非线性特征精加工。解码器(右侧)在此基础上增加掩码多头自注意力(防止预测下一个词时“偷看”未来 token,如生成“我爱__”时仅可见“我”“爱”)与多头交叉注意力(让解码器按需查询编码器产出的源序列表示),随后经层归一化与前馈网络输出至顶部 Linear 线性层与 Softmax,将隐状态投影为词表概率分布以预测下一词。
核心组件原理与编码器-解码器堆叠实测
Transformer 的核心公式为缩放点积注意力 Attention(Q, K, V) = softmax(QKᵀ / √d_k) V,其中 Q、K、V 由输入线性投影得到,缩放因子 √d_k 防止高维点积过大导致 Softmax 梯度消失(来源开篇简化代码省略了 `/ √d_k`,正文公式及练习 1 完整版已补全)。多头注意力并行运行多组子空间注意力后拼接以同时捕捉局部/全局与语法/语义模式;由于架构本身无循环或卷积,必须显式叠加正弦/余弦或可学习位置编码以注入序列顺序。
每个位置随后通过两层全连接前馈网络 FFN(x) = max(0, xW₁ + b₁)W₂ + b₂ 完成逐位置非线性变换,并借助残差连接 x + Sublayer(x) 缓解深层梯度消失、借助层归一化加速稳定收敛。原始架构将上述模块堆叠构成编码器与解码器(下表 1 汇总编码器四大组件),解码器额外引入掩码多头自注意力与编码器-解码器交叉注意力。本站纯 NumPy 搭建完整编码器块与解码器块(src_len = 6、tgt_len = 4、d_model = 32、4 头、d_ff = 64、词表 20)实测:输出形状精确为编码器 [1, 6, 32]、交叉注意力 [1, 4, 4, 6] 与词表概率 [1, 4, 20],LayerNorm 后逐位置均值绝对误差仅 2.08e-17、标准差误差 4.58e-06;扰动编码器记忆后解码器输出平均响应变化 0.5666,而施加下三角因果掩码后大幅扰动未来位置 t >= 3 对前序 0..2 输出影响精确为 0.0(未来权重上限 0.0)。
正弦位置编码数学特性与相对位置旋转验证
正弦位置编码对偶数维 2i 采用 PE(pos, 2i) = sin(pos / 10000^(2i / d_model))、对奇数维 2i+1 采用 PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model)),其中 pos 为词在序列中的位置索引,i 满足 0 ≤ i < d_model / 2,d_model 通常与词向量维度(如 512、768)一致。该编码具备确定性免学习、可外推至长于训练窗口的序列长度、且对相对位置敏感三大特性:对任意固定偏移 k,均存在与绝对位置 pos 无关的 2×2 频率旋转矩阵将 PE(pos) 精确线性映射至 PE(pos + k)。本站生成长度 256、维度 64 的位置编码矩阵实测:全部数值落在 [-1.0, 1.0],对 k = 7 跨 pos = 0, 5, 19, 120, 200 核验线性旋转恒等式最大绝对误差仅 8.99e-15,且相邻位置余弦相似度随间距平滑衰减(距 1 步 0.9662 → 距 5 步 0.7345 → 距 15 步 0.6084)。下图汇总本次实测的位置编码矩阵热力图与 50×50 位置余弦相似度矩阵(对应练习 2)。
架构对比、O(n²) 显存瓶颈与实践答疑
与 RNN/LSTM 和 CNN 相比(详见下表 2),Transformer 兼具完全并行计算与任意两词间直接建模优势,展现出卓越的基准表现、规模可扩展性(如 GPT-3)、跨文本/图像/语音多模态适应力以及“预训练+微调”迁移友好度。实践练习 1 的掩码缩放点积注意力(mask == 0 处填充 -1e9,注:FP16 半精度下需改用 -1e4 或 -inf 避免溢出)与练习 2 的位置编码可视化及相似度分析均已在本站独立实验脚本中完整复现并核验通过。
常见疑问集中于三点:(1)为何比 RNN 更适合长文本——RNN 须逐步递归传递状态导致远距信息衰减,而 Transformer 任意两位置直连交互;(2)为何选择正弦函数——周期组合允许以线性变换表达相对偏移并自然外推至未见长度;(3)核心计算瓶颈在哪——自注意力得分矩阵空间与计算复杂度均为 O(n²),长序列显存急剧增长。本站实测序列长度从 32 依次翻倍至 64、128、256,单头注意力矩阵元素数精确按 1024 → 4096 → 16384 → 65536 呈严格 [4.0, 4.0, 4.0] 倍率扩张。掌握并行计算、全局依赖建模、可扩展性与内存权衡,正是深入 BERT 与 GPT 等现代模型的关键起点。
Transformer 编码器核心组件功能与重要性
| 组件 | 功能描述 | 重要性 |
| 多头注意力 | 在多个投影子空间并行计算自注意力,捕捉语法与语义全局依赖。 | ★★★★★ |
| 前馈网络 | 逐位置执行两层线性变换与非线性激活(如 ReLU/GELU),深化特征表达。 | ★★★★ |
| 残差连接 | 将子层输入直接跳过并与输出相加(x + Sublayer(x)),缓解深层梯度消失。 | ★★★★ |
| 层归一化 | 沿单样本特征维归一化至零均值与单位方差(实测均值误差 2.08e-17),稳定训练。 | ★★★★ |
Transformer 与 RNN/LSTM、CNN 架构特性对比
| 特性 | Transformer | RNN/LSTM | CNN |
| 并行性 | 完全并行处理整段序列 | 须按时间步顺序串行处理 | 卷积核窗口内局部并行 |
| 长距离依赖 | 任意两词 O(1) 路径直接建模 | 依赖隐状态逐步传递易衰减 | 受卷积核大小与层数感受野限制 |
| 训练速度 | 高并行度带来更快硬件吞吐 | 串行依赖导致长序列训练较慢 | 中等(依赖深层堆叠扩感受野) |
| 内存消耗 | 较高,自注意力矩阵呈 O(n²) 增长(实测倍增比 4.0) | 中等,随序列步数线性增长 | 较低,局部参数共享节省显存 |
运行 Transformer 掩码注意力、正弦位置编码旋转恒等式、编解码块与 O(n²) 显存实测
展开查看收起
"""Independent pure-NumPy & Matplotlib lab for Transformer Architecture (Ch 13)."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
shifted = x - np.max(x, axis=axis, keepdims=True)
ex = np.exp(shifted)
return ex / np.sum(ex, axis=axis, keepdims=True)
def layer_norm(x: np.ndarray, eps: float = 1e-5) -> np.ndarray:
mean = np.mean(x, axis=-1, keepdims=True)
var = np.var(x, axis=-1, keepdims=True)
return (x - mean) / np.sqrt(var + eps)
def scaled_dot_product_attention(q: np.ndarray, k: np.ndarray, v: np.ndarray, mask: np.ndarray | None = None):
d_k = q.shape[-1]
scores = np.matmul(q, np.swapaxes(k, -2, -1)) / np.sqrt(float(d_k))
if mask is not None:
scores = np.where(mask == 0, -1e9, scores)
weights = softmax(scores, axis=-1)
return np.matmul(weights, v), weights
def sinusoidal_positional_encoding(max_len: int, d_model: int) -> np.ndarray:
pos = np.arange(max_len, dtype=float)[:, None]
div_term = np.exp(np.arange(0, d_model, 2, dtype=float) * (-np.log(10000.0) / d_model))
pe = np.zeros((max_len, d_model), dtype=float)
pe[:, 0::2] = np.sin(pos * div_term)
pe[:, 1::2] = np.cos(pos * div_term)
return pe
def multi_head_attention(q_in, k_in, v_in, wq, wk, wv, wo, num_heads, mask=None):
b, lq, d_model = q_in.shape
lk = k_in.shape[1]
d_k = d_model // num_heads
q = (q_in @ wq).reshape(b, lq, num_heads, d_k).transpose(0, 2, 1, 3)
k = (k_in @ wk).reshape(b, lk, num_heads, d_k).transpose(0, 2, 1, 3)
v = (v_in @ wv).reshape(b, lk, num_heads, d_k).transpose(0, 2, 1, 3)
out, weights = scaled_dot_product_attention(q, k, v, mask=mask)
concat = out.transpose(0, 2, 1, 3).reshape(b, lq, d_model)
return concat @ wo, weights
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
rng = np.random.default_rng(2017)
# 1. Scaled Dot-Product Attention & Causal Mask Anti-Cheat Verification
l_seq, d_k = 5, 16
q = rng.normal(0.0, 1.0, size=(1, l_seq, d_k))
k = rng.normal(0.0, 1.0, size=(1, l_seq, d_k))
v = rng.normal(0.0, 1.0, size=(1, l_seq, d_k))
causal_mask = np.tril(np.ones((l_seq, l_seq), dtype=int))
out_orig, w_causal = scaled_dot_product_attention(q, k, v, mask=causal_mask)
# Perturb future positions (t=3, 4) drastically and check positions 0..2 stay bit-identical
q_pert, k_pert, v_pert = q.copy(), k.copy(), v.copy()
q_pert[:, 3:, :] += 50.0
k_pert[:, 3:, :] -= 40.0
v_pert[:, 3:, :] += 100.0
out_pert, _ = scaled_dot_product_attention(q_pert, k_pert, v_pert, mask=causal_mask)
prefix_diff = float(np.max(np.abs(out_orig[:, :3, :] - out_pert[:, :3, :])))
future_weight_max = float(np.max(w_causal[0][causal_mask == 0]))
c1_ok = prefix_diff < 1e-12 and future_weight_max < 1e-9
cases.append(dict(
name="scaled_attention_and_causal_mask",
inputs=dict(seq_len=l_seq, d_k=d_k, perturbed_future_start=3),
prerequisites="按练习 1 公式实现带下三角掩码(mask==0 置 -1e9)的缩放点积注意力。",
action="大幅扰动未来位置 t>=3 的输入张量,核对前序位置 0..2 输出变化与上三角权重。",
expected=dict(future_weights_zero=True, zero_future_information_leakage=True),
actual=dict(future_weights_zero=future_weight_max < 1e-9, zero_future_information_leakage=prefix_diff < 1e-12),
measurements=dict(
max_future_weight=float(f"{future_weight_max:.2e}"),
prefix_max_abs_diff=float(f"{prefix_diff:.2e}"),
),
passed=c1_ok,
))
# 2. Sinusoidal Positional Encoding: exact bounds, relative-offset rotation, extrapolation
d_model = 64
pe_256 = sinusoidal_positional_encoding(256, d_model)
pos0_even_err = float(np.max(np.abs(pe_256[0, 0::2] - 0.0)))
pos0_odd_err = float(np.max(np.abs(pe_256[0, 1::2] - 1.0)))
# Verify exact relative-position linear rotation PE(pos + k) = R(k) * PE(pos) for offset k=7
offset_k = 7
div_term = np.exp(np.arange(0, d_model, 2, dtype=float) * (-np.log(10000.0) / d_model))
max_rot_err = 0.0
for pos in (0, 5, 19, 120, 200):
pred = np.zeros(d_model, dtype=float)
c_k = np.cos(offset_k * div_term)
s_k = np.sin(offset_k * div_term)
pred[0::2] = c_k * pe_256[pos, 0::2] + s_k * pe_256[pos, 1::2]
pred[1::2] = -s_k * pe_256[pos, 0::2] + c_k * pe_256[pos, 1::2]
max_rot_err = max(max_rot_err, float(np.max(np.abs(pred - pe_256[pos + offset_k]))))
# Cosine similarity decays smoothly with local distance (pos=10 vs pos=11 > pos=15 > pos=25)
pe_norm = pe_256[:50] / np.linalg.norm(pe_256[:50], axis=-1, keepdims=True)
sim_mat = pe_norm @ pe_norm.T
sim_d1 = float(sim_mat[10, 11])
sim_d5 = float(sim_mat[10, 15])
sim_d15 = float(sim_mat[10, 25])
c2_ok = (
pos0_even_err < 1e-12
and pos0_odd_err < 1e-12
and max_rot_err < 1e-11
and sim_d1 > sim_d5 > sim_d15
)
cases.append(dict(
name="sinusoidal_positional_encoding_properties",
inputs=dict(d_model=d_model, max_len=256, relative_offset_k=offset_k),
prerequisites="依据正弦/余弦偶奇维公式生成长度 256、维度 64 的位置编码矩阵。",
action="验证 pos=0 初值、任意绝对位置按固定偏移 k=7 的线性旋转恒等式,以及近邻余弦相似度单调衰减。",
expected=dict(pos0_exact=True, relative_linear_transform_exact=True, local_similarity_decays=True),
actual=dict(
pos0_exact=(pos0_even_err < 1e-12 and pos0_odd_err < 1e-12),
relative_linear_transform_exact=max_rot_err < 1e-11,
local_similarity_decays=(sim_d1 > sim_d5 > sim_d15),
),
measurements=dict(
pe_min=round(float(np.min(pe_256)), 4),
pe_max=round(float(np.max(pe_256)), 4),
relative_rotation_max_err=float(f"{max_rot_err:.2e}"),
cos_sim_dist1=round(sim_d1, 4),
cos_sim_dist5=round(sim_d5, 4),
cos_sim_dist15=round(sim_d15, 4),
),
passed=c2_ok,
))
# 3. Full Encoder-Decoder Block Forward: MHA + Cross-Attention + ReLU FFN + Residual + LayerNorm + Vocab Linear
b, src_len, tgt_len, dm, nh, d_ff, vocab = 1, 6, 4, 32, 4, 64, 20
src_x = rng.normal(0.0, 1.0, size=(b, src_len, dm)) + sinusoidal_positional_encoding(src_len, dm)[None, :, :]
tgt_x = rng.normal(0.0, 1.0, size=(b, tgt_len, dm)) + sinusoidal_positional_encoding(tgt_len, dm)[None, :, :]
def rand_w(r, c):
return rng.normal(0.0, np.sqrt(2.0 / (r + c)), size=(r, c))
# Encoder block
e_wq, e_wk, e_wv, e_wo = [rand_w(dm, dm) for _ in range(4)]
e_w1, e_b1, e_w2, e_b2 = rand_w(dm, d_ff), np.zeros(d_ff), rand_w(d_ff, dm), np.zeros(dm)
enc_attn, _ = multi_head_attention(src_x, src_x, src_x, e_wq, e_wk, e_wv, e_wo, nh)
enc_h1 = layer_norm(src_x + enc_attn)
enc_ffn = np.maximum(0.0, enc_h1 @ e_w1 + e_b1) @ e_w2 + e_b2
enc_out = layer_norm(enc_h1 + enc_ffn)
# Decoder block (Masked Self-Attn -> Cross-Attn -> FFN -> Vocab Linear + Softmax)
d_sq, d_sk, d_sv, d_so = [rand_w(dm, dm) for _ in range(4)]
d_cq, d_ck, d_cv, d_co = [rand_w(dm, dm) for _ in range(4)]
d_w1, d_b1, d_w2, d_b2 = rand_w(dm, d_ff), np.zeros(d_ff), rand_w(d_ff, dm), np.zeros(dm)
w_vocab = rand_w(dm, vocab)
dec_mask = np.tril(np.ones((tgt_len, tgt_len), dtype=int))
def run_decoder(t_in, memory):
self_a, _ = multi_head_attention(t_in, t_in, t_in, d_sq, d_sk, d_sv, d_so, nh, mask=dec_mask)
h1 = layer_norm(t_in + self_a)
cross_a, cw = multi_head_attention(h1, memory, memory, d_cq, d_ck, d_cv, d_co, nh)
h2 = layer_norm(h1 + cross_a)
ffn = np.maximum(0.0, h2 @ d_w1 + d_b1) @ d_w2 + d_b2
h3 = layer_norm(h2 + ffn)
probs = softmax(h3 @ w_vocab, axis=-1)
return h3, probs, cw
dec_out, vocab_probs, cross_w = run_decoder(tgt_x, enc_out)
# Check LayerNorm zero-mean / unit-std
ln_mean_err = float(np.max(np.abs(np.mean(dec_out, axis=-1))))
ln_std_err = float(np.max(np.abs(np.std(dec_out, axis=-1) - 1.0)))
# Check Cross-Attention sensitivity to encoder memory
dec_out_mem2, _, _ = run_decoder(tgt_x, enc_out + 1.5)
mem_effect = float(np.mean(np.abs(dec_out - dec_out_mem2)))
prob_sum_err = float(np.max(np.abs(np.sum(vocab_probs, axis=-1) - 1.0)))
c3_ok = (
enc_out.shape == (b, src_len, dm)
and dec_out.shape == (b, tgt_len, dm)
and vocab_probs.shape == (b, tgt_len, vocab)
and cross_w.shape == (b, nh, tgt_len, src_len)
and ln_mean_err < 1e-6
and ln_std_err < 1e-3
and mem_effect > 0.05
and prob_sum_err < 1e-12
)
cases.append(dict(
name="encoder_decoder_block_forward_and_layernorm",
inputs=dict(src_len=src_len, tgt_len=tgt_len, d_model=dm, num_heads=nh, d_ff=d_ff, vocab_size=vocab),
prerequisites="纯 NumPy 搭建完整 Transformer 编码器块、解码器块(含掩码自注意力与交叉注意力)及词表线性投影层。",
action="验证编码/解码输出形状、LayerNorm 均值归零与标准差近 1、交叉注意力响应编码器记忆变化以及词表概率归一。",
expected=dict(shapes_valid=True, layernorm_normalized=True, cross_attn_responds_to_encoder=True, vocab_probs_sum_one=True),
actual=dict(
shapes_valid=(enc_out.shape == (b, src_len, dm) and vocab_probs.shape == (b, tgt_len, vocab)),
layernorm_normalized=(ln_mean_err < 1e-6 and ln_std_err < 1e-3),
cross_attn_responds_to_encoder=mem_effect > 0.05,
vocab_probs_sum_one=prob_sum_err < 1e-12,
),
measurements=dict(
encoder_shape=list(enc_out.shape),
cross_attn_shape=list(cross_w.shape),
vocab_probs_shape=list(vocab_probs.shape),
layernorm_max_mean_abs=float(f"{ln_mean_err:.2e}"),
layernorm_max_std_err=float(f"{ln_std_err:.2e}"),
encoder_memory_perturbation_delta=round(mem_effect, 4),
),
passed=c3_ok,
))
# 4. O(n^2) Attention Memory Scaling vs O(n) Sequential Steps
lengths = [32, 64, 128, 256]
attn_elements = []
for n in lengths:
qn = rng.normal(0.0, 1.0, size=(n, 16))
kn = rng.normal(0.0, 1.0, size=(n, 16))
mat = qn @ kn.T
attn_elements.append(int(mat.size))
ratios = [round(attn_elements[i + 1] / attn_elements[i], 4) for i in range(len(lengths) - 1)]
c4_ok = ratios == [4.0, 4.0, 4.0] and attn_elements[-1] == 65536
cases.append(dict(
name="quadratic_memory_scaling_check",
inputs=dict(sequence_lengths=lengths),
prerequisites="在序列长度翻倍序列 32/64/128/256 上实际构造单头自注意力得分矩阵。",
action="验证序列长度每次翻倍时注意力矩阵元素数精确扩大为 4 倍,量化 O(n^2) 显存瓶颈。",
expected=dict(exact_quadratic_ratios=True, len256_elements=65536),
actual=dict(exact_quadratic_ratios=(ratios == [4.0, 4.0, 4.0]), len256_elements=attn_elements[-1]),
measurements=dict(matrix_elements_by_len=dict(zip([str(n) for n in lengths], attn_elements)), doubling_ratios=ratios),
passed=c4_ok,
))
# 5. Matplotlib PNG: Sinusoidal Positional Encoding & Position Cosine Similarity Matrix
mpl_ver = None
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.0), dpi=140)
im0 = axes[0].imshow(pe_256[:50, :], cmap="RdBu", vmin=-1.0, vmax=1.0, aspect="auto")
axes[0].set_title("Sinusoidal Positional Encoding (pos=0..49, d=64)", fontsize=10)
axes[0].set_xlabel("Embedding Dimension")
axes[0].set_ylabel("Sequence Position")
fig.colorbar(im0, ax=axes[0], fraction=0.046, pad=0.04)
im1 = axes[1].imshow(sim_mat, cmap="viridis", vmin=-0.5, vmax=1.0, aspect="auto")
axes[1].set_title("Pairwise Cosine Similarity (Relative-Distance Bands)", fontsize=10)
axes[1].set_xlabel("Position j")
axes[1].set_ylabel("Position i")
fig.colorbar(im1, ax=axes[1], fraction=0.046, pad=0.04)
fig.tight_layout()
out_png = fig_dir / "transformer-positional-encoding.png"
fig.savefig(out_png)
plt.close(fig)
figures["transformer-positional-encoding.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
c5_ok = sim_mat.shape == (50, 50) and float(np.max(np.abs(np.diag(sim_mat) - 1.0))) < 1e-12
cases.append(dict(
name="observed_positional_encoding_plot",
inputs=dict(plotted_positions=50, d_model=d_model),
prerequisites="使用实测位置编码矩阵与 50x50 位置余弦相似度矩阵绘制双联图(覆盖练习 2)。",
action="验证对角线自相似度精确为 1.0 并产出位置编码热力图与相对距离带状相似度图。",
expected=dict(diag_sim_one=True, matrix_shape_50x50=True),
actual=dict(
diag_sim_one=float(np.max(np.abs(np.diag(sim_mat) - 1.0))) < 1e-12,
matrix_shape_50x50=(sim_mat.shape == (50, 50)),
),
measurements=dict(figure_generated="transformer-positional-encoding.png" in figures),
passed=c5_ok,
))
payload = dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
依据三角和差公式,sin(ω(pos+k)) 与 cos(ω(pos+k)) 均可写作 sin(ω·pos) 与 cos(ω·pos) 乘以仅取决于偏移量 k 的固定 2×2 旋转矩阵的线性组合(本站实测最大误差仅 8.99e-15)。