7Multi-Head: Concat + Project
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.proj(out) # Linear(num_heads*head_size, n_embd)
n_embd=64 splits into 4 independent 16-dim subspaces, each learning a different relational pattern, then remixed by proj. Your Head/MultiHeadAttention code loops over heads in Python and concatenates — mathematically equivalent to (but not literally) a batched 4D (B,n_head,T,head_size) tensor.
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(num_heads * head_size, n_embd)
self.dropout = nn.Dropout(0.1)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1) # (B,T,n_head*head_size)
out = self.dropout(self.proj(out)) # back to (B,T,n_embd)
return out
nn.ModuleList is a plain Python list that PyTorch also knows how to walk — each Head inside it gets correctly registered so its parameters show up in .parameters() and it moves with .to(device); a raw Python list of modules would silently hide them from the optimizer. torch.cat(..., dim=-1) concatenates along the last axis — 4 tensors of (B,T,16) become one (B,T,64), a pure memory-layout operation, no computation.📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell 1177f3ef
# 继承上面的单头自注意力,构建多头自注意力 class MultiHeadAttention(nn.Module): def __init__(self, num_heads, head_size): super().__init__() # 这里将多个heads重新组合成一个多头自注意力层,每个head都会独立地计算自己的query、key、value向量,并且在最后将它们的输出拼接起来,得到一个新的表示,这个表示包含了输入数据中捕捉到的多个特定模式或关系的信息 # 现在的形状是num_heads个head_size维的表示,最后我们会将它们拼接起来,得到一个新的n_embd维的表示,这个表示包含了输入数据中捕捉到的多个特定模式或关系的信息 self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)]) # 为什么命名是proj,它是projection(投影的意思)的简写,表示映射回n_embd维的空间中,得到一个新的表示 self.proj = nn.Linear(num_heads * head_size, n_embd) self.dropout = nn.Dropout(0.1) def forward(self, x): out = torch.cat([h(x) for h in self.heads], dim=-1) # 将多个head的输出拼接起来,得到一个新的表示,这个表示包含了输入数据中捕捉到的多个特定模式或关系的信息 out = self.dropout(self.proj(out)) # 将拼接后的表示映射回n_embd维的空间中,得到一个新的表示,这个表示包含了输入数据中捕捉到的多个特定模式或关系的信息 # 现在形状是B,T,n_embd return out
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note bbdcc75b
import torch import torch.nn as nn import torch.nn.functional as F
Multi-head 切分 n_embd 为独立子空间 + 正确 attention 公式 + KV Cache 原理
torch.manual_seed(0) n_embd_demo = 8 n_head_demo = 4 head_size = n_embd_demo // n_head_demo # = 2
print(f"n_embd={n_embd_demo} n_head={n_head_demo} head_size={head_size}")
B, T = 1, 5 x = torch.randn(B, T, n_embd_demo) print(f"输入 x: {x.shape} (B={B}, T={T} 个 token)\n")
权重矩阵:推理时固定,等价于 nn.Linear(n_embd, head_size, bias=False).weight.T
W_q = torch.randn(n_embd_demo, head_size) W_k = torch.randn(n_embd_demo, head_size) W_v = torch.randn(n_embd_demo, head_size)
── 方式1:无 KV Cache,一次并行处理全部 T 个 token ─────────────────
注:这只是"计算形状"和训练一次前向传播相同(多位置并行),实际没有 backward/optimizer,仍然是推理
print("=== 推理(无 KV Cache,朴素重算):全部 T 个 token 一次并行 ===") q = x @ W_q # (B, T, head_size) k = x @ W_k v = x @ W_v
正确公式:先缩放再 softmax,最后聚合 value(不能省略 softmax 直接乘 v)
wei = q @ k.transpose(-2, -1) * head_size**-0.5 # (B, T, T) 相似度分数 wei = F.softmax(wei, dim=-1) # (B, T, T) 归一化为概率 out_full = wei @ v # (B, T, head_size) 加权聚合 print(f" q/k/v: {q.shape} → out: {out_full.shape}\n")
── 方式2:推理时逐 token,KV Cache 追加,Q 当步用完即丢 ─────────────
print("=== 推理 + KV Cache:Q 不缓存,K/V 逐步追加历史 ===") k_cache = torch.zeros(B, 0, head_size) v_cache = torch.zeros(B, 0, head_size)
for t in range(T): x_new = x[:, t:t+1, :] # (B, 1, n_embd) 当前新 token
q_new = x_new @ W_q # (B, 1, head_size) 当前 token 提问,用完即丢
k_new = x_new @ W_k # (B, 1, head_size) 追加进 cache
v_new = x_new @ W_v # (B, 1, head_size) 追加进 cache
k_cache = torch.cat([k_cache, k_new], dim=1) # cache 增长为 (B, t+1, head_size)
v_cache = torch.cat([v_cache, v_new], dim=1)
wei_new = q_new @ k_cache.transpose(-2, -1) * head_size**-0.5 # (B, 1, t+1)
wei_new = F.softmax(wei_new, dim=-1)
out_new = wei_new @ v_cache # (B, 1, head_size)
print(f" step {t}: Q {q_new.shape} 用完丢弃 | K/V cache {k_cache.shape} | out {out_new.shape}")
print(f"\n为什么只缓存 K/V,不缓存 Q:") print(f" K/V = '历史 token 提供的答案',每步追加 1 条,对未来所有 step 仍然有效") print(f" Q = '当前 token 的提问', 每步只有 1 个问题,用完对下一步毫无用处")