11.3  KV 缓存与缓存缩减

仔细观察 GPT.generate(11.2.4 节)在解码第 \(t\) 步所做的工作:为了采样词元 \(t+1\),它对整个长度为 \(t\) 的前缀 \(x_{1:t}\) 运行一次完整的前向传播,只读取最后一个对数几率向量 \(\mathbf{z}_t \in \mathbb{R}^V\),追加 \(x_{t+1}\),然后在第 \(t+1\) 步把 \(x_{1:t+1}\) 再次送入全部 \(L\) 个块。由于因果注意力是下三角的,每一层位置 \(s \le t\) 的表示只依赖于词元 \(1, \dots, s\),因此在第 \(t\) 步重新计算位置 \(1, \dots, t-1\) 的键和值,只是把第 \(t-1\) 步算过的张量原封不动地再算一遍。生成 \(T\) 个词元的过程中,这种冗余重算让 \(O(T^2)\) 个词元通过权重矩阵,而原本只需 \(T\) 个。

将过去的键和值保存在键值(KV)缓存(图 11.3.1)中即可消除这一冗余:在第 \(t\) 步,每一层只将单个新词元 \(x_t\) 投影为 \((\mathbf{q}_t, \mathbf{k}_t, \mathbf{v}_t)\),将 \((\mathbf{k}_t, \mathbf{v}_t)\) 写入预分配缓冲区的第 \(t\) 个槽位,并用 \(\mathbf{q}_t\) 对缓存的前缀 \((\mathbf{K}_{1:t}, \mathbf{V}_{1:t})\) 计算注意力。

然而,消除冗余浮点运算却暴露出另一重硬件瓶颈:内存容量与内存带宽。在单词元解码期间,每生成一个词元都必须将模型权重和整个 KV 缓存从 GPU 显存(HBM)流式读出,才能完成寥寥几次矩阵-向量乘法。在长上下文或大批量下,KV 缓存会膨胀至数十 GB,封顶解码吞吐量。本节前半部分构建带缓存的前向传播,并在硬件屋顶线上分析预填充、解码与批处理。后半部分(11.3.3 节)则沿三个维度压缩 KV 缓存:头数(GQA/MQA)、通道宽度(低秩键值投影)以及序列长度(带注意力汇点的滑动窗口)。

from functools import partial

11.3.1 从重算到缓存

图 11.3.1: 位置 \(t\) 处的一步解码。朴素生成会重算前缀的每一个键、值和分数行,随后却只使用最后一行。使用 KV 缓存后,过去的键和值直接从内存读取,该步只需计算单个新的键、值和分数行。

11.3.1.1 带缓存的前向传播

为什么我们在每个块中缓存键和值 \((\mathbf{K}_{1:t}, \mathbf{V}_{1:t})\),而不是查询 \(\mathbf{Q}_{1:t}\) 或残差状态 \(\mathbf{H}_{1:t}\)?在因果掩码下,查询 \(\mathbf{q}_s\)(\(s < t\))仅在输出词元 \(s+1\) 时用到,此后绝不再被引用。并且,缓存经 RoPE 旋转后的键 \(\mathbf{k}_s\) 和值 \(\mathbf{v}_s\)(各自形状为 \((B, H_{\textrm{kv}}, 1, d_h)\)),意味着过去的词元再也不需要经 \(\mathbf{W}_k, \mathbf{W}_v\) 重新投影或经 RoPE 重新旋转。

init_cache 为 \(L\) 个块中的每一个预分配清零的键和值缓冲区 ks, vs,形状为 \((B, H_{\textrm{kv}}, T_{\max}, d_h)\)。图 11.3.2 展示了生成过程中的这样一个缓冲区:位置 \(t\) 之前的槽位已填满,当前步写入槽位 \(t\),其余槽位仍为零并被掩码隐藏。

图 11.3.2: 位置 \(t\) 这一步中某个块的缓存缓冲区(单个序列、单个键值头)。槽位 \(0, \dots, t-1\) 保存先前步骤的键和值。当前步将 \(\mathbf{k}_t\) 和 \(\mathbf{v}_t\) 写入槽位 \(t\)。\(t\) 之后的槽位仍为零且被掩码屏蔽,因此查询 \(t\) 仅关注槽位 \(0, \dots, t\)。

forward_cached(model, X, ks, vs, t) 处理从位置偏移 t 开始、包含 \(n\) 个新词元的切片 X(向 RoPE 传入 offset=t,或索引 pos_emb[t:t+n]),将其键和值写入 [:, :, t:t+n, :],并对 [:, :, :t+n, :] 计算注意力:

def init_cache(model, batch_size, max_len):
    """Zeroed keys and values: for every block one buffer of each, of
    shape (batch, kv heads, max_len, head width)."""
    attn = model.blks[0].attention
    shape = (batch_size, attn.num_kv_heads, max_len,
             attn.kv_hiddens // attn.num_kv_heads)
    p = next(model.parameters())
    cache = [torch.zeros(shape, device=p.device, dtype=p.dtype)
             for _ in range(2 * len(model.blks))]
    for u in cache:  # Fixed addresses, which a compiled step writes into
        torch._dynamo.mark_static_address(u)
    return cache[::2], cache[1::2]

def forward_cached(model, X, ks, vs, t):
    """Logits after the last of the new tokens X, which sit at positions
    t, t + 1, ...; writes their keys and values into the cache."""
    assert all(blk.pre_norm for blk in model.blks), 'pre-norm blocks only'
    T = X.shape[1]
    pos = t + torch.arange(T, device=X.device)  # t: an int or a tensor
    H, tables = model.token_emb(X), None
    if model.pos == 'learned':
        H = H + model.pos_emb(pos)
    else:  # RoPE angles of positions t, ..., t + T - 1, for every block
        tables = d2l.rope_tables(T, model.head_width, t, device=X.device)
    # Query t + i sees the filled positions 0, ..., t + i of the buffer
    mask = torch.arange(ks[0].shape[2], device=X.device) <= pos[:, None]
    for i, blk in enumerate(model.blks):  # Pre-norm, as in d2l.GPT
        attn = blk.attention
        q, k, v = attn.qkv(blk.norm1(H), t, tables)  # Rotated at t, ...
        ks[i][:, :, pos], vs[i][:, :, pos] = k, v    # Written in place
        # Attention over the whole buffer; each group of query heads
        # reads one key-value head: (batch, kv heads, group, T, max_len)
        q = q.unflatten(1, (attn.num_kv_heads, -1))
        S = q @ ks[i][:, :, None].transpose(-1, -2) / math.sqrt(q.shape[-1])
        Y = d2l.masked_softmax(S, mask) @ vs[i][:, :, None]
        H = H + attn.W_o(Y.flatten(1, 2).transpose(1, 2).flatten(2))
        H = H + blk.ffn(blk.norm2(H))
    return F.linear(model.norm(H[:, -1]), model.token_emb.weight), ks, vs
def init_cache(model, batch_size, max_len):
    """Zeroed keys and values: for every block one buffer of each, of
    shape (batch, max_len, kv heads, head width)."""
    attn = model.blks[0].attention
    shape = (batch_size, max_len, attn.num_kv_heads,
             attn.kv_hiddens // attn.num_kv_heads)
    dtype = model.token_emb.embedding[...].dtype
    cache = [jnp.zeros(shape, dtype) for _ in range(2 * len(model.blks))]
    return cache[::2], cache[1::2]

def forward_cached(model, X, ks, vs, t):
    """Logits after the last of the new tokens X, which sit at positions
    t, t + 1, ...; writes their keys and values into the cache."""
    assert all(blk.pre_norm for blk in model.blks), 'pre-norm blocks only'
    B, T = X.shape
    pos = t + jnp.arange(T)  # t: an int or a traced value
    H, tables = model.token_emb(X), None
    if model.pos == 'learned':
        H = H + model.pos_emb(pos)
    else:  # RoPE angles of positions t, ..., t + T - 1, for every block
        tables = d2l.rope_tables(T, model.head_width, t)
    # Query t + i sees the filled positions 0, ..., t + i of the buffer
    mask = jnp.arange(ks[0].shape[1]) <= pos[:, None]
    ks, vs = list(ks), list(vs)
    for i, blk in enumerate(model.blks):  # Pre-norm, as in d2l.GPT
        attn = blk.attention
        q, k, v = (u.swapaxes(1, 2)  # (batch, T, heads, head width)
                   for u in attn.qkv(blk.norm1(H), t, tables))
        # A write past the end of the buffer would not fail: XLA moves the
        # start back, so the caller keeps t + T within max_len
        ks[i] = jax.lax.dynamic_update_slice(ks[i], k, (0, t, 0, 0))
        vs[i] = jax.lax.dynamic_update_slice(vs[i], v, (0, t, 0, 0))
        Y = jax.nn.dot_product_attention(q, ks[i], vs[i], mask=mask)
        H = H + attn.W_o(Y.reshape(B, T, -1))
        H = H + blk.ffn(blk.norm2(H))
    return model.token_emb.attend(model.norm(H[:, -1])), ks, vs

借助 forward_cached,generate_cached 将生成拆为两个阶段:(1)预填充,通过一次并行调用处理长度为 \(T_p\) 的整个提示(t = 0, n = T_p);(2)解码,每步处理一个新采样的词元(在偏移 t = T_p, T_p+1, ... 处取 n = 1):

def sample(logits, temperature=1.0, top_k=None):
    """One token per row of logits (batch, vocab), as generate draws it."""
    logits = logits / temperature
    if top_k is not None:
        cutoff = torch.topk(logits, top_k).values[:, -1:]
        logits = logits.masked_fill(logits < cutoff, -torch.inf)
    return torch.multinomial(F.softmax(logits, -1), 1)

# One-token steps of fixed shape, compiled once and replayed as CUDA graphs
# (mode='reduce-overhead' sets the first option; the second turns off a
# one-pass softmax that does not apply to a single query over a long cache)
decode_step = torch.compile(forward_cached, dynamic=True, options={
    'triton.cudagraphs': True, 'online_softmax': False})

@torch.inference_mode()
def decode(model, logits, ks, vs, t, num_tokens, temperature=1.0,
           top_k=None):
    """Sample num_tokens tokens per sequence, the first from logits and
    each next one after a step at positions t, t + 1, ...; returns them as
    (batch, num_tokens), and the cache."""
    pos = torch.arange(t, t + num_tokens, device=logits.device)
    tokens = [sample(logits, temperature, top_k)]
    for i in range(num_tokens - 1):  # No step after the last token
        logits, ks, vs = decode_step(model, tokens[-1], ks, vs, pos[i])
        tokens.append(sample(logits, temperature, top_k))
    return torch.cat(tokens, 1), ks, vs

@d2l.add_to_class(d2l.GPT)
def generate_cached(self, prefix, num_tokens, temperature=1.0, top_k=None):
    """Sample as generate does, but never recompute the prefix."""
    assert len(prefix) + num_tokens <= self.max_len, 'cache overflow'
    X = torch.tensor(prefix, device=next(self.parameters()).device)[None]
    ks, vs = init_cache(self, 1, len(prefix) + num_tokens)
    with torch.inference_mode():  # Prefill: the whole prompt in one call
        logits, ks, vs = forward_cached(self, X, ks, vs, 0)
    tokens = decode(self, logits, ks, vs, len(prefix), num_tokens,
                    temperature, top_k)[0]
    return list(prefix) + tokens[0].tolist()
def sample(logits, key, temperature=1.0, top_k=None):
    """One token per row of logits (batch, vocab), as generate draws it."""
    logits = logits / temperature
    if top_k is not None:
        cutoff = jax.lax.top_k(logits, top_k)[0][:, -1:]
        logits = jnp.where(logits < cutoff, -jnp.inf, logits)
    return jax.random.categorical(key, logits)[:, None]

@partial(jax.jit, static_argnames=('graphdef', 'num_tokens', 'top_k'),
         donate_argnames=('ks', 'vs'))
def decode(graphdef, params, X, ks, vs, t, num_tokens, key,
           temperature=1.0, top_k=None):
    """Feed X at positions t, t + 1, ..., then sample num_tokens tokens
    per sequence; returns them as (batch, num_tokens), and the cache."""
    model = nnx.merge(graphdef, params)
    logits, ks, vs = forward_cached(model, X, ks, vs, t)  # Prefill
    first = sample(logits, jax.random.fold_in(key, 0), temperature, top_k)
    tokens = jnp.zeros((X.shape[0], num_tokens), jnp.int32).at[:, 0].set(
        first[:, 0])
    def step(i, carry):  # Feed token i - 1, sample token i
        ks, vs, tokens = carry
        logits, ks, vs = forward_cached(model, tokens[:, i - 1, None], ks, vs,
                                        t + X.shape[1] + i - 1)
        token = sample(logits, jax.random.fold_in(key, i), temperature, top_k)
        return ks, vs, tokens.at[:, i].set(token[:, 0])
    ks, vs, tokens = jax.lax.fori_loop(1, num_tokens, step, (ks, vs, tokens))
    return tokens, ks, vs

@d2l.add_to_class(d2l.GPT)
def generate_cached(self, prefix, num_tokens, temperature=1.0, top_k=None):
    """Sample as generate does, but never recompute the prefix."""
    assert len(prefix) + num_tokens <= self.max_len, 'cache overflow'
    ks, vs = init_cache(self, 1, len(prefix) + num_tokens)
    tokens = decode(*nnx.split(self), jnp.asarray(prefix)[None], ks, vs, 0,
                    num_tokens, d2l.get_key(), temperature, top_k)[0]
    return list(prefix) + jax.device_get(tokens)[0].tolist()

11.3.1.2 检验精确等价性

在为 generate_cached 计时之前,我们先验证:预填充提示后再逐词元推进缓存,对于 pos='rope' 和 pos='learned' 两种位置编码,所得对数几率与一次性在整个序列上运行 model(X) 完全相同(误差在浮点舍入 \(\sim 10^{-6}\) 以内):

gpt = d2l.GPT
def gpt(*args, **kwargs):  # Fresh random weights for every model
    return d2l.GPT(*args, **kwargs, rngs=nnx.Rngs(d2l.get_key()))

现在我们分别在旋转位置编码(pos='rope')和学习绝对位置编码(pos='learned')下实例化 3 块 GPT,一次性预填充 \(48\) 词元序列的前 \(16\) 个词元,再逐个推进剩余 \(32\) 个位置,并测量与完整无缓存前向传播 model(x) 之间的最大绝对差异:

for pos in ('rope', 'learned'):
    model = gpt(vocab_size=97, num_hiddens=128, num_heads=4, num_blks=3,
                pos=pos).eval()
    x = torch.randint(0, 97, (1, 48))
    ks, vs = init_cache(model, 1, 48)
    with torch.inference_mode():
        full = model(x)[0, 15:]  # Logits after positions 15, ..., 47
        logits, ks, vs = forward_cached(model, x[:, :16], ks, vs, 0)
        outs = [logits]
        for t in range(16, 48):
            logits, ks, vs = forward_cached(model, x[:, t:t + 1], ks, vs, t)
            outs.append(logits)
    err = (torch.cat(outs) - full).abs().max()
    print(f'{pos}: max |full - cached| = {err:.1e}')
rope: max |full - cached| = 9.5e-07
learned: max |full - cached| = 6.0e-07
with jax.default_matmul_precision('highest'):
    for pos in ('rope', 'learned'):
        model = gpt(vocab_size=97, num_hiddens=128, num_heads=4,
                    num_blks=3, pos=pos)
        model.eval()
        x = jax.random.randint(d2l.get_key(), (1, 48), 0, 97)
        full = model(x)[0, 15:]  # Logits after positions 15, ..., 47
        ks, vs = init_cache(model, 1, 48)
        logits, ks, vs = forward_cached(model, x[:, :16], ks, vs, 0)
        outs = [logits]
        for t in range(16, 48):
            logits, ks, vs = forward_cached(model, x[:, t:t + 1], ks, vs, t)
            outs.append(logits)
        err = jnp.abs(jnp.concatenate(outs) - full).max()
        print(f'{pos}: max |full - cached| = {err:.1e}')
rope: max |full - cached| = 9.5e-07
learned: max |full - cached| = 6.0e-07

11.3.1.3 测量从二次到线性的加速

在 12 层 GPT-2 规模的模型(\(d = 768, H = 12, L = 12\))上,将无缓存前向传播处理 \(n\) 个词元的挂钟时间(time_forward,朴素解码在每一步都要重复它)与上下文长度 \(n\) 处单步带缓存解码的时间(time_decode)对比,就能看出为何长上下文生成必须使用缓存:

torch.set_float32_matmul_precision('high')  # fp32 matmuls may use tf32
device = d2l.try_gpu()
model = gpt(vocab_size=50257, num_hiddens=768, num_heads=12, num_blks=12,
            max_len=4096).to(device).eval()  # GPT-2's vocabulary and size
print(f'{d2l.num_params(model) / 1e6:.0f}M parameters')
124M parameters
model = gpt(vocab_size=50257, num_hiddens=768, num_heads=12, num_blks=12,
            max_len=4096)  # GPT-2's vocabulary and size
model.eval()
print(f'{d2l.num_params(model) / 1e6:.0f}M parameters')
124M parameters

接下来,我们使用 d2l.Benchmark 定义两个计时辅助函数:time_forward(model, n) 测量编译后对 \(n\) 个词元运行完整前缀前向传播的时间,而 time_decode(model, batch_size, n) 计算从上下文长度 \(n\) 开始连续 \(32\) 次单词元带缓存解码步骤的平均挂钟延迟:

def time_forward(model, n):
    """Seconds for a compiled forward pass over n random tokens."""
    device = next(model.parameters()).device
    x = torch.randint(0, model.token_emb.num_embeddings, (1, n),
                      device=device)
    forward = torch.compile(model)
    with torch.inference_mode():
        return d2l.Benchmark(lambda: forward(x)[:, -1]).time

def time_decode(model, batch_size, n):
    """Seconds per decode step for batch_size sequences at context n,
    averaged over 32 steps."""
    device = next(model.parameters()).device
    logits = torch.zeros(batch_size, model.token_emb.num_embeddings,
                         device=device)  # Uniform: random first tokens
    ks, vs = init_cache(model, batch_size, n + 32)
    return d2l.Benchmark(
        lambda: decode(model, logits, ks, vs, n, 33)).time / 32
@partial(jax.jit, static_argnames='graphdef')
def last_logits(graphdef, params, X):
    """The step of naive generation: a forward pass over all of X."""
    return nnx.merge(graphdef, params)(X)[:, -1]

def time_forward(model, n):
    """Seconds for a forward pass over n random tokens."""
    graphdef, params = nnx.split(model)
    x = jax.random.randint(d2l.get_key(), (1, n), 0,
                           model.token_emb.num_embeddings)
    return d2l.Benchmark(lambda: last_logits(graphdef, params, x)).time

def time_decode(model, batch_size, n):
    """Seconds per decode step for batch_size sequences at context n,
    averaged over 32 steps."""
    graphdef, params = nnx.split(model)
    x = jax.random.randint(d2l.get_key(), (batch_size, 1), 0,
                           model.token_emb.num_embeddings)
    cache = init_cache(model, batch_size, n + 32)
    def run():
        nonlocal cache  # decode consumes the cache and returns it updated
        tokens, *cache = decode(graphdef, params, x, *cache, n - 1, 32,
                                d2l.get_key())
        return tokens
    return d2l.Benchmark(run).time / 32

将上下文长度 \(n\) 按 2 的幂从 \(256\) 扫描至 \(4{,}032\) 个词元,对比每次无缓存步骤的线性增长与带缓存解码步骤近乎平坦的延迟:

lengths, t_naive, t_cached = [256, 512, 1024, 2048, 4032], [], []
for n in lengths:
    t_naive.append(time_forward(model, n))
    t_cached.append(time_decode(model, 1, n))
    print(f'n={n:4d}: naive {1e3 * t_naive[-1]:5.1f} ms, '
          f'cached {1e3 * t_cached[-1]:4.1f} ms per token')
n= 256: naive   2.7 ms, cached  0.9 ms per token
n= 512: naive   3.3 ms, cached  0.9 ms per token
n=1024: naive   6.5 ms, cached  0.9 ms per token
n=2048: naive  13.6 ms, cached  1.0 ms per token
n=4032: naive  33.2 ms, cached  1.2 ms per token
lengths, t_naive, t_cached = [256, 512, 1024, 2048, 4032], [], []
for n in lengths:
    t_naive.append(time_forward(model, n))
    t_cached.append(time_decode(model, 1, n))
    print(f'n={n:4d}: naive {1e3 * t_naive[-1]:5.1f} ms, '
          f'cached {1e3 * t_cached[-1]:4.1f} ms per token')
n= 256: naive   1.6 ms, cached  0.8 ms per token
n= 512: naive   2.5 ms, cached  0.9 ms per token
n=1024: naive   5.1 ms, cached  0.9 ms per token
n=2048: naive  16.7 ms, cached  1.0 ms per token
n=4032: naive  53.4 ms, cached  1.3 ms per token

在对数-对数坐标上绘制两条单词元延迟曲线可以看到,朴素步骤的开销随上下文长度 \(n\) 成正比增长,而带缓存步骤几乎保持平坦(新查询仍需与全部 \(n\) 个缓存键计算分数,但该项常数很小):

d2l.plot(lengths, [[1e3 * t for t in t_naive], [1e3 * t for t in t_cached]],
         'context length', 'ms per token', legend=['naive', 'cached'],
         xscale='log', yscale='log')

d2l.plot(lengths, [[1e3 * t for t in t_naive], [1e3 * t for t in t_cached]],
         'context length', 'ms per token', legend=['naive', 'cached'],
         xscale='log', yscale='log')

在 \(3{,}584\) 词元提示之后端到端生成 \(256\) 个新词元时,用 model.generate_cached 替换 model.generate 可带来超过一个数量级的挂钟加速:

prefix = list(range(3584))  # Any token ids will do for timing
for name, gen in (('naive ', model.generate),
                  ('cached', model.generate_cached)):
    t = d2l.Benchmark(lambda: gen(prefix, 256), warmup=1, repeats=1).time
    print(f'{name}: 256 tokens in {t:4.1f} s = {256 / t:5.1f} tokens/s')
naive : 256 tokens in  8.1 s =  31.5 tokens/s
cached: 256 tokens in  0.5 s = 557.2 tokens/s
prefix = list(range(3584))  # Any token ids will do for timing
for name, gen in (('naive ', model.generate),
                  ('cached', model.generate_cached)):
    t = d2l.Benchmark(lambda: gen(prefix, 256), warmup=1, repeats=1).time
    print(f'{name}: 256 tokens in {t:4.1f} s = {256 / t:5.1f} tokens/s')
naive : 256 tokens in 15.2 s =  16.8 tokens/s
cached: 256 tokens in  0.4 s = 641.6 tokens/s

11.3.2 内存容量与硬件屋顶线

对于包含 \(L\) 个块、批量大小 \(B\)、序列长度 \(n\)、\(H_{\textrm{kv}}\) 个宽度为 \(d_h\) 的键值头、每个数值占 \(b\) 字节(FP32 为 \(b = 4\),BF16/FP16 为 \(2\),FP8 为 \(1\))的模型,每个块需存储两个形状为 \((B, H_{\textrm{kv}}, n, d_h)\) 的张量(\(\mathbf{K}\) 和 \(\mathbf{V}\))。因此 KV 缓存的总占用为

\[ M_{\textrm{KV}}(n, B) \;=\; 2 \, b \, B \, L \, n \, H_{\textrm{kv}} \, d_h \;\;\textrm{bytes}. \tag{11.3.1}\]

def kv_cache_bytes(model, num_tokens, batch_size=1, bytes_per_elem=4):
    """Bytes of the keys and values of num_tokens positions in every block
    of a GPT, for batch_size sequences."""
    attn = model.blks[0].attention
    return (2 * len(model.blks) * attn.kv_hiddens * num_tokens * batch_size
            * bytes_per_elem)

def kv_cache_bytes(model, num_tokens, batch_size=1, bytes_per_elem=4):
    """Bytes of the keys and values of num_tokens positions in every block
    of a GPT, for batch_size sequences."""
    attn = model.blks[0].attention
    return (2 * len(model.blks) * attn.kv_hiddens * num_tokens * batch_size
            * bytes_per_elem)

在 \(n = 4{,}096\) 个词元处对 124M 参数的 FP32 模型调用 kv_cache_bytes,确认已分配的缓存缓冲区与 式 11.3.1 一致(\(288\textrm{ MiB}\)),并且已经超过模型权重 \(471\textrm{ MiB}\) 占用的一半:

bytes_per_param = 4  # fp32 weights
weight_bytes = bytes_per_param * d2l.num_params(model)
ks, vs = init_cache(model, 1, 4096)
print(f'cache buffers {sum(u.nbytes for u in ks + vs) / 2**20:.0f} MiB, '
      f'formula {kv_cache_bytes(model, 4096) / 2**20:.0f} MiB, '
      f'weights {weight_bytes / 2**20:.0f} MiB')
cache buffers 288 MiB, formula 288 MiB, weights 471 MiB
bytes_per_param = 4  # fp32 weights
weight_bytes = bytes_per_param * d2l.num_params(model)
ks, vs = init_cache(model, 1, 4096)
print(f'cache buffers {sum(u.nbytes for u in ks + vs) / 2**20:.0f} MiB, '
      f'formula {kv_cache_bytes(model, 4096) / 2**20:.0f} MiB, '
      f'weights {weight_bytes / 2**20:.0f} MiB')
cache buffers 288 MiB, formula 288 MiB, weights 471 MiB

11.3.2.1 屋顶线上的预填充与解码

为什么一次 2,048 词元的预填充耗时与大约十五步单词元解码处于同一数量级?屋顶线模型(图 11.3.3)通过算术强度(在 HBM 与计算单元之间每传输一字节所执行的浮点运算次数)解释了这一差异:

  • 预填充(并行处理 \(n = 2048\) 个词元,受算力限制):每个权重矩阵 \(\mathbf{W}\) 只需从 HBM 读取一次,便与 \(B n\) 个词元向量相乘(在 \(b_w N_{\textrm{params}}\) 字节的权重上执行 \(2 B n N_{\textrm{params}}\) 次浮点运算),算术强度达 \(\sim 2 B n / b_w \gg 80\textrm{ FLOPs/byte}\)——远高于 GPU 的拐点,足以打满张量核。
  • 单流解码(每步 \(B = 1, n = 1\) 个词元,受内存带宽限制):每步仅执行 \(2 N_{\textrm{params}}\) 次矩阵-向量浮点运算,却必须从 HBM 流式读取全部 \(b_w N_{\textrm{params}}\) 字节权重以及 \(M_{\textrm{KV}}(n, 1)\) 字节缓存,算术强度 \(\le 2 / b_w \approx 0.5\textrm{ FLOPs/byte}\)(FP32 下;BF16 下为 \(1.0\textrm{ FLOP/byte}\))——比算力屋顶低 \(100\times\) 以上。
图 11.3.3: RTX 4090 的 fp32 屋顶线。可达吞吐量是算力屋顶(约 83 TFLOP/s)与算术强度乘以内存带宽(约 1 TB/s)两者中的较小值;二者相交于约 82 FLOPs/byte 的拐点。GPT-2 规模模型在 2,048 词元上下文下的单步解码仅执行 0.38 FLOPs/byte,远远落在带宽斜坡下方;而 2,048 词元的预填充仅计权重与缓存就达到约 780,稳居算力屋顶之下。
t_prefill = time_forward(model, 2048)
t_decode = time_decode(model, 1, 2048)
t_prefill = time_forward(model, 2048)
t_decode = time_decode(model, 1, 2048)

将实测词元吞吐量与算术强度对照 \(1\textrm{ TB/s}\) 的 HBM 带宽预算,可以清楚看到为何单流解码贴近内存带宽上限,而 \(2{,}048\) 词元预填充的吞吐量高出 \(100\times\) 以上:

bandwidth = 1e12  # bytes/s, about an RTX 4090
flops = 2 * d2l.num_params(model)  # One decode step at context 2048
moved = weight_bytes + kv_cache_bytes(model, 2048)
print(f'prefill: {2048 / t_prefill:6.0f} tokens/s')
print(f'decode:  {1 / t_decode:6.0f} tokens/s, bandwidth ceiling '
      f'{bandwidth / moved:.0f} tokens/s')
print(f'FLOPs per byte: decode {flops / moved:.2f}, '
      f'prefill about {2048 * flops / moved:.0f}')
prefill: 150413 tokens/s
decode:     952 tokens/s, bandwidth ceiling 1550 tokens/s
FLOPs per byte: decode 0.38, prefill about 784
bandwidth = 1e12  # bytes/s, about an RTX 4090
flops = 2 * d2l.num_params(model)  # One decode step at context 2048
moved = weight_bytes + kv_cache_bytes(model, 2048)
print(f'prefill: {2048 / t_prefill:6.0f} tokens/s')
print(f'decode:  {1 / t_decode:6.0f} tokens/s, bandwidth ceiling '
      f'{bandwidth / moved:.0f} tokens/s')
print(f'FLOPs per byte: decode {flops / moved:.2f}, '
      f'prefill about {2048 * flops / moved:.0f}')
prefill: 121629 tokens/s
decode:     997 tokens/s, bandwidth ceiling 1550 tokens/s
FLOPs per byte: decode 0.38, prefill about 784

11.3.2.2 批处理解码

由于单流解码步(\(B = 1\))的时间主要花在从 HBM 流式读取模型权重字节 \(M_{\textrm{weights}} = b_w N_{\textrm{params}}\) 上,同时解码 \(B\) 条序列可以将每次权重读取复用到全部 \(B\) 个词元上,同时读取 \(B\) 份各自的 KV 缓存(\(B \, M_{\textrm{KV}}(n, 1)\) 字节)。在内存带宽为 \(\mathcal{B}_{\textrm{HBM}}\)(字节/秒)时,受带宽限制的解码吞吐量(词元/秒)为

\[ \textrm{Throughput}(B, n) \;\le\; \frac{B \, \mathcal{B}_{\textrm{HBM}}}{M_{\textrm{weights}} + B \, M_{\textrm{KV}}(n, 1)}. \tag{11.3.2}\]

在小批量下(\(B \, M_{\textrm{KV}} \ll M_{\textrm{weights}}\)),吞吐量几乎随 \(B\) 线性增长(“免费批处理”);随着 \(B\) 或 \(n\) 增大(\(B \, M_{\textrm{KV}} \gg M_{\textrm{weights}}\)),KV 缓存读取主导 HBM 流量,吞吐量在 KV 带宽上限 \(\mathcal{B}_{\textrm{HBM}} / M_{\textrm{KV}}(n, 1)\) 处趋于饱和:

batches, measured, bounds = [1, 4, 16, 64], [], []
for n in (128, 1024):
    measured.append([b / time_decode(model, b, n) for b in batches])
    nc = kv_cache_bytes(model, n)  # One sequence's cache
    bounds.append([b * bandwidth / (weight_bytes + b * nc) for b in batches])
    print(f'n={n}: ' + ', '.join(f'{r:.0f}' for r in measured[-1])
          + ' tokens/s')
d2l.plot(batches, measured + bounds, 'batch size', 'tokens per second',
         legend=['n=128', 'n=1024'], fmts=('C0-o', 'C1-s', 'C0:', 'C1:'),
         xscale='log', yscale='log', legend_loc='lower right')
n=128: 1173, 3574, 12353, 32525 tokens/s
n=1024: 1104, 2783, 6507, 9902 tokens/s

batches, measured, bounds = [1, 4, 16, 64], [], []
for n in (128, 1024):
    measured.append([b / time_decode(model, b, n) for b in batches])
    nc = kv_cache_bytes(model, n)  # One sequence's cache
    bounds.append([b * bandwidth / (weight_bytes + b * nc) for b in batches])
    print(f'n={n}: ' + ', '.join(f'{r:.0f}' for r in measured[-1])
          + ' tokens/s')
d2l.plot(batches, measured + bounds, 'batch size', 'tokens per second',
         legend=['n=128', 'n=1024'], fmts=('C0-o', 'C1-s', 'C0:', 'C1:'),
         xscale='log', yscale='log', legend_loc='lower right')
n=128: 1270, 4689, 15790, 36660 tokens/s
n=1024: 1072, 3346, 7245, 9994 tokens/s

11.3.3 缩减 KV 缓存

由于内存容量(式 11.3.1)与大批量解码吞吐量上限(式 11.3.2)均由单序列缓存大小 \(M_{\textrm{KV}}(n, 1) = 2 b L n H_{\textrm{kv}} d_h\) 决定,现代 Transformer 架构沿三条正交轴压缩乘积 \(n \cdot H_{\textrm{kv}} \cdot d_h\):

  1. 更少的键值头(\(H_{\textrm{kv}} < H\)):分组查询注意力(GQA) (Ainslie 等 2023年) 与多查询注意力(MQA) (Shazeer 2019年) 让每 \(G = H / H_{\textrm{kv}}\) 个查询头共享一个键值头(图 11.3.4)。
  2. 更窄的单词元表示(\(2 H_{\textrm{kv}} d_h \to r\)):低秩键值投影与多头潜在注意力(MLA) (DeepSeek-AI 等 2024年) 将所有头的键和值压缩为一个低维潜在向量(11.3.3.2 节)。
  3. 更短的缓存上下文(\(n \to w + s\)):滑动窗口注意力驱逐早于窗口 \(w\) 的词元,同时保留 \(s \ge 1\) 个初始注意力汇点词元 (Xiao 等 2024年),以保持 softmax 分母稳定(11.3.3.3 节)。
图 11.3.4: 查询头及其读取的键值头。多头注意力为每个查询头配备独立的键值头;分组查询注意力为每组查询头共享一个键值头;多查询注意力让所有查询头共享单个键值头。缓存大小随键值头数量线性缩放。

11.3.3.1 轴 1:分组查询注意力与检查点增量训练

我们的 CausalAttention 类(11.2 节)已经支持 num_kv_heads:设置 \(H_{\textrm{kv}} = H / G\) 会缩小 \(\mathbf{W}_{qkv}\) 并将 \(M_{\textrm{KV}}\) 削减 \(G = H / H_{\textrm{kv}}\) 倍。此外,Ainslie 等 (2023年) 表明,通过对每组 \(G\) 个键和值投影头做均值池化(pool_heads),再以原训练预算的一小部分(\(\sim 5\text{--}10\%\))进行增量训练(uptraining),即可将已有的多头检查点(\(H_{\textrm{kv}} = H\))转换为 GQA 或 MQA 模型。

我们将从零训练 1,000 步、\(H_{\textrm{kv}} \in \{8, 2\}\) 的 6 块字节级 GPT(\(H = 8\))(以及仅从零训练 50 步的 \(H_{\textrm{kv}} = 2\) 模型),与把已训练的 \(H_{\textrm{kv}} = 8\) 检查点通过均值池化或仅保留每组首个头转换为 \(H_{\textrm{kv}} = 2\) 的结果进行对比,在两次运行中分别考察零样本(0 步)以及 50 步和 100 步(\(10\%\))增量训练后的表现:

def pool_heads(target, source, pool):
    """Load the weights of source into target, which has fewer key-value
    heads. Each key (and value) projection of target is the mean of those
    of a group of consecutive heads of source (pool='mean'), or the first
    of them (pool='first')."""
    src, tgt = source.blks[0].attention, target.blks[0].attention
    group = src.num_kv_heads // tgt.num_kv_heads
    state = source.state_dict()
    for name, W in state.items():
        if name.endswith('W_qkv.weight'):  # Rows: d queries, keys, values
            q, k, v = W.split([W.shape[1], src.kv_hiddens, src.kv_hiddens])
            k, v = (u.unflatten(0, (tgt.num_kv_heads, group, -1))
                    for u in (k, v))
            k, v = ((u.mean(1) if pool == 'mean' else u[:, 0]).flatten(0, 1)
                    for u in (k, v))
            state[name] = torch.cat([q, k, v])
    target.load_state_dict(state)
    return target.to(next(source.parameters()).device)
def pool_heads(target, source, pool):
    """Load the weights of source into target, which has fewer key-value
    heads. Each key (and value) projection of target is the mean of those
    of a group of consecutive heads of source (pool='mean'), or the first
    of them (pool='first')."""
    src, tgt = source.blks[0].attention, target.blks[0].attention
    group = src.num_kv_heads // tgt.num_kv_heads
    def convert(path, W):
        if 'W_qkv' not in jax.tree_util.keystr(path):
            return W
        d = W.shape[0]  # Kernel columns: d queries, keys, values
        q, k, v = jnp.split(W, [d, d + src.kv_hiddens], axis=1)
        k, v = (u.reshape(d, tgt.num_kv_heads, group, -1) for u in (k, v))
        k, v = ((u.mean(2) if pool == 'mean' else u[:, :, 0]).reshape(d, -1)
                for u in (k, v))
        return jnp.concatenate([q, k, v], axis=1)
    nnx.update(target, jax.tree_util.tree_map_with_path(
        convert, nnx.state(source, nnx.Param)))
    return target

现在我们在 WikiText103 上以 \(H_{\textrm{kv}} \in \{8, 2\}\) 训练 6 块字节级 GPT,并在 \(0\)、\(50\) 和 \(100\) 步增量训练下评估采用 'mean' 与 'first' 两种头池化方式的 pool_heads:

data = d2l.WikiText103(batch_size=64, num_steps=128)

def trained(num_kv_heads, num_steps=1000):
    """A d2l.GPT trained from scratch with the recipe of the GPT section."""
    lm = gpt(len(data.vocab), num_kv_heads=num_kv_heads)
    optimizer = d2l.LMOptimizer(lm, lr=2e-3, num_steps=num_steps,
                                warmup=min(100, num_steps // 10))
    d2l.train_steps(lm, data, optimizer, num_steps)
    return lm

def val_loss(lm):
    return math.log(d2l.lm_perplexity(lm, data.val_dataloader()))

for run in (1, 2):
    mha = trained(8)
    print(f'run {run}, trained from scratch: H_kv=8 {val_loss(mha):.2f}, '
          f'H_kv=2 {val_loss(trained(2)):.2f}, '
          f'H_kv=2 for 50 steps only {val_loss(trained(2, 50)):.2f}')
    for pool in ('mean', 'first'):
        lm = pool_heads(gpt(len(data.vocab), num_kv_heads=2), mha, pool)
        losses = [val_loss(lm)]
        optimizer = d2l.LMOptimizer(lm, lr=3e-4, num_steps=10**9, warmup=0)
        for _ in range(2):  # Uptraining at a constant rate
            d2l.train_steps(lm, data, optimizer, 50)
            losses.append(val_loss(lm))
        print(f'  H_kv=8 converted by {pool:5s}: {losses[0]:.2f}, after 50 '
              f'steps {losses[1]:.2f}, after 100 steps {losses[2]:.2f}')
run 1, trained from scratch: H_kv=8 1.34, H_kv=2 1.35, H_kv=2 for 50 steps only 2.66
  H_kv=8 converted by mean : 2.76, after 50 steps 1.62, after 100 steps 1.47
  H_kv=8 converted by first: 2.83, after 50 steps 1.89, after 100 steps 1.71
run 2, trained from scratch: H_kv=8 1.34, H_kv=2 1.35, H_kv=2 for 50 steps only 2.66
  H_kv=8 converted by mean : 2.75, after 50 steps 1.62, after 100 steps 1.46
  H_kv=8 converted by first: 2.71, after 50 steps 1.79, after 100 steps 1.64
data = d2l.WikiText103(batch_size=64, num_steps=128)

def trained(num_kv_heads, num_steps=1000):
    """A d2l.GPT trained from scratch with the recipe of the GPT section."""
    lm = gpt(len(data.vocab), num_kv_heads=num_kv_heads)
    optimizer = d2l.LMOptimizer(lm, lr=2e-3, num_steps=num_steps,
                                warmup=min(100, num_steps // 10))
    d2l.train_steps(lm, data, optimizer, num_steps)
    return lm

def val_loss(lm):
    return math.log(d2l.lm_perplexity(lm, data.val_dataloader()))

for run in (1, 2):
    mha = trained(8)
    print(f'run {run}, trained from scratch: H_kv=8 {val_loss(mha):.2f}, '
          f'H_kv=2 {val_loss(trained(2)):.2f}, '
          f'H_kv=2 for 50 steps only {val_loss(trained(2, 50)):.2f}')
    for pool in ('mean', 'first'):
        lm = pool_heads(gpt(len(data.vocab), num_kv_heads=2), mha, pool)
        losses = [val_loss(lm)]
        optimizer = d2l.LMOptimizer(lm, lr=3e-4, num_steps=10**9, warmup=0)
        for _ in range(2):  # Uptraining at a constant rate
            d2l.train_steps(lm, data, optimizer, 50)
            losses.append(val_loss(lm))
        print(f'  H_kv=8 converted by {pool:5s}: {losses[0]:.2f}, after 50 '
              f'steps {losses[1]:.2f}, after 100 steps {losses[2]:.2f}')
run 1, trained from scratch: H_kv=8 1.34, H_kv=2 1.34, H_kv=2 for 50 steps only 2.66
  H_kv=8 converted by mean : 2.85, after 50 steps 1.68, after 100 steps 1.48
  H_kv=8 converted by first: 2.96, after 50 steps 1.80, after 100 steps 1.64
run 2, trained from scratch: H_kv=8 1.34, H_kv=2 1.34, H_kv=2 for 50 steps only 2.67
  H_kv=8 converted by mean : 2.75, after 50 steps 1.62, after 100 steps 1.46
  H_kv=8 converted by first: 2.87, after 50 steps 1.72, after 100 steps 1.57

让 4 个查询头共享一组键值(\(H_{\textrm{kv}} = 2\),KV 缓存缩小 \(4\times\))在从零训练时几乎没有可测量的质量损失(1.34–1.35 对比 1.34 奈特/字节)。头池化初始损失接近 2.8 奈特/字节,而仅需 100 步增量训练即可使均值池化模型恢复至约 1.47,回升了约 90% 的差距;相比之下,从零训练 50 步只能达到约 2.7,而仅保留每组首个头在增量训练后也落后于均值池化。

11.3.3.2 轴 2:低秩键值投影

除了减少头数 \(H_{\textrm{kv}}\),我们能否将第 \(i\) 层每个词元拼接后的 \(2 d\) 维键值向量 \([\mathbf{k}_t; \mathbf{v}_t] \in \mathbb{R}^{2d}\) 压缩到一个秩为 \(r\) 的子空间(\(r \ll 2d\))?我们直接在预训练的 GPT-2 Small(124M,其中 \(d = 768\),\(2d = 1536\))上,取《时间机器》中 \(T = 1024\) 个词元的段落进行测试:

gpt2, enc = d2l.load_gpt2().to(device), d2l.gpt2_tokenizer()
fname = d2l.download(d2l.DATA_URL + 'timemachine.txt', '../data',
                     '090b5e7e70c295757f55df93cb0a180b9691891a')
tokens = torch.tensor(enc.encode(open(fname).read()), device=device)
x, calib = tokens[None, :1024], tokens[None, 1024:2048]
print(f'{len(tokens)} tokens of The Time Machine')
44073 tokens of The Time Machine
gpt2, enc = d2l.load_gpt2(), d2l.gpt2_tokenizer()
fname = d2l.download(d2l.DATA_URL + 'timemachine.txt', '../data',
                     '090b5e7e70c295757f55df93cb0a180b9691891a')
tokens = jnp.asarray(enc.encode(open(fname).read()))
x, calib = tokens[None, :1024], tokens[None, 1024:2048]
print(f'{len(tokens)} tokens of The Time Machine')
44073 tokens of The Time Machine

为了在不重写 GPT 的前提下拦截并变换每一层的键和值,我们定义 forward_blocks(model, X, attn_fn),将第 \(i\) 块的注意力委托给回调函数 attn_fn(q, k, v, i),并验证标准因果注意力与 gpt2(x) 吻合至 \(10^{-5}\) 以内,同时建立位置 \(512 \dots 1023\) 上的基线 tail_loss:

def forward_blocks(model, X, attn_fn):
    """The forward pass of a d2l.GPT with attention computed by
    attn_fn(q, k, v, i) in block i, on inputs of shape (batch, heads,
    length, head width)."""
    assert all(blk.pre_norm for blk in model.blks), 'pre-norm blocks only'
    H = model.token_emb(X)
    if model.pos == 'learned':
        H = H + model.pos_emb(torch.arange(X.shape[1], device=X.device))
    for i, blk in enumerate(model.blks):
        attn = blk.attention
        Y = attn_fn(*attn.qkv(blk.norm1(H)), i)
        H = H + attn.W_o(Y.transpose(1, 2).flatten(2))
        H = H + blk.ffn(blk.norm2(H))
    return F.linear(model.norm(H), model.token_emb.weight)

def tail_loss(logits, X):
    """Mean loss of the next-token predictions from position 512 on."""
    return F.cross_entropy(logits[0, 512:-1], X[0, 513:])

causal = lambda q, k, v, i: F.scaled_dot_product_attention(
    q, k, v, is_causal=True)
with torch.inference_mode():
    logits = forward_blocks(gpt2, x, causal)
    print(f'helper vs model: max deviation '
          f'{(logits - gpt2(x)).abs().max():.1e}')
    full = tail_loss(logits, x)
print(f'full attention: loss {full:.2f}, perplexity {full.exp():.0f}')
helper vs model: max deviation 0.0e+00
full attention: loss 3.58, perplexity 36
def forward_blocks(model, X, attn_fn):
    """The forward pass of a d2l.GPT with attention computed by
    attn_fn(q, k, v, i) in block i, on inputs of shape (batch, heads,
    length, head width)."""
    assert all(blk.pre_norm for blk in model.blks), 'pre-norm blocks only'
    H = model.token_emb(X)
    if model.pos == 'learned':
        H = H + model.pos_emb(jnp.arange(X.shape[1]))
    for i, blk in enumerate(model.blks):
        attn = blk.attention
        Y = attn_fn(*attn.qkv(blk.norm1(H)), i)
        H = H + attn.W_o(Y.swapaxes(1, 2).reshape(*X.shape, -1))
        H = H + blk.ffn(blk.norm2(H))
    return model.token_emb.attend(model.norm(H))

def tail_loss(logits, X):
    """Mean loss of the next-token predictions from position 512 on."""
    return optax.softmax_cross_entropy_with_integer_labels(
        logits[0, 512:-1], X[0, 513:]).mean()

def causal(q, k, v, i):
    """Fused causal attention; the kernel wants (batch, length, ...)."""
    return jax.nn.dot_product_attention(
        *(u.swapaxes(1, 2) for u in (q, k, v)), is_causal=True).swapaxes(1, 2)

logits = forward_blocks(gpt2, x, causal)
print(f'helper vs model: max deviation '
      f'{jnp.abs(logits - gpt2(x)).max():.1e}')
full = tail_loss(logits, x)
print(f'full attention: loss {full:.2f}, perplexity {jnp.exp(full):.0f}')
helper vs model: max deviation 0.0e+00
full attention: loss 3.58, perplexity 36

利用书中接下来的 1,024 个词元(calib)为每一层拼接后的键值行拟合经验 PCA/SVD 基 \(\mathbf{U}_i \in \mathbb{R}^{2d \times r}\)(fit_bases),并将待评估段落 x 的键和值投影到前 \(r \in \{512, 256, 128\}\) 个主方向(projected),从而度量即便不重新训练,GPT-2 的 KV 缓存也具备多高的可压缩性:

def kv_rows(k, v):
    """Keys and values of all heads of each token as one row: (T, 2d)."""
    return torch.cat([u[0].transpose(0, 1).flatten(1) for u in (k, v)], 1)

def fit_bases(model, X):
    """Right singular vectors of the key-value rows of X in every block."""
    bases = []
    def fit(q, k, v, i):
        bases.append(torch.linalg.svd(kv_rows(k, v), full_matrices=False)[2])
        return causal(q, k, v, i)
    forward_blocks(model, X, fit)
    return bases

def projected(bases, r):
    """Attention with keys and values projected onto the top r bases."""
    def attn_fn(q, k, v, i):
        P = bases[i][:r]  # (r, 2d), orthonormal rows
        KV = kv_rows(k, v) @ P.T @ P
        k, v = (u.unflatten(1, (k.shape[1], -1)).transpose(0, 1)[None]
                for u in KV.chunk(2, 1))
        return causal(q, k, v, i)
    return attn_fn

with torch.inference_mode():
    bases = fit_bases(gpt2, calib)
    for r in (512, 256, 128):
        loss = tail_loss(forward_blocks(gpt2, x, projected(bases, r)), x)
        print(f'rank {r} of 768: loss {loss:.2f}, '
              f'perplexity {loss.exp():.0f}')
rank 512 of 768: loss 3.55, perplexity 35
rank 256 of 768: loss 3.61, perplexity 37
rank 128 of 768: loss 4.14, perplexity 63
def kv_rows(k, v):
    """Keys and values of all heads of each token as one row: (T, 2d)."""
    return jnp.concatenate(
        [u[0].swapaxes(0, 1).reshape(u.shape[2], -1) for u in (k, v)], 1)

def fit_bases(model, X):
    """Right singular vectors of the key-value rows of X in every block."""
    bases = []
    def fit(q, k, v, i):
        bases.append(jnp.linalg.svd(kv_rows(k, v), full_matrices=False)[2])
        return causal(q, k, v, i)
    forward_blocks(model, X, fit)
    return bases

def projected(bases, r):
    """Attention with keys and values projected onto the top r bases."""
    def attn_fn(q, k, v, i):
        P = bases[i][:r]  # (r, 2d), orthonormal rows
        KV = kv_rows(k, v) @ P.T @ P
        k, v = (u.reshape(u.shape[0], k.shape[1], -1).swapaxes(0, 1)[None]
                for u in jnp.split(KV, 2, axis=1))
        return causal(q, k, v, i)
    return attn_fn

bases = fit_bases(gpt2, calib)
for r in (512, 256, 128):
    loss = tail_loss(forward_blocks(gpt2, x, projected(bases, r)), x)
    print(f'rank {r} of 768: loss {loss:.2f}, '
          f'perplexity {jnp.exp(loss):.0f}')
rank 512 of 768: loss 3.55, perplexity 35
rank 256 of 768: loss 3.61, perplexity 37
rank 128 of 768: loss 4.14, perplexity 63

由于每个块都用一个矩阵加一个偏置从同一个 \(d\) 维输入计算其 \(2d\) 个键和值,它们必然落在一个仅 \(d = 768\) 维的仿射子空间中,这正是输出里“of 768”的由来。即便是事后线性投影,也能将 GPT-2 的 KV 向量压缩 \(6\times\)(从 \(2d = 1536\) 压到 \(r = 256\))而几乎没有可测量的退化(3.61 对比 3.58 奈特),而 \(r = 128\) 则会增加超过半个奈特的损失;若像 DeepSeek-V2/V3 的多头潜在注意力(MLA) (DeepSeek-AI 等 2024年) 那样端到端训练低秩瓶颈,单个 512 维潜在向量即可替代所有头的键和值,压缩率达 \(>16\times\)。

11.3.3.3 轴 3:滑动窗口与注意力汇点

第三条轴将缓存中保存的序列长度 \(n\) 限制为最近 \(w\) 个词元的滚动窗口(10.6 节)。然而,如果直接对 1,024 词元段落上的预训练 GPT-2 施加纯滑动窗口(\(w = 256\)),尾部词元(\(t \ge 512\))的交叉熵会从 \(\sim 3.6\) 奈特飙升至 \(8\) 奈特以上。

为了查明原因,sink_mass 测量 GPT-2 全部 12 层中,位置 \(t \ge 64\) 的查询分配给词元 0(序列最开头的第一个词元)的平均注意力概率:

def sink_mass(model, X):
    """Mean attention weight on token 0 of the queries from position 64
    on, one entry per block."""
    masses = []
    def watch(q, k, v, i):  # Explicit causal attention
        scores = q @ k.transpose(-1, -2) / math.sqrt(q.shape[-1])
        alpha = d2l.masked_softmax(scores, d2l.causal_mask(
            q.shape[2], device=q.device))
        masses.append(alpha[..., 64:, 0].mean())
        return alpha @ v
    forward_blocks(model, X, watch)
    return masses

with torch.inference_mode():
    masses = sink_mass(gpt2, x)
print('mean attention weight on token 0 (uniform would be about 0.003)')
print('block ' + ''.join(f'{i:6d}' for i in range(len(masses))))
print('weight' + ''.join(f'{m:6.2f}' for m in torch.stack(masses).tolist()))
mean attention weight on token 0 (uniform would be about 0.003)
block      0     1     2     3     4     5     6     7     8     9    10    11
weight  0.00  0.01  0.11  0.30  0.32  0.51  0.46  0.57  0.48  0.48  0.45  0.34
def sink_mass(model, X):
    """Mean attention weight on token 0 of the queries from position 64
    on, one entry per block."""
    masses = []
    def watch(q, k, v, i):  # Explicit causal attention
        scores = q @ k.swapaxes(-1, -2) / math.sqrt(q.shape[-1])
        alpha = d2l.masked_softmax(scores, d2l.causal_mask(q.shape[2]))
        masses.append(alpha[..., 64:, 0].mean())
        return alpha @ v
    forward_blocks(model, X, watch)
    return masses

masses = sink_mass(gpt2, x)
print('mean attention weight on token 0 (uniform would be about 0.003)')
print('block ' + ''.join(f'{i:6d}' for i in range(len(masses))))
print('weight' + ''.join(f'{m:6.2f}' for m in jax.device_get(masses)))
mean attention weight on token 0 (uniform would be about 0.003)
block      0     1     2     3     4     5     6     7     8     9    10    11
weight  0.00  0.01  0.11  0.30  0.32  0.51  0.46  0.57  0.48  0.48  0.45  0.34

在 GPT-2 的中层和高层,无论位置 0 上是什么词,查询都会把 30% 到近 60% 的全部注意力权重放在词元 0 上。由于 softmax 概率之和必须为 \(1\),当没有匹配的局部词元时,注意力头就会把最早的词元——唯一对所有因果查询都可见的位置——当作默认的注意力汇点 (Xiao 等 2024年)。一旦纯滑动窗口滑过位置 0(\(t \ge w\)),将词元 0 从 softmax 分母中移除会迫使那 \(30\text{--}60\%\) 的概率质量倾泻到剩余窗口词元上,从而搅乱残差流。

只需在缓存最前端固定保留 \(s \in \{1, 4\}\) 个初始汇点词元,与最近 \(w = 256\) 个词元并存(总共缓存 \(w + s\) 个词元),就能让 GPT-2 的验证损失几乎完全恢复到全上下文基线:

j = torch.arange(x.shape[1], device=device)
allowed = d2l.causal_mask(x.shape[1], device=device)
w = 256  # The window: each query sees itself and the 255 tokens before it
window = allowed & (j[:, None] - j[None, :] < w)
with torch.inference_mode():
    for nsink in (0, 1, 4):
        mask = window | (allowed & (j[None, :] < nsink))
        loss = tail_loss(forward_blocks(
            gpt2, x, lambda q, k, v, i: F.scaled_dot_product_attention(
                q, k, v, attn_mask=mask)), x)
        print(f'window {w} + {nsink} sink tokens: loss {loss:.2f}, '
              f'perplexity {loss.exp():.0f}')
print(f'full attention:            loss {full:.2f}, '
      f'perplexity {full.exp():.0f}')
window 256 + 0 sink tokens: loss 8.25, perplexity 3842
window 256 + 1 sink tokens: loss 3.86, perplexity 47
window 256 + 4 sink tokens: loss 3.76, perplexity 43
full attention:            loss 3.58, perplexity 36
j = jnp.arange(x.shape[1])
allowed = d2l.causal_mask(x.shape[1])
w = 256  # The window: each query sees itself and the 255 tokens before it
window = allowed & (j[:, None] - j[None, :] < w)
for nsink in (0, 1, 4):
    mask = window | (allowed & (j[None, :] < nsink))
    loss = tail_loss(forward_blocks(
        gpt2, x, lambda q, k, v, i: jax.nn.dot_product_attention(
            *(u.swapaxes(1, 2) for u in (q, k, v)),
            mask=mask).swapaxes(1, 2)), x)
    print(f'window {w} + {nsink} sink tokens: loss {loss:.2f}, '
          f'perplexity {jnp.exp(loss):.0f}')
print(f'full attention:            loss {full:.2f}, '
      f'perplexity {jnp.exp(full):.0f}')
window 256 + 0 sink tokens: loss 8.25, perplexity 3838
window 256 + 1 sink tokens: loss 3.86, perplexity 47
window 256 + 4 sink tokens: loss 3.76, perplexity 43
full attention:            loss 3.58, perplexity 36

11.3.4 缓存缩减方法对比

表 11.3.1: 沿 \(M_{\textrm{KV}} = 2 b B L n H_{\textrm{kv}} d_h\) 三个因子的 KV 缓存缩减机制总结。
方法 缩减的因子 单序列存储数值量 是否需要训练?
共享 KV 头(GQA、MQA) (Shazeer 2019年; Ainslie 等 2023年) 头数 \(H_{\textrm{kv}} < H\) \(2 L n H_{\textrm{kv}} d_h\) 是:从零训练或增量训练(\(\sim 5\text{--}10\%\))
低秩潜在表示(MLA) (DeepSeek-AI 等 2024年) 宽度 \(2 H_{\textrm{kv}} d_h \to r\) \(\approx L n r\)(加少量旋转键) MLA 需训练;事后 SVD 基可达 \(\sim 6\times\)
带汇点的滑动窗口 (Xiao 等 2024年) 长度 \(n \to w + s\) \(2 L (w + s) H_{\textrm{kv}} d_h\) \(s \ge 1\) 时可在预训练模型上零样本生效

11.3.5 小结

KV 缓存保存过去词元经 RoPE 旋转后的键和值,使每一步解码只需投影单个新词元(n = 1),从而将生成 \(T\) 个词元的投影工作量从 \(O(T^2)\) 次词元评估降至 \(O(T)\) 次(注意力打分从 \(O(T^3)\) 降至 \(O(T^2)\)),同时产生完全一致的对数几率。在硬件屋顶线(图 11.3.3)上,推理服务分为算力受限的预填充(以高算术强度并行处理 \(n = T_p\) 个提示词元)和内存带宽受限的解码(以低算术强度每步处理 \(n = 1\) 个词元)。批处理解码将权重读取摊薄到 \(B\) 条并发序列上(式 11.3.2),使吞吐量随 \(B\) 线性扩展,直至 KV 缓存流量占据主导并在 \(\mathcal{B}_{\textrm{HBM}} / M_{\textrm{KV}}(n, 1)\) 处饱和。为了同时提升显存容量与大批量吞吐量,现代架构沿三条正交轴压缩 \(M_{\textrm{KV}} = 2 b L n H_{\textrm{kv}} d_h\)(式 11.3.1,表 11.3.1):头数(GQA/MQA)、通道宽度(低秩 KV / MLA)以及序列长度(带注意力汇点的滑动窗口)。

11.3.6 练习

  1. 70B 模型的缓存内存与批量上限。Llama 3.1 70B 有 \(L = 80\) 层、隐藏大小 \(d = 8192\)、\(H = 64\) 个查询头(\(d_h = 128\))和 \(H_{\textrm{kv}} = 8\) 个键值头,以 BF16(\(b = 2\) 字节)存储。

    1. 利用 式 11.3.1 计算单条序列在满上下文长度 \(n = 131{,}072\)(\(128\textrm{K}\))下的 KV 缓存大小 \(M_{\textrm{KV}}(n, 1)\),并与标准 MHA(\(H_{\textrm{kv}} = 64\))下的缓存开销比较。
    2. 在一台拥有 \(8 \times 80 = 640\textrm{ GB}\) 总 HBM 的 8-GPU 节点上(其中 \(140\textrm{ GB}\) 存放 BF16 模型权重),剩余的 \(500\textrm{ GB}\) 在 GQA(\(H_{\textrm{kv}} = 8\))与 MHA(\(H_{\textrm{kv}} = 64\))下分别最多能容纳多少条 \(128\textrm{K}\) 词元序列(最大批量大小 \(B\))?
  2. 批处理解码吞吐量与 KV 带宽上限。在总 HBM 带宽 \(\mathcal{B}_{\textrm{HBM}} = 24\textrm{ TB/s}\)、\(M_{\textrm{weights}} = 140\textrm{ GB}\) 的系统上,以 \(n = 32{,}768\) 的上下文长度部署 1 中的 70B 模型。

    1. 分别针对 GQA(\(H_{\textrm{kv}} = 8\))和 MHA(\(H_{\textrm{kv}} = 64\)),在批量大小 \(B \in \{1, 8, 32, 128, 512\}\) 下计算带宽上界 式 11.3.2。
    2. 两种配置分别在多大批量大小 \(B_{1/2}\) 处达到其渐近上限 \(\lim_{B \to \infty} \textrm{Throughput}(B, n) = \mathcal{B}_{\textrm{HBM}} / M_{\textrm{KV}}(n, 1)\) 的一半?
  3. 跨 \(K\) 条续写的前缀共享。假设一个批量中的 \(K = 16\) 条序列共享长度为 \(n_{\textrm{shared}} = 4096\) 词元的公共系统提示,且各自已生成 \(n_{\textrm{unique}} = 256\) 个独立词元。当共享前缀的 KV 缓存每步只需为全部 \(K\) 条序列存储并读取一次时,修改 式 11.3.2 的分母,并计算 70B GQA 模型在 \(K = 16\) 时的吞吐量加速比。

  4. INT8 / FP8 KV 缓存量化。在 forward_blocks 中使用对称逐词元 8 比特整数量化存储 GPT-2 的缓存键和值:对每个词元向量 \(\mathbf{u} \in \mathbb{R}^d\),计算缩放因子 \(s = \max_j |u_j| / 127\),量化为 \(\tilde{\mathbf{u}} = s \cdot \textrm{round}(\mathbf{u} / s)\),并在注意力中使用 \(\tilde{\mathbf{u}}\)。测量将键和值量化至 8 比特(比 FP32 缓存小 \(4\times\),比 BF16 小 \(2\times\))对比 4 比特(max / 7,分别小 \(8\times\) / \(4\times\))时,x 上 tail_loss 的变化。

  5. 注意力汇点与虚拟汇点对数几率(\(\textrm{softmax}_1\))。Xiao 等 (2024年) 与 gpt-oss(表 11.2.2)指出,注意力头需要注意力汇点是因为标准 softmax 强制注意力权重之和为 \(1\)。

    1. 将 forward_blocks 中的 softmax 替换为 \(\textrm{softmax}_1(\mathbf{s})_j = \frac{e^{s_j}}{e^{b} + \sum_{m} e^{s_m}}\)(在分母中加入非词元汇点对数几率 \(b = 5.0\),但不添加任何值向量)。
    2. 在 \(b = 5.0\) 下评估 GPT-2 上的纯滑动窗口(\(w = 256, s = 0\) 个保留汇点词元)。虚拟分母对数几率消除了多少 \(s = 0\) 时的损失尖峰?
  6. 将低秩键值重构吸收到 \(\mathbf{W}_q\) 与 \(\mathbf{W}_o\) 中。假设第 \(\ell\) 层将每个词元 \(j\) 压缩为单个潜在向量 \(\mathbf{c}_j \in \mathbb{R}^r\)(\(r \ll d_h H\)),再通过 \(\mathbf{k}_{j,m} = \mathbf{c}_j \mathbf{B}_{k,m}\) 和 \(\mathbf{v}_{j,m} = \mathbf{c}_j \mathbf{B}_{v,m}\)(\(\mathbf{B}_{k,m}, \mathbf{B}_{v,m} \in \mathbb{R}^{r \times d_h}\))重构头 \(m\) 的键和值。

    1. 证明 \(\mathbf{q}_{t,m}\mathbf{k}_{j,m}^\top = (\mathbf{x}_t \mathbf{W}_{q,m} \mathbf{B}_{k,m}^\top)\mathbf{c}_j^\top\) 且 \(\bigl(\sum_j \alpha_{t,j}^{(m)} \mathbf{v}_{j,m}\bigr)\mathbf{W}_{o,m} = \bigl(\sum_j \alpha_{t,j}^{(m)} \mathbf{c}_j\bigr)(\mathbf{B}_{v,m}\mathbf{W}_{o,m})\)。
    2. 解释为什么在解码期间将 \(\mathbf{B}_{k,m}^\top\) 吸收到 \(\mathbf{W}_{q,m}\)、将 \(\mathbf{B}_{v,m}\) 吸收到 \(\mathbf{W}_{o,m}\) 可以完全避免在 HBM 中物化完整的键 \(\mathbf{k}_{j,m}\) 或值 \(\mathbf{v}_{j,m}\),并说明为什么 DeepSeek-V2/V3 对单独的窄解耦键 \(\mathbf{k}_j^{\textrm{RoPE}}\) 施加 RoPE,而不是旋转 \(\mathbf{c}_j \mathbf{B}_{k,m}\)。
  7. 实现固定大小的流式环形缓冲区缓存。编写 init_cache 与 forward_cached 的 StreamingCache 变体,使每层只预分配 \(s + w\) 个词元槽位(在槽位 \(0 \dots s-1\) 保留前 \(s = 4\) 个汇点位置,对 \(t \ge s\) 在环形缓冲区中覆盖槽位 \(s + ((t - s) \bmod w)\)),并验证它能以恒定 \(O(s + w)\) 的缓存内存生成 2,048 个词元。gpt2 只有 1,024 个学习位置,因此可以改用带旋转位置编码的模型(pos='rope',其位置索引可无限增长),或者按照 Xiao 等 (2024年) 的做法,为 gpt2 的每个词元赋予其所在缓存槽位的位置。

讨论