Title here
Summary here
把两段文档连到同一条提示里,第二段的 token 就能看到第一段。这个依赖来自每层的因果自注意力,也是 CacheBlend 需要重新计算一部分位置的原因。
Transformer 的一层先让各位置读取可见的上下文,再对每个位置做前馈变换。对 CacheBlend 来说,两段文字能否共用旧 KV,首先取决于哪些 token 的上文发生了变化。
| 操作 | 同一层的位置依赖 |
|---|---|
| RNN 处理一条序列 | 第 步需要前一步的隐状态,时间步按顺序推进。 |
| Transformer 处理已给定的提示词 | 输入位置已经齐备,可以并行计算各行的查询。因果 mask 决定一行能读到哪些键。 |
| 自回归解码 | 下一次输入取决于这一轮采样出的 token。不同请求可以合批,同一请求仍逐轮生成。 |
graph TB
subgraph "Transformer 整体架构"
Input["输入序列"] --> Embed["Embedding Layer"]
Embed --> PE["+ Position Encoding"]
PE --> Blocks["N × Transformer Blocks"]
Blocks --> LMHead["Language Model Head"]
LMHead --> Output["输出概率分布"]
endgraph LR
subgraph "Encoder-Decoder (T5, BART)"
E1["Encoder"] --> Cross["Cross-Attention"]
Cross --> D1["Decoder"]
end
subgraph "Decoder-Only (GPT, LLaMA)"
D2["Decoder with Causal Mask"]
end| 架构 | 代表模型 | 适用场景 | 特点 |
|---|---|---|---|
| Encoder-Decoder | T5, BART, mT5 | 翻译、摘要 | 双向编码 + 自回归解码 |
| Decoder-Only | GPT, LLaMA, Mistral | 文本生成、对话 | 仅自回归解码 |
| Encoder-Only | BERT, RoBERTa | 分类、NER | 双向编码 |
现代 LLM(如 LLaMA、Mistral)通常使用 Pre-LN(Pre-Layer Normalization)结构:
graph TB
subgraph "Decoder Block (Pre-LN)"
Input["Input: x"] --> LN1["RMSNorm"]
LN1 --> Attn["Self-Attention"]
Attn --> Add1["x + Attention(LN(x))"]
Input --> Add1
Add1 --> LN2["RMSNorm"]
LN2 --> FFN["Feed-Forward Network"]
FFN --> Add2["x + FFN(LN(x))"]
Add1 --> Add2
Add2 --> Output["Output"]
endclass DecoderBlock(nn.Module):
def __init__(self, hidden_size, num_heads, intermediate_size):
super().__init__()
self.input_layernorm = RMSNorm(hidden_size)
self.self_attn = SelfAttention(hidden_size, num_heads)
self.post_attention_layernorm = RMSNorm(hidden_size)
self.mlp = MLP(hidden_size, intermediate_size)
def forward(self, hidden_states, attention_mask=None, position_ids=None):
# Self-Attention with residual
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(hidden_states, attention_mask, position_ids)
hidden_states = residual + hidden_states
# FFN with residual
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states单头注意力的计算公式:
其中:
多头注意力将输入投影到多个子空间,每个子空间独立计算注意力:
其中:
graph TB
subgraph "Multi-Head Attention"
Input["Input: X"] --> Q["Q = X @ W_Q"]
Input --> K["K = X @ W_K"]
Input --> V["V = X @ W_V"]
Q --> Split1["Split into h heads"]
K --> Split2["Split into h heads"]
V --> Split3["Split into h heads"]
Split1 --> H1["Head 1"]
Split2 --> H1
Split3 --> H1
Split1 --> H2["Head 2"]
Split2 --> H2
Split3 --> H2
Split1 --> Hn["Head h"]
Split2 --> Hn
Split3 --> Hn
H1 --> Concat["Concat"]
H2 --> Concat
Hn --> Concat
Concat --> Proj["Output Projection"]
Proj --> Output["Output"]
endclass MultiHeadAttention(nn.Module):
def __init__(self, hidden_size, num_heads):
super().__init__()
self.num_heads = num_heads
self.head_dim = hidden_size // num_heads
self.q_proj = nn.Linear(hidden_size, hidden_size)
self.k_proj = nn.Linear(hidden_size, hidden_size)
self.v_proj = nn.Linear(hidden_size, hidden_size)
self.o_proj = nn.Linear(hidden_size, hidden_size)
def forward(self, hidden_states, attention_mask=None):
batch_size, seq_len, _ = hidden_states.shape
# 投影
q = self.q_proj(hidden_states)
k = self.k_proj(hidden_states)
v = self.v_proj(hidden_states)
# 重塑为多头形式: [batch, seq, num_heads, head_dim]
q = q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
k = k.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
v = v.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
# 计算注意力分数
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
# 应用因果掩码(可选)
if attention_mask is not None:
scores = scores + attention_mask
# Softmax + 加权求和
attn_weights = F.softmax(scores, dim=-1)
output = torch.matmul(attn_weights, v)
# 重塑并投影
output = output.transpose(1, 2).contiguous().view(batch_size, seq_len, -1)
output = self.o_proj(output)
return output现代 LLM(如 LLaMA 2/3、Mistral)使用 GQA 来减少 KV Cache 的内存占用:
graph TB
subgraph "注意力变体对比"
subgraph "MHA"
MHA_Q["Q: 32 heads"]
MHA_K["K: 32 heads"]
MHA_V["V: 32 heads"]
end
subgraph "GQA"
GQA_Q["Q: 32 heads"]
GQA_K["K: 8 groups"]
GQA_V["V: 8 groups"]
end
subgraph "MQA"
MQA_Q["Q: 32 heads"]
MQA_K["K: 1 head"]
MQA_V["V: 1 head"]
end
end| 变体 | Query Heads | KV Heads | KV Cache 大小 |
|---|---|---|---|
| MHA | 32 | 32 | 100% |
| GQA | 32 | 8 | 25% |
| MQA | 32 | 1 | 3.125% |
class MLP(nn.Module):
def __init__(self, hidden_size, intermediate_size):
super().__init__()
self.gate_proj = nn.Linear(hidden_size, intermediate_size)
self.up_proj = nn.Linear(hidden_size, intermediate_size)
self.down_proj = nn.Linear(intermediate_size, hidden_size)
self.act_fn = nn.SiLU() # SwiGLU activation
def forward(self, x):
# SwiGLU: down(act(gate(x)) * up(x))
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))graph LR
subgraph "FFN 功能"
A["特征变换"] --> B["非线性映射"]
B --> C["知识存储"]
C --> D["维度转换"]
endgraph TB
subgraph "Post-LN (原始)"
P1["x"] --> P2["Attention"]
P2 --> P3["Add"]
P1 --> P3
P3 --> P4["LayerNorm"]
end
subgraph "Pre-LN (现代)"
Q1["x"] --> Q2["LayerNorm"]
Q2 --> Q3["Attention"]
Q3 --> Q4["Add"]
Q1 --> Q4
endPre-LN 的优势:
LLaMA 使用 RMSNorm(Root Mean Square Layer Normalization):
class RMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.eps = eps
def forward(self, x):
# RMSNorm: x / sqrt(mean(x^2) + eps) * weight
rms = torch.sqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + self.eps)
return x / rms * self.weightRMSNorm vs LayerNorm:
graph LR
subgraph "残差连接"
X["x"] --> F["F(x)"]
F --> Add["+"]
X --> Add
Add --> Out["x + F(x)"]
end作用:
# 注意力层的残差
hidden_states = residual + self.self_attn(self.input_layernorm(hidden_states))
# FFN 层的残差
hidden_states = residual + self.mlp(self.post_attention_layernorm(hidden_states))Transformer 的注意力机制是位置无关的(permutation invariant),需要额外注入位置信息。
graph TB
subgraph "位置编码演进"
A["绝对位置编码<br>(Sinusoidal)"] --> B["可学习位置编码<br>(Learned)"]
B --> C["相对位置编码<br>(T5 Style)"]
C --> D["RoPE<br>(Rotary)"]
D --> E["ALiBi<br>(Attention Linear Bias)"]
endRoPE 是目前最流行的位置编码方式(LLaMA、Mistral 等使用):
核心思想: 通过旋转变换将位置信息编码到 Q 和 K 中
其中 是旋转矩阵:
RoPE 的关键性质:
注意力分数只依赖于相对位置 ,这是 CacheBlend 能够复用 KV Cache 的理论基础。
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
# 获取对应位置的 cos 和 sin
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
sin = sin[position_ids].unsqueeze(1)
# 应用旋转
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def rotate_half(x):
"""将向量的前后半部分交换并取负"""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)| 方法 | 外推能力 | 计算开销 | 是否可复用 KV |
|---|---|---|---|
| Sinusoidal | 差 | 低 | 否 |
| Learned | 无 | 低 | 否 |
| RoPE | 中等 | 中等 | 是(通过旋转恢复) |
| ALiBi | 好 | 低 | 否 |
理解这些组件是深入学习 CacheBlend 的前提。