Transformer 深度解析,从注意力到 KV 缓存
用可逐行核对的数值和一层 CPU 解码器理解注意力、位置、归一化与训练。
学完这一章,你能够
- 用可逐行核对的数值和一层 CPU 解码器理解注意力、位置、归一化与训练。
递归如何传递顺序
2017 年的 Transformer 用注意力连接序列中的位置。循环网络则把当前位置输入和上一位置的状态一起变换。本站用三个标量实测 hₜ = tanh(2xₜ + 0.5hₜ₋₁),逆转输入会改变结果。沿时间步反传时,梯度经过一串雅可比矩阵,可能衰减或放大。LSTM 与 GRU 的门控能改善信息保留,效果仍取决于任务与训练。
同层的密集自注意力能批量计算训练序列,未屏蔽的位置可以直接建立联系。自回归生成仍要等待上一个词元。无位置机制、无掩码的自注意力对输入置换等变,交换输入行会相应交换输出行。训练速度还取决于序列长度、张量维度、硬件和实现。
从 Q、K、V 到权重和输出
Q、K、V 是输入的线性投影。自注意力的三组投影来自同一序列,交叉注意力可从另一序列取得 K 和 V。查询与键的最后一维同为 dₖ,值向量可以有不同宽度 dᵥ。令查询数为 m、键值对数为 n,QKᵀ 的形状为 m×n,输出形状为 m×dᵥ。
先按键维度的平方根缩放分数,再对每个查询的可见键做 softmax,最后以权重对 V 求和。若查询与键的分量彼此独立且均值为零、方差为一,点积方差为 dₖ。缩放控制的是这一假设下的分数尺度。softmax 减去该行最大值可避免正指数溢出。
本站以两个查询、两个键和三维值向量计算完整权重。因果掩码把第一个查询的未来键权重置零,第一行因此直接等于第一个值向量。全部键不可见时,本练习明确报错。观察页可对照带掩码和完整权重。

多头注意力为不同头学习不同投影。每个头独立计算分数和输出,拼接后再乘输出投影矩阵。实验比较两头逐项计算与 PyTorch 的结果。常见均匀分头要求模型宽度可整除头数。训练后可分析头的模式,不能预先假定某个头一定代表语法或指代。
位置如何影响注意力
原始 Transformer 把固定正弦和余弦位置向量加到词嵌入。成对列 2i 与 2i+1 共用频率 10000^(−2i/d_model)。若循环变量已经是偶数列号 j,指数写成 −j/d_model。本站检查五维编码的三组频率,最后一列只有正弦。
正余弦加法关系让固定偏移可表示为每对分量上的线性旋转。RoPE 把旋转施加在 Q、K 的成对分量上,同一频率下的点积随键与查询的位置差变化。ALiBi 在 softmax 前给较远的可见键加入更负的分数偏置,并可给每头不同斜率。本站分别平移两端位置和计算距离偏置。可计算更长的位置,实际有效上下文仍由模型训练与评测决定。
前馈网络、残差与归一化
逐位置前馈层对每个词元独立应用同一组参数。原始结构先用线性层扩宽,再经 ReLU 和输出投影恢复模型宽度。SwiGLU 用两条中间投影,将其中一条经 Swish,也就是 x·sigmoid(x),与另一条逐元素相乘,再映射回模型宽度。只使用 sigmoid 的门对应 GLU。本站以固定投影结果区分三种门控路径。
LayerNorm 在选定的特征轴上减均值,以 sqrt(方差 + epsilon) 缩放,再应用可学习的增益与偏移。常量向量有 epsilon 保护,归一化后只剩偏移。RMSNorm 用 sqrt(均方 + epsilon),不减均值。前置归一化计算 x + F(Norm(x)),后置计算 Norm(x + F(x))。原始 Transformer 使用后置方案,许多后来的解码器采用前置方案,训练稳定性仍与配置相关。
编码器、解码器与下一个词元
原始编码器-解码器的编码器产生输入表示,解码器含有带因果掩码的自注意力和读取编码表示的交叉注意力。编码器型模型常用双向自注意力,适用于分类、实体识别和抽取问答。BERT 的掩码语言模型从双侧上下文预测被遮盖的训练词元。解码器型模型常以因果掩码做逐词生成。选择架构时先看输入和输出任务。
本站的解码器用词元和位置嵌入开始,依次经过前置归一化、因果注意力和残差,再经前置归一化、前馈层和残差,最后将状态映射成词表大小的 logits。推理时可把最后一行转成下一词元的概率。训练直接把 logits 与后移一位的标签交给交叉熵。固定合成词表训练 40 步后,用同一训练样本核对损失与预测,这项结果只衡量样本拟合。
分块注意力与解码缓存解决不同成本
对长度 N 的密集注意力,分数共有 N² 个。N=8192 时,单个头的一份 FP16 分数矩阵是 128 MiB。实际总量还取决于批次、头数、层数、梯度和保留的中间量。FlashAttention 把 Q、K、V 分块并维护在线归一化状态,减少完整分数矩阵在显存中的物化与慢速内存访问。密集点积的总算术仍随 N² 增长,浮点加法次序也可能影响舍入结果。本站在 CPU 上验证分块加权的数值等价,GPU 内核和速度另验。
KV 缓存保存过去词元在各层的键和值。已有 n 个词元时,一个新查询仍需访问历史 K/V。固定头维和层数,单步注意力的历史扫描随 n 线性增长。实验用同一权重比较全前缀计算与缓存解码,检查长度增长和 logits 一致。MHA 给每个查询头独立的 K/V,GQA 让一组查询头共享,MQA 让所有查询头共享。按 batch × 层数 × 词元数 × KV 头数 × 头维 × 2 × 每元素字节估算缓存的张量数据量。
训练与生成的计算条件
| 特性 | 循环网络 | Transformer |
|---|---|---|
| 计算方式 | 同一序列的递归状态有时间依赖,批次和部分矩阵操作可并行。 | 可批量计算训练位置,自回归生成逐步推进。 |
| 长距离依赖 | 梯度经过多次状态变换,门控能改善保留。 | 未屏蔽位置可直接相连,学到有效关系仍取决于训练。 |
| 位置信息 | 递归更新顺序参与计算。 | 按架构采用位置嵌入、旋转、相对偏置或掩码等。 |
| 训练速度 | 跨时间的串行路径可能限制吞吐。 | 并行有利于吞吐,密集注意力的计算开销随长度平方增长。 |
位置机制比较
| 方式 | 计算规则 | 适用范围与例子 |
|---|---|---|
| 正弦位置编码 | 把频率不同的固定正弦余弦向量加到输入。 | 原始 Transformer。可计算任意位置,模型效果另评。 |
| 可学习位置编码 | 将绝对位置作为索引,查询随训练更新的嵌入。 | GPT‑2 与 BERT 的常见实现。超出表长须专门处理。 |
| RoPE | 旋转查询与键的成对维度。 | 用于 LLaMA、PaLM 等,旋转后的点积体现相对位移。 |
| ALiBi | 在归一化前按距离给注意力分数加偏置。 | 用于 BLOOM 等。斜率和长度外推效果须在模型条件下验证。 |
三种架构的连接方式
| 架构 | 可见性 | 代表模型与任务 |
|---|---|---|
| Encoder-Decoder | 编码自注意力、因果解码自注意力及交叉注意力。 | T5、BART,用于翻译或摘要等序列到序列任务。 |
| Decoder-Only | 在因果掩码下读取当前与过去位置。 | GPT、LLaMA 等,用于自回归生成。 |
| Encoder-Only | 可同时使用左侧和右侧有效词元。 | BERT、RoBERTa,用于分类、实体识别或抽取式问答。 |
历史配置与参数定义
| 参数 | 含义 | GPT‑2 小型 | LLaMA 7B 初版 | GPT‑3 175B |
|---|---|---|---|---|
| d_model | 每个词元的隐藏特征宽度。 | 768 | 4096 | 12288 |
| num_heads | 注意力查询头数量。 | 12 | 32 | 96 |
| num_layers | 重复堆叠的 Transformer 层数。 | 12 | 32 | 96 |
| d_ff | 前馈子层的中间宽度。 | 3072 | 11008 | 49152,按论文给出的 4×d_model |
| context_len | 单序列的位置预算,版本与实现须匹配。 | 1024 | 2048。Llama 2 的 4096 属于后续版本。 | 2048 |
实算注意力、缓存和一层解码器
"""Inspect Transformer components and train a small CPU decoder on synthetic tokens."""
import math
import sys
import torch
from torch import nn
from torch.nn import functional as F
from attention_lab import exercise as basic_attention
from lab_tools import run_exercise
def close(left, right):
return torch.allclose(left, right, atol=1e-6, rtol=1e-6)
def number_row(row):
return [round(float(value), 6) for value in row]
def position_encoding(length, width):
even_columns = torch.arange(0, width, 2, dtype=torch.float64)
angle = torch.arange(length, dtype=torch.float64)[:, None] / (10_000 ** (even_columns / width))
encoding = torch.empty((length, width), dtype=torch.float64)
encoding[:, ::2] = angle.sin()
encoding[:, 1::2] = angle[:, :width // 2].cos()
return encoding
def rotate_pairs(vector, angle):
paired = vector.reshape(-1, 2)
x, y = paired.unbind(-1)
return torch.stack((x * angle.cos() - y * angle.sin(),
x * angle.sin() + y * angle.cos()), dim=-1).flatten()
def online_attention(scores, values, tile_size):
"""Evaluate one attention row with online max, denominator and weighted sum."""
largest = -math.inf
total = 0.0
weighted = torch.zeros_like(values[0])
for offset in range(0, len(scores), tile_size):
score_tile = scores[offset:offset + tile_size]
value_tile = values[offset:offset + tile_size]
next_largest = max(largest, float(score_tile.max()))
old_scale = math.exp(largest - next_largest)
weights = (score_tile - next_largest).exp()
total = total * old_scale + float(weights.sum())
weighted = weighted * old_scale + weights @ value_tile
largest = next_largest
return weighted / total
def recurrence_and_heads(checks):
sequence = torch.tensor([[0.25], [0.75], [-0.5]], dtype=torch.float64)
rnn = nn.RNN(1, 1, bias=False, batch_first=True, dtype=torch.float64)
with torch.no_grad():
rnn.weight_ih_l0.fill_(2)
rnn.weight_hh_l0.fill_(0.5)
expected, hidden = [], 0.0
for row in sequence:
hidden = math.tanh(2 * float(row[0]) + 0.5 * hidden)
expected.append(round(hidden, 6))
output, _ = rnn(sequence.unsqueeze(0))
reverse, _ = rnn(sequence.flip(0).unsqueeze(0))
checks.expect("transformer_rnn", sequence.flatten().tolist(),
"Compare a real recurrent layer with scalar recurrence and then reverse token order",
[expected, True], [number_row(output.flatten().detach()), not close(output, reverse.flip(1))])
x = torch.tensor([[1.0, 0.0, 2.0, -1.0], [0.0, 1.0, -1.0, 2.0]])
identity = torch.eye(4)
mha = nn.MultiheadAttention(4, 2, batch_first=True, bias=False)
with torch.no_grad():
mha.in_proj_weight.copy_(torch.cat((identity * 2, identity, identity * 3)))
mha.out_proj.weight.copy_(torch.diag(torch.tensor([1., 2., 3., 4.])))
actual, observed_weights = mha(x[None], x[None], x[None], average_attn_weights=False)
q, k, v = [data.reshape(2, 2, 2).transpose(0, 1) for data in (2*x, x, 3*x)]
weights = (q @ k.transpose(-2, -1) / math.sqrt(2)).softmax(dim=-1)
joined = (weights @ v).transpose(0, 1).reshape(2, 4)
expected = joined @ mha.out_proj.weight.T
checks.expect("transformer_projected_heads", x.tolist(),
"Compare two projected heads, concatenation and a distinct output projection",
[[1, 2, 4], [1, 2, 2, 2], True, True, True],
[list(actual.shape), list(observed_weights.shape), close(actual[0], expected),
close(observed_weights[0], weights), not close(weights[0], weights[1])])
try:
nn.MultiheadAttention(5, 2)
except (AssertionError, ValueError):
invalid_width = True
else:
invalid_width = False
checks.expect("transformer_head_divisibility", [5, 2], "Create a standard multihead layer with indivisible width",
True, invalid_width)
tokens = torch.tensor([[[[1.0,0.0],[0.0,1.0]]]])
alternate = tokens.clone()
alternate[0,0,1] = torch.tensor([3.0,2.0])
original_bi = F.scaled_dot_product_attention(tokens, tokens, tokens)
changed_bi = F.scaled_dot_product_attention(alternate, alternate, alternate)
original_causal = F.scaled_dot_product_attention(tokens, tokens, tokens, is_causal=True)
changed_causal = F.scaled_dot_product_attention(alternate, alternate, alternate, is_causal=True)
cross = F.scaled_dot_product_attention(tokens[:,:,:1], alternate, alternate)
checks.expect("transformer_architecture_masks", [tokens.flatten().tolist(), alternate.flatten().tolist()],
"Change only the future token and compare bidirectional, causal and source-attending queries",
[True, True, [1,1,1,2], True],
[not close(original_bi[:,:,:1], changed_bi[:,:,:1]), close(original_causal[:,:,:1], changed_causal[:,:,:1]),
list(cross.shape), close(cross, changed_bi[:,:,:1])])
def positions_and_layers(checks):
encoding = position_encoding(3, 5)
angles = torch.tensor([1., 10_000 ** (-2/5), 10_000 ** (-4/5)], dtype=torch.float64)
expected = [math.sin(1), math.cos(1), math.sin(float(angles[1])),
math.cos(float(angles[1])), math.sin(float(angles[2]))]
checks.expect("transformer_sinusoidal", [3, 5], "Check the first two rows and the unpaired fifth sine column",
[[0., 1., 0., 1., 0.], [round(value, 6) for value in expected]],
[number_row(encoding[0]), number_row(encoding[1])])
q = torch.tensor([1., 2., 3., -1.], dtype=torch.float64)
k = torch.tensor([3., 0., 1., 2.], dtype=torch.float64)
frequencies = torch.tensor([0.3, 0.07], dtype=torch.float64)
baseline = rotate_pairs(q, 2 * frequencies) @ rotate_pairs(k, 5 * frequencies)
shifted = rotate_pairs(q, 8 * frequencies) @ rotate_pairs(k, 11 * frequencies)
reference = q @ rotate_pairs(k, 3 * frequencies)
checks.expect("transformer_rope", [[2,5],[8,11]], "Shift both positions by six and compare relative dot products",
[True, True, True], [close(baseline, shifted), close(baseline, reference),
close(rotate_pairs(q, 2 * frequencies).norm(), q.norm())])
score = torch.zeros(3, dtype=torch.float64)
biased = score - 0.5 * torch.arange(2, -1, -1, dtype=torch.float64)
checks.expect("transformer_alibi", [0,0,0], "Apply distance bias before softmax at the third position",
[[-1., -0.5, 0.], [0.186324, 0.307196, 0.50648]],
[number_row(biased), number_row(biased.softmax(dim=0))])
gate = torch.tensor([2., -1.], dtype=torch.float64)
up = torch.tensor([3., 4.], dtype=torch.float64)
out = torch.tensor([2., -1.], dtype=torch.float64)
relu_output = F.relu(gate) @ out
swiglu_output = (F.silu(gate) * up) @ out
glu_output = (gate.sigmoid() * up) @ out
expected_swi = 12/(1+math.exp(-2)) + 4/(1+math.exp(1))
checks.expect("transformer_ffn_gates", [gate.tolist(), up.tolist(), out.tolist()],
"Compare ReLU, Swish-gated and sigmoid-gated intermediate features through the output projection",
[4., round(expected_swi, 6), True],
[float(relu_output), round(float(swiglu_output), 6), not close(swiglu_output, glu_output)])
x = torch.tensor([1., 3.], dtype=torch.float64)
gamma, beta = torch.tensor([2., 3.], dtype=x.dtype), torch.tensor([4., 5.], dtype=x.dtype)
eps = 0.25
norm = F.layer_norm(x, (2,), gamma, beta, eps)
constant = F.layer_norm(torch.ones_like(x), (2,), gamma, beta, eps)
rms = F.rms_norm(x, (2,), gamma, eps)
zero = F.rms_norm(torch.zeros_like(x), (2,), gamma, eps)
checks.expect("transformer_norms", [x.tolist(),gamma.tolist(),beta.tolist(),eps],
"Compare LayerNorm and RMSNorm with affine terms and check constant and zero rows",
[[round(4-2/math.sqrt(1.25),6), round(5+3/math.sqrt(1.25),6)], [4.,5.],
[round(2/math.sqrt(5.25),6), round(9/math.sqrt(5.25),6)], [0.,0.]],
[number_row(norm), number_row(constant), number_row(rms), number_row(zero)])
f = lambda values: values * torch.tensor([2., 4.], dtype=x.dtype)
pre = x + f(F.layer_norm(x, (2,)))
post = F.layer_norm(x + f(x), (2,))
checks.expect("transformer_norm_order", x.tolist(), "Apply residual and normalization in both orders",
[True, True], [not close(pre, post), abs(float(post.mean())) < 1e-6])
class Decoder(nn.Module):
"""One causal decoder layer with a full-prefix and cached inference path."""
def __init__(self, vocabulary=5, width=8, heads=2, max_tokens=12):
super().__init__()
self.heads = heads
self.embedding = nn.Embedding(vocabulary, width)
self.position = nn.Embedding(max_tokens, width)
self.attention_norm = nn.LayerNorm(width)
self.qkv = nn.Linear(width, 3 * width, bias=False)
self.merge = nn.Linear(width, width, bias=False)
self.ffn_norm = nn.LayerNorm(width)
self.ffn = nn.Sequential(nn.Linear(width, 16), nn.ReLU(), nn.Linear(16, width))
self.output_norm = nn.LayerNorm(width)
self.logits = nn.Linear(width, vocabulary)
def forward(self, tokens, cache=None):
batch, steps = tokens.shape
past = 0 if cache is None else cache[0].size(-2)
positions = torch.arange(past, past + steps, device=tokens.device)
x = self.embedding(tokens) + self.position(positions)
q, k, v = self.qkv(self.attention_norm(x)).chunk(3, dim=-1)
q, k, v = (data.reshape(batch, steps, self.heads, -1).transpose(1, 2) for data in (q, k, v))
if cache is not None:
k = torch.cat((cache[0], k), dim=-2)
v = torch.cat((cache[1], v), dim=-2)
mask = torch.arange(past + steps, device=tokens.device)[None, :] <= positions[:, None]
attended = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
x = x + self.merge(attended.transpose(1, 2).reshape_as(x))
x = x + self.ffn(self.ffn_norm(x))
return self.logits(self.output_norm(x)), (k, v)
def caches_and_training(checks):
scores = torch.tensor([1000., 999., 1002., 998., 1001.], dtype=torch.float64)
values = torch.tensor([[1.,2.],[3.,5.],[1.,6.],[0.,-1.],[-2.,5.]], dtype=torch.float64)
dense = scores.softmax(0) @ values
checks.expect("transformer_online_softmax", [scores.tolist(), [1,2,5]],
"Compare online block rescaling to a materialized dense row on the CPU",
[True, True, True], [close(dense, online_attention(scores, values, n)) for n in (1,2,5)])
# Per layer, each token has a K vector and a V vector per KV head.
bytes_per_token = 2 * 32 * 128 * 2
cache_sizes = [bytes_per_token * 32 * 4096 // 2**20 // reduction for reduction in (1,4,32)]
checks.expect("transformer_cache_memory", [1,32,4096,128,2,[32,8,1]],
"Count only keys and values for 32, 8 and 1 KV heads",
[2048, 512, 64], cache_sizes)
tokens = torch.tensor([[0, 1, 2, 3]])
model = Decoder().eval()
with torch.no_grad():
full, _ = model(tokens)
prefix, cache = model(tokens[:, :2])
parts = [prefix]
lengths = [cache[0].size(-2)]
for i in range(2, tokens.size(1)):
logits, cache = model(tokens[:, i:i+1], cache)
parts.append(logits)
lengths.append(cache[0].size(-2))
edited, _ = model(torch.tensor([[0, 1, 3, 4]]))
checks.expect("transformer_kv_equivalence", tokens.tolist(),
"Prefill two tokens, decode two more and compare logits to a full causal pass",
[True, [2,3,4], [1,2,4,4], True],
[close(full,torch.cat(parts,dim=1)), lengths,list(cache[0].shape),close(full[:,:2],edited[:,:2])])
model.train()
optimizer = torch.optim.Adam(model.parameters(), lr=0.04)
inputs = torch.tensor([[0,1,2,3],[1,2,3,4],[2,3,4,0],[3,4,0,1],[4,0,1,2]])
labels = (inputs + 1) % 5
def loss(logits):
return F.cross_entropy(logits.flatten(0,1), labels.flatten())
with torch.no_grad():
initial = float(loss(model(inputs)[0]))
for _ in range(40):
optimizer.zero_grad()
objective = loss(model(inputs)[0])
objective.backward()
optimizer.step()
model.eval()
with torch.no_grad():
predictions, _ = model(inputs)
final = float(loss(predictions))
next_probabilities = predictions[0, -1].softmax(dim=-1)
checks.expect("transformer_tiny_training", [40, inputs.tolist()],
"Train with shifted labels and check loss reduction, argmax, probabilities and vocabulary size",
[True, True, 5, 4, 1.0], [final < initial/4, bool(torch.equal(predictions.argmax(-1), labels)),
next_probabilities.numel(), int(next_probabilities.argmax()),
round(float(next_probabilities.sum()),6)])
def exercise(checks, workspace):
torch.set_num_threads(1)
torch.manual_seed(31)
version = [sys.version.split()[0], torch.__version__.split("+")[0]]
checks.expect("transformer_cpu_version", "CPU", "Identify the isolated runtime",
["3.12.14", "2.10.0"], version)
basic_attention(checks, workspace)
recurrence_and_heads(checks)
positions_and_layers(checks)
caches_and_training(checks)
if __name__ == "__main__":
run_exercise(exercise)
- 权重逐行归一化,掩码后的首行只读自身。两头结果与库实现一致,缓存解码与全前缀 logits 一致,合成词表训练后损失下降。
所需环境:CPython 3.12.14、PyTorch 2.10.0,CPU 单线程、自编小矩阵及五词元词表。
当前源码 SHA256:3be27abbca22ca11859ebbfabe96bbb394fba93fd9394cf3390ae620448b8f93
Transformer 练习 ZIP
含标准库注意力实现、CPU 解码器、数值检查和本站观察页。
所需环境:CPython 3.12.14、PyTorch 2.10.0,CPU 单线程、自编小矩阵及五词元词表。
ZIP SHA256:32ad2af1581db23f3c7cd3d7b7eeff4a7c080a5a211fa5265d1aa808eb366d5f
常见错误与边界
- 正弦公式里的 2i 是列号。实现按偶数列迭代时直接使用列号。
- SwiGLU 的门分支需要 Swish。缓存估算使用 KV 头数,并包含键和值两份。
练习与解答
用 ZIP 中的程序检查首个查询的掩码权重,再对照缓存长度与全前缀 logits。
展开参考解答
第一行权重为 [1, 0]。两词元预填充后逐次增长到 3 和 4,拼接的 logits 与全前缀计算一致。