Skip to content
quboliu
⚙

All About Transformer InferenceTransformer 推理详解

第 7 章 · How To Scale Your Model (在 TPU 上训练 LLaMA 3 | 在 TPU 上部署 LLaMA 3-70B 推理服务)

Performing inference on a Transformer can be very different from training. Partly this is because inference adds a new factor to consider: latency. In this section, we will go all the way from sampling a single new token from a model to efficiently scaling a large Transformer across many slices of accelerators as part of an inference engine.

本章从计算、带宽和内存出发分析 Transformer 推理,解释预填充和生成的不同瓶颈,讨论 KV 缓存如何影响延迟、吞吐量、并行设计和推理引擎。

The Basics of Transformer InferenceTransformer 推理的基础知识

So you’ve trained a Transformer, and you want to use it to generate some new sequences. At the end of the day, benchmark scores going up and loss curves going down are only proxies for whether something interesting is going to happen once the rubber hits the road!1

假设你训练好了一个 Transformer,接下来要用它生成新序列。基准测评分数提高、损失降低,只是衡量模型实际生成效果的间接指标。1

Sampling is conceptually simple. We put a sequence in and our favorite Transformer will spit out log⁡p(next tokeni∣previous tokens)\log p(\text{next token}_i \vert \text{previous tokens}), i.e. log-probabilities for all possible next tokens. We can sample from this distribution and obtain a new token. Append this token and repeat this process and we obtain a sequence of tokens which is a continuation of the prompt.

采样在概念上很简单。我们输入一个序列,我们最喜欢的 Transformer 会吐出 log⁡p(next tokeni∣previous tokens)\log p(\text{next token}_i \vert \text{previous tokens}),即所有可能的下一个 token 的对数概率。我们可以从这个分布中采样并获得一个新的 token。附加这个 token 并重复这个过程,我们就得到了一个作为提示延续的 token 序列。

naive inference

Figure: naive sampling from a Transformer. The blue logits give us a distribution over the next token that we can sample from. Note that each step re-processes the entire prefix, leading to a Θ(n2)\Theta(n^2) runtime for the algorithm.

图: 从 Transformer 进行朴素采样. 蓝色的 logits 给了我们一个关于下一个 token 的分布, 我们可以从中采样. 请注意, 每个步骤都会重新处理整个前缀, 导致算法的运行时间为 Θ(n2)\Theta(n^2).

We have just described the naive implementation of Transformer sampling, and while it works, we never do it in practice because we are re-processing the entire sequence every time we generate a token. This algorithm is O(n2)O(n^2) on the FFW and O(n3)O(n^3) on the attention mechanism to generate nn tokens!

我们刚刚描述了 Transformer 采样的朴素实现,虽然它有效,但我们在实践中从不这样做,因为我们每次生成一个 token 都会重新处理整个序列。这个算法在 FFW 上是 O(n2)O(n^2),在注意力机制上是 O(n3)O(n^3),以生成 nn 个 token!

How do we avoid this? Instead of doing the full forward pass every time, it turns out we can save some intermediate activations from each forward pass that let us avoid re-processing previous tokens. Specifically, since a given token only attends to previous tokens during dot-product attention, we can simply write each token’s key and value projections into a new data structure called a KV cache. Once we’ve saved these key/value projections for past tokens, future tokens can simply compute their qi⋅kjq_i \cdot k_j products without performing any new FLOPs on the earlier tokens. Amazing!

我们如何避免这种情况? 与其每次都进行完整的前向传播,事实证明我们可以保存每次前向传播的一些中间激活,从而避免重新处理之前的 token。具体来说,由于给定的 token 在点积注意力期间只关注之前的 token,我们可以简单地将每个 token 的键和值投影写入一个名为 KV 缓存的新数据结构中。一旦我们为过去的 token 保存了这些键/值投影,未来的 token 就可以简单地计算它们的 qi⋅kjq_i \cdot k_j 乘积,而无需对早期的 token 执行任何新的 FLOPs。太棒了!

With this in mind, inference has two key parts:

考虑到这一点,推理有两个关键部分:

  • Prefill: Given a long prompt, we process all the tokens in the prompt at the same time and save the resulting activations (specifically, the key-value projections) in a “KV cache”. We also save the logits for the last token.
  • Generation: Given a KV cache and the previous logits, we incrementally sample one token from the logits, feed that token back into the Transformer, and produce a new set of logits for the next step. We also append the KV activations for that new token to the KV cache. We repeat this until we hit a special <EOS> token or reach some maximum length limit.
  • 预填充:给定一个长提示,我们同时处理提示中的所有 token,并将结果激活 (特别是键值投影) 保存在一个**“KV 缓存”**中。我们还保存了最后一个 token 的 logits.
  • 生成:给定一个 KV 缓存和之前的 logits,我们从 logits 中增量地采样一个 token,将该 token 反馈给 Transformer,并为下一步生成一组新的 logits。我们还将该新 token 的 KV 激活附加到 KV 缓存中。我们重复这个过程,直到遇到一个特殊的 <EOS> token 或达到某个最大长度限制。

Here’s a diagram of sampling with a KV cache:

这是一个带 KV 缓存的采样图:

cached inference

Figure: diagram of efficient Transformer sampling with a KV cache. Prefill processes our prompt and saves all the per-token key-value activations in a cache. Generation takes this cache (and the last-token logits), samples a new token, and passes that new token through the model, attending to the KV cache and saving the new token’s key-value projections back to the cache. This is an O(n)O(n) algorithm in the MLP block.

图: 使用 KV 缓存的高效 Transformer 采样图. 预填充处理我们的提示并将其所有每个 token 的键值激活保存在缓存中. 生成获取此缓存 (和最后一个 token 的 logits), 采样一个新 token, 并将该新 token 通过模型, 关注 KV 缓存并将新 token 的键值投影保存回缓存. 这是 MLP 块中的一个 O(n)O(n) 算法.

By sampling with a KV cache, we’ve reduced our time complexity to generate nn tokens to O(n)O(n) on the FFW and O(n2)O(n^2) on the attention, since we never reprocess a previous token. However, many forward passes are still needed to generate a sequence — that’s what’s happening when you query Gemini or ChatGPT and the result streams back to you. Every token is (usually) a separate (but partially cached) Transformer call to a massive model.

通过使用 KV 缓存进行采样,我们将生成 nn 个 token 的时间复杂度在 FFW 上降低到 O(n)O(n),在注意力上降低到 O(n2)O(n^2),因为我们从不重新处理之前的 token。然而,生成一个序列仍然需要许多次前向传播 —— 这就是当你查询 Gemini 或 ChatGPT 并且结果流式传输给你时发生的事情。每个 token (通常) 都是对一个巨大模型的单独 (但部分缓存的) Transformer 调用。

We will soon see that prefill and generation are very different beasts — Transformer inference is two tasks in disguise! Compared to training, the KV cache is also a novel and significant source of complexity.

预填充和生成有不同的性能瓶颈,因此 Transformer 推理实际上包含两项各不相同的任务。与训练相比,推理还引入了 KV 缓存,给系统带来了新的复杂性。

What do we actually want to optimize?我们到底想优化什么?

Before we proceed further, it’s worth highlighting one aspect of inference that’s totally new: latency. While during training we only care about throughput (total tokens processed per second per chip), during inference we have to worry about how fast we’re producing tokens (both the Time To First Token (TTFT) and the per-token latency). For example:

在继续之前,值得强调一下推理中一个全新的方面:延迟。虽然在训练期间我们只关心吞吐量 (每秒每个芯片处理的总 token 数),但在推理期间,我们必须担心我们生成 token 的速度 (包括首个 token 的时间 (TTFT) 和每个 token 的延迟)。例如:

  • Offline batch inference for evals and data generation only cares about bulk cost of inference and is blind to the latency of individual samples.
  • Chat interfaces/streaming tasks need to run cheaply at scale while having low TTFT and generating tokens fast enough to exceed human reading speed.
  • Edge inference (e.g. llama.cpp on your laptop) only needs to service one user at a time at the lowest possible latency, potentially with heavy hardware constraints.
  • 用于评估和数据生成的离线批量推理只关心推理的批量成本,而不关心单个样本的延迟。
  • 聊天界面/流式任务需要在规模上廉价运行,同时具有较低的 TTFT,并且生成 token 的速度要快于人类的阅读速度。
  • 边缘推理 (例如,你笔记本电脑上的 llama.cpp) 只需要以尽可能低的延迟一次为一个用户提供服务,可能会有严格的硬件限制。

Maximizing hardware utilization is still critical and helps with cost and TTFT, but unlike training, it does not necessarily translate to better experience for individual users in all contexts. Many optimizations at the accelerator, systems and model architectural level make tradeoffs between latency, throughput, context length and even model quality.

最大化硬件利用率仍然至关重要,有助于降低成本和 TTFT,但与训练不同,它不一定在所有情况下都能转化为更好的用户体验。加速器,系统和模型架构级别的许多优化都在延迟,吞吐量,上下文长度甚至模型质量之间进行权衡。

A more granular view of the TransformerTransformer 的更精细视图

So far we’ve mostly treated a Transformer as a stack of feedforward blocks. While this is often reasonable from a FLOPs and memory standpoint, it’s not sufficient to properly model inference.2 As we saw in Part 4, the major components of a Transformer forward pass are:

到目前为止,我们主要将 Transformer 视为一堆前馈块。虽然从 FLOPs 和内存的角度来看,这通常是合理的,但它不足以正确地建模推理。2 正如我们在第 4 部分中看到的,Transformer 前向传播的主要组成部分是:

  1. A bunch of linear operations, including the MLP (WinW_{in}, WoutW_{out}) and the attention QKV projections and output projections (WQW_Q, WKW_K, WVW_V, and WOW_O). These all involve reading parameters and a batch of activations from HBM, doing some FLOPs, and writing the result back to HBM.
  2. Dot-product attention. We need to read a batch of key-value projections and a batch of query activations from HBM, do a few inner products and some softmax operations, and write the attention result back to HBM.
  3. Everything else, including applying layer norms, activation functions, token sampling, updating KV caches, and positional embeddings. These do take some FLOPs, but are dominated by, or fused into, the above.
  1. 一堆线性操作,包括 MLP (WinW_{in}, WoutW_{out}) 和注意力 QKV 投影和输出投影 (WQW_Q, WKW_K, WVW_V,和 WOW_O)。这些都涉及从 HBM 读取参数和一批激活,进行一些 FLOPs,并将结果写回 HBM.
  2. 点积注意力。我们需要从 HBM 读取一批键值投影和一批查询激活,进行一些内积和一些 softmax 操作,并将注意力结果写回 HBM.
  3. 其余操作,包括应用层归一化、激活函数、token 采样、更新 KV 缓存和位置嵌入。这些操作也会消耗一些 FLOPs,但开销相对较小,或者已融合到上述操作中。

For the next couple of sections, we’re going to look at each of these in the context of prefill and generation and ask what is likely to bottleneck our performance. Within a single accelerator, are we compute-bound or memory-bound? We want to emphasize how different the answers will be for prefill versus generation.

在接下来的几节中,我们将结合预填充和生成来看待这些操作,并询问什么可能成为我们性能的瓶颈。在单个加速器内,我们是受计算限制还是受内存限制?我们想强调一下,对于预填充和生成,答案会有多大的不同。

Linear operations: what bottlenecks us?线性操作:我们的瓶颈是什么?

All our linear operations are conceptually the same, whether they live in the MLP block or attention. Their arithmetic intensity depends on the batch size. We did this math in Section 1 but it’s worth repeating. Let’s look at a single matrix multiply of a bf16[B, D]\text{bf16[B, D]} batch by a bf16[D, F]\text{bf16[D, F]} matrix. This could be the big MLP block (WinW_\text{in} or WoutW_\text{out}) or one of the smaller attention projections (WQW_Q, WKW_K, WVW_V, WOW_O). To do this matmul, we need to load both of these arrays from HBM into the MXU, do the multiplication, then write the result back to HBM. As before, we have:

无论发生在 MLP 还是注意力中,这些线性操作的计算原理都一样。它们的算术强度取决于批次大小。第 1 章已经计算过这一点,这里再推导一次。考虑将一个 bf16[B, D]\text{bf16[B, D]} 批次与一个 bf16[D, F]\text{bf16[D, F]} 矩阵相乘。这可能是较大的 MLP 矩阵(WinW_\text{in} 或 WoutW_\text{out}),也可能是较小的注意力投影矩阵(WQW_Q、WKW_K、WVW_V 或 WOW_O)。为此要将两个数组都从 HBM 载入 MXU,相乘后再将结果写回 HBM。耗时仍然是:

Tmath=Computation FLOPsAccelerator FLOPs/s=2BDFAccelerator FLOPs/sT_\text{math} = \frac{\text{Computation FLOPs}}{\text{Accelerator FLOPs/s}} = \frac{2BDF}{\text{Accelerator FLOPs/s}} Tcomms=Communication BytesBandwidth Bytes/s=2BD+2FD+2BFBandwidth Bytes/sT_\text{comms} = \frac{\text{Communication Bytes}}{\text{Bandwidth Bytes/s}} = \frac{2BD + 2FD + 2BF}{\text{Bandwidth Bytes/s}}

A TPU or GPU can overlap these by loading as it does the compute, so to be compute-bound, we need Tmath≥TcommsT_\text{math} \geq T_\text{comms}, or:

TPU 或 GPU 可以通过在进行计算时进行加载来重叠这些操作,因此要受计算限制,我们需要 Tmath≥TcommsT_\text{math} \geq T_\text{comms},或者:

2BDF2BD+2DF+2BF≥Accelerator FLOPs/sBandwidth Bytes/s=TPU v5e1.97E+148.20E+11=240\frac{2BDF}{2BD + 2DF + 2BF} \geq \frac{\text{Accelerator FLOPs/s}}{\text{Bandwidth Bytes/s}} \underset{\text{TPU v5e}}{=} \frac{1.97E+14}{8.20E+11} = 240

where the RHS is the arithmetic intensity of our hardware. Now let’s assume DD and FF are very large compared to BB (usually our batches are at most 500 and DD and F>10kF > 10k), we can simplify the denominator by using the fact that 2BD+2DF+2BF≈2DF\small{2BD + 2DF + 2BF \approx 2DF} which gives us

其中 RHS 是我们硬件的算术强度。现在让我们假设 DD 和 FF 相对于 BB 非常大 (通常我们的批次最多为 500,而 DD 和 F>10kF > 10k),我们可以通过使用 2BD+2DF+2BF≈2DF\small{2BD + 2DF + 2BF \approx 2DF} 的事实来简化分母,这给了我们

2BDF2BD+2DF+2BF≈2BDF2DF≥Accelerator FLOPs/sBandwidth Bytes/s=TPU v5e1.97E+148.20E+11  ⟹  B≥240=Bcrit\begin{align*} \frac{2BDF}{2BD + 2DF + 2BF} \approx \frac{2BDF}{2DF} \geq \frac{\text{Accelerator FLOPs/s}}{\text{Bandwidth Bytes/s}} \\ \underset{\text{TPU v5e}}{=} \frac{1.97E+14}{8.20E+11} \implies B \geq 240 = B_{\text{crit}} \end{align*}

If we quantize our weights or use lower precision FLOPs for the matrix multiplication, this critical batch size can change. For instance, if we quantize our weights to int8 or fp8, BcritB_\text{crit} decreases by 2x. If we do our FLOPs in int8 or fp8, BcritB_\text{crit} increases by 2x. Thus if we let β=bits per param/bits per activation\beta = \text{bits per param} / \text{bits per activation} and αhbm=C/Whbm\alpha_\text{hbm} = C / W_\text{hbm}, our critical batch size is actually Bcrit=βαhbmB_\text{crit} = \beta \alpha_\text{hbm}.

如果我们对权重进行量化或对矩阵乘法使用较低精度的 FLOPs,这个临界批次大小可能会改变。例如,如果我们将权重 量化为 int8 或 fp8, BcritB_\text{crit} 会减少 2 倍。如果我们用 int8 或 fp8 进行 FLOPs, BcritB_\text{crit} 会增加 2 倍。因此,如果我们令 β=bits per param/bits per activation\beta = \text{bits per param} / \text{bits per activation}, αhbm=C/Whbm\alpha_\text{hbm} = C / W_\text{hbm},我们的临界批次大小实际上是 Bcrit=βαhbmB_\text{crit} = \beta \alpha_\text{hbm}.

During training, we’ll have a high intensity during all our matrix multiplications because we reuse the same weights over a very large batch. That high arithmetic intensity carries over to prefill, since user prompts are typically hundreds if not thousands of tokens long. As we saw before, the hardware arithmetic intensity of a TPUv5e is 240, so if a sequence longer than 240 tokens is fed into a dense model running on this hardware at bf16, we would expect to be compute-bound and all is well. Prompts shorter than this can technically be batched together to achieve higher utilization, but this is typically not necessary.

在训练期间,我们在所有矩阵乘法中都会有很高的强度,因为我们在一个非常大的批次上重复使用相同的权重。这种高算术强度会延续到预填充,因为用户提示通常有数百甚至数千个 token. 正如我们之前看到的,TPU v5e 的硬件算术强度是 240,所以如果一个长度超过 240 个 token 的序列被输入到一个在 bf16 下运行的密集模型中,我们会期望受计算限制,一切都很好。比这短的提示在技术上可以批处理在一起以实现更高的利用率,但这通常不是必需的。

However, during generation, for each request, we can only do our forward passes one token at a time since there’s a sequential dependency between steps! Thus we can only (easily) achieve good utilization by batching multiple requests together, parallelizing over the batch dimension. We’ll talk about this more later, but actually batching many concurrent requests together without affecting latency is hard. For that reason, it is much harder to saturate the hardware FLOPs with generation.

然而,在生成期间,对于每个请求,我们只能一次一个 token 地进行前向传播,因为步骤之间存在顺序依赖关系!因此,我们只能 (容易地) 通过将多个请求批处理在一起,在批处理维度上进行并行化来获得良好的利用率。我们稍后会更多地讨论这个问题,但实际上在不影响延迟的情况下将许多并发请求批处理在一起是很困难的。因此,用生成来饱和硬件 FLOPs 要困难得多。

It’s worth noting just how large this is! Generate batch size of 240 means 240 concurrent requests generating at once, and 240 separate KV caches for dense models. That means this is difficult to achieve in practice, except in some bulk inference settings. In contrast, pushing more than 240 tokens through during a prefill is pretty routine, though some care is necessary as sparsity increases.

值得注意的是这有多大! 生成批次大小为 240 意味着 240 个并发请求同时生成,以及 240 个单独的密集模型 KV 缓存。这意味着这在实践中很难实现,除了一些批量推理设置。相比之下,在预填充期间推送超过 240 个 token 是相当常规的,尽管随着稀疏性的增加需要一些小心。

Note that this exact number will differ on the kind of quantization and hardware. Accelerators often can supply more arithmetic in lower precision. For example, if we have int8 parameters but do our computation in bf16, the critical batch size drops to 120. With int8 activations and int8 params, it jumps back up to 240 since the TPUv5e can supply 400 TOPs/s of int8 x int8.

请注意,这个确切的数字会因量化和硬件的类型而异。 加速器通常可以在较低的精度下提供更多的算术运算。例如,如果我们有 int8 参数但在 bf16 中进行计算,临界批次大小会降至 120。使用 int8 激活和 int8 参数,它会跳回到 240,因为 TPU v5e 可以提供 400 TOPs/s 的 int8 x int8.

What about attention?注意力呢?

Things get more complicated when we look at the dot-product attention operation, especially since we have to account for KV caches. Let’s look at just one attention head with pure multi-headed attention. In a single Flash Attention fusion, we3:

当我们看点积注意力操作时,事情变得更加复杂,特别是由于我们必须考虑 KV 缓存。让我们只看一个具有纯多头注意力的注意力头。在单个 Flash Attention 融合中,我们3:

  1. Read the QQ activations of shape bf16[B, T, D]\text{bf16[B, T, D]} from HBM.
  2. Read the KVKV cache, which is a pair of bf16[B, S, D]\text{bf16[B, S, D]} tensors from HBM.
  3. Perform 2BSTD2BSTD FLOPs in the QKQK matmul. With Flash Attention, we don’t need to write the bf16[B, S, T]\text{bf16[B, S, T]} attention matrix back into HBM.
  4. Perform 2BSTD2BSTD in the attention AVAV matmul.
  5. Write the resulting bf16[B, T, D]\text{bf16[B, T, D]} tensor back into HBM.
  1. 从 HBM 读取形状为 bf16[B, T, D]\text{bf16[B, T, D]} 的 QQ 激活。
  2. 从 HBM 读取 KVKV 缓存,这是一对 bf16[B, S, D]\text{bf16[B, S, D]} 张量。
  3. 在 QKQK 矩阵乘法中执行 2BSTD2BSTD FLOPs。使用 Flash Attention,我们不需要将 bf16[B, S, T]\text{bf16[B, S, T]} 注意力矩阵写回 HBM.
  4. 在注意力 AVAV 矩阵乘法中执行 2BSTD2BSTD.
  5. 将结果 bf16[B, T, D]\text{bf16[B, T, D]} 张量写回 HBM.

Putting it all together, we get:

把它们放在一起,我们得到:

Multiheaded Attention Arithmetic Intensity=4BSTD4BSD+4BTD=STS+T\text{Multiheaded Attention Arithmetic Intensity} = \frac{4BSTD}{4BSD + 4BTD} = \frac{ST}{S+T}

For prefill, S=TS=T since we’re doing self-attention, so this simplifies to T2/2T=T/2T^2 / 2T = T / 2. This is great because it means the arithmetic intensity of attention during prefill is Θ(T)\Theta(T). That means it’s quite easy to be compute-bound for attention. As long as our sequence length is fairly large, we’ll be fine!

对于预填充,S=TS=T 因为我们正在进行自注意力,所以这简化为 T2/2T=T/2T^2 / 2T = T / 2。这很棒,因为这意味着预填充期间注意力的算术强度是 Θ(T)\Theta(T)。这意味着很容易受计算限制。只要我们的序列长度相当大,我们就没问题!

But since generation has a trivial sequence dim, and the BB and DD dims cancel, we can make the approximation:

但是由于生成的序列维度很小,并且 BB 和 DD 维度抵消了,我们可以做近似:

S≫T=1  ⟹  STS+T≈1S \gg T = 1 \implies \frac{ST}{S+T} \approx 1

This is bad, since it means we cannot do anything to improve the arithmetic intensity of attention during generation. We’re doing a tiny amount of FLOPs while loading a massive KV cache. So we’re basically always memory bandwidth-bound during attention!

这很糟糕,因为这意味着我们无法做任何事情来提高生成期间注意力的算术强度。我们在加载一个巨大的 KV 缓存的同时只做了少量的 FLOPs. 所以我们在注意力期间基本上总是受内存带宽限制!

Why is this, conceptually? Mainly, we’re compute-bound in linear portions of the model because the parameters (the memory bandwidth-heavy components) are reused for many batch items. However, every batch item has its own KV cache, so a bigger batch size means more KV caches. We will almost always be memory bound here unless the architecture is adjusted aggressively.

从概念上讲,这是为什么? 主要地,我们在模型的线性部分受计算限制,因为参数 (内存带宽密集型组件) 被许多批处理项重用。然而,每个批处理项都有自己的 KV 缓存,所以更大的批次大小意味着更多的 KV 缓存。我们几乎总是会在这里受内存限制,除非架构被积极地调整。

This also means you will get diminishing returns on throughput from increasing batch size once params memory becomes comparable to KV cache memory. The degree to which the diminishing returns hurt you depends on the ratio of parameter to KV cache bytes for a single sequence, i.e. roughly the ratio 2DF/SHK2DF / SHK. Since HK≈DHK\approx D, this roughly depends on the ratio of FF to SS, the sequence length. This also depends on architectural modifications that make the KV cache smaller (we’ll say more in a moment).

这也意味着一旦参数内存与 KV 缓存内存相当,你将从增加批次大小中获得递减的吞吐量回报。递减回报对你的伤害程度取决于单个序列的参数与 KV 缓存字节之比,即大约是 2DF/SHK2DF / SHK 的比率。由于 HK≈DHK\approx D,这大约取决于 FF 与 SS (序列长度) 的比率。这也取决于使 KV 缓存更小的架构修改 (我们稍后会详细说明).

Theoretical estimates for LLM latency and throughput估算 LLM 的延迟和吞吐量

From this math, we can get pretty good bounds on the step time we should aim for when optimizing. (Note: if there is one thing we want the reader to take away from this entire chapter, it’s the following). For small batch sizes during generation (which is common), we can lower-bound our per-step latency by assuming we’re memory bandwidth bound in both the attention and MLP blocks:

从这个数学中,我们可以得到相当好的优化时应该瞄准的单步耗时的界限。(注意:如果我们希望读者从本章中带走一件事,那就是以下内容). 对于生成期间的小批次大小 (这很常见),我们可以通过假设我们在注意力和 MLP 块中都受内存带宽限制来为我们的每步延迟设定下限:

Theoretical Min Step Time=Batch Size×KV Cache Size+Parameter SizeTotal Memory Bandwidth\begin{equation*} \text{Theoretical Min Step Time} = \frac{\text{Batch Size} \times \text{KV Cache Size} + \text{Parameter Size}}{\text{Total Memory Bandwidth}} \end{equation*}

Similarly, for throughput:

同样,对于吞吐量:

Theoretical Max Tokens/s=Batch Size×Total Memory BandwidthBatch Size×KV Cache Size+Parameter Size\begin{equation*} \text{Theoretical Max Tokens/s} = \frac{\text{Batch Size} \times \text{Total Memory Bandwidth}}{\text{Batch Size} \times \text{KV Cache Size} + \text{Parameter Size}} \end{equation*}

Eventually, as our batch size grows, FLOPs begin to dominate parameter loading, so in practice we have the more general equation:

最终,随着我们批次大小的增长,FLOPs 开始主导参数加载,所以在实践中我们有更通用的方程:

Theoretical Step Time (General)=Batch Size×KV Cache SizeTotal Memory Bandwidth⏟Attention (always bandwidth-bound)+max⁡(2×Batch Size×Parameter CountTotal FLOPs/s,Parameter SizeTotal Memory Bandwidth)⏟MLP (can be compute-bound)\begin{align} \tiny \text{Theoretical Step Time (General)} = \underbrace{\frac{\text{Batch Size} \times \text{KV Cache Size}}{\tiny \text{Total Memory Bandwidth}}}_{\text{Attention (always bandwidth-bound)}} + \underbrace{\max\left(\frac{2 \times \text{Batch Size} \times \text{Parameter Count}}{\text{Total FLOPs/s}}, \frac{\text{Parameter Size}}{\text{Total Memory Bandwidth}}\right)}_{\tiny \text{MLP (can be compute-bound)}} \end{align}

where the attention component (left) is never compute-bound, and thus doesn’t need a FLOPs roofline. These are fairly useful for back-of-the-envelope calculations, e.g.

其中注意力组件 (左) 从不受计算限制,因此不需要 FLOPs 屋顶线。这些对于粗略的计算相当有用,例如

Pop Quiz: Assume we want to take a generate step with a batch size of 4 tokens from a 30B parameter dense model on TPU v5e 4x4 slice in int8 with bf16 FLOPs, 8192 context and 100 kB / token KV caches. What is a reasonable lower bound on the latency of this operation? What if we wanted to sample a batch of 256 tokens?

小测验: 假设我们想在 TPU v5e 4x4 切片上,用 int8 和 bf16 FLOPs, 8192 上下文和 100 kB / token KV 缓存,从一个 30B 参数的密集模型中生成一个批次大小为 4 个 token 的步骤。这个操作的延迟的合理下限是多少?如果我们想采样一个 256 个 token 的批次呢?

Click here for the answer. 点击这里查看答案.

Answer: in int8, our parameters will use 30e9 bytes and with the given specs our KV caches will use 100e3 * 8192 = 819MB each. We have 16 chips, each with 8.2e11 bytes/s of bandwidth and 1.97e14 bf16 FLOPs/s. From the above equations, since we have a small batch size, we expect our step time to be at least (4 * 819e6 + 30e9) / (16 * 8.2e11) = 2.5 ms. At 256 tokens, we’ll be well into the compute-bound regime for our MLP blocks, so we have a step time of roughly (256 * 819e6) / (16 * 8.2e11) + (2 * 256 * 30e9) / (16 * 1.97e14) = 21ms.

答案: 在 int8 中,我们的参数将使用 30e9 字节,并且根据给定的规格,我们的 KV 缓存将每个使用 100e3 * 8192 = 819MB。我们有 16 个芯片,每个芯片有 8.2e11 字节/秒的带宽和 1.97e14 bf16 FLOPs/s。从上面的方程中,由于我们的批次大小很小,我们预计我们的单步耗时至少为 (4 * 819e6 + 30e9) / (16 * 8.2e11) = 2.5 ms。在 256 个 token 时,我们将完全进入 MLP 块的计算限制状态,所以我们的单步耗时大约是 (256 * 819e6) / (16 * 8.2e11) + (2 * 256 * 30e9) / (16 * 1.97e14) = 21ms.

As you can see, there’s a clear tradeoff between throughput and latency here. Small batches are fast but don’t utilize the hardware well. Big batches are slow but efficient. Here’s the latency-throughput Pareto frontier calculated for some older PaLM models (from the ESTI paper[1]):

正如你所看到的,这里在吞吐量和延迟之间存在明显的权衡。小批量速度快,但不能很好地利用硬件。大批量速度慢,但效率高。这是为一些较早的 PaLM 模型计算的延迟-吞吐量帕累托前沿 (来自ESTI 论文[1]):

latency cost

Figure: Pareto frontier of cost (read: throughput) versus latency for several PaLM models. Note how chip count (C) and batch size (B) moves you along the Pareto frontier, with the exception of the green dot (C:32 B:16 for PaLM 540B) where the available memory prevented the setup from supporting a good batch size and caused throughput to suffer. Note how throughput generally tends to flatten around after the batch size 240. int8 weights offers a better latency-throughput pareto optimal, but not a better max throughput.

图: 几个 PaLM 模型的成本 (读作: 吞吐量) 与延迟的帕累托前沿. 请注意芯片数量 (C) 和批次大小 (B) 如何将你沿着帕累托前沿移动, 除了绿点 (PaLM 540B 的 C:32 B:16), 在那里可用内存阻止了设置支持一个好的批次大小, 并导致吞吐量受损. 请注意吞吐量通常在批次大小 240 之后趋于平缓. int8 权重提供了更好的延迟-吞吐量帕累托最优, 但不是更好的最大吞吐量.

Not only do we trade off latency and throughput with batch size as knob, we may also prefer a larger topology to a smaller one so we can fit larger batches if we find ourselves limited by HBM. The next section explores this in more detail.

我们不仅用批次大小作为旋钮来权衡延迟和吞吐量,如果我们发现自己受 HBM 限制,我们也可能更喜欢更大的拓扑而不是更小的拓扑,以便容纳更大的批次。下一节将更详细地探讨这一点。

There are some caveats to this from a hardware standpoint. Click here for some nits. 从硬件的角度来看, 这有一些警告. 点击这里查看一些细节.

This is all quite theoretical. In practice we often don’t quite see a sharp roofline for a few reasons:

这一切都相当理论化。在实践中,我们通常不会看到一个清晰的屋顶线,原因有几个:

  • Our assumption that HBM reads will be perfectly overlapped with FLOPs is not realistic, since our compiler (XLA) is fallible.
  • For sharded models, XLA also often fails to efficiently overlap the ICI communication of our model-sharded matrix multiples with the FLOPs themselves, so we often start taking a latency hit on linears over BS=32\text{BS}=32.
  • Batch sizes larger than the theoretical roofline will still see some improvement in throughput because of imperfect overlapping, but this is a good heuristic.
  • 我们关于 HBM 读取将与 FLOPs 完美重叠的假设是不现实的,因为我们的编译器 (XLA) 是会出错的。
  • 对于分片模型,XLA 也经常无法有效地将我们模型分片矩阵乘法的 ICI 通信与 FLOPs 本身重叠,所以我们经常在 BS=32\text{BS}=32 以上的线性操作上开始出现延迟损失。
  • 大于理论屋顶线的批次大小仍然会看到一些吞吐量的改善,因为重叠不完美,但这是一个很好的启发式方法。

What about memory?内存呢?

We’ve spent some time looking at bandwidth and FLOPs, but not at memory. The memory picture looks a lot different at inference time, thanks to our new data structure, the KV cache. For this section, let’s pick a real model (LLaMA 2-13B) to demonstrate how different things look:

我们花了一些时间来看带宽和 FLOPs,但没有看内存。在推理时,内存情况看起来大不相同,这要归功于我们的新数据结构,KV 缓存。对于本节,让我们选择一个真实模型 (LLaMA 2-13B) 来演示情况有多么不同:

hyperparam
超参数
value
值
L (num_layers)
L (层数)
40
D (d_model)5,120
F (ffw_dimension)13,824
N (num_heads)
N (头数)
40
K (num_kv_heads)40
H (qkv_dim)128
V (num_embeddings)32,000

What’s using memory during inference? Well, obviously, our parameters. Counting those, we have:

在推理期间什么在使用内存?嗯,显然,是我们的参数。计算这些,我们有:

param
参数
formula
公式
size (in bytes)
大小 (字节)
FFW params
FFW 参数
d_model2 x ffw_multiplier x 3 (for SwiGLU gate, up, and down projections) x n_layers
d_model2 x ffw_multiplier x 3 (SwiGLU 的门控、升维和降维投影) x n_layers
5,120 x 5,120 x 2.7 x 3 x 40 = 8.5e9
Vocab params
词汇表参数
2 (input and output embeddings) x n_embeddings x d_model
2 (输入和输出嵌入) x n_embeddings x d_model
2 x 32,000 x 5,120 = 0.3e9
Attention params
注意力参数
[2 (q and output) x d_model x n_heads x d_qkv + 2 (for k and v) x d_model x n_kv_heads x d_qkv] x n_layers
[2 (q 和输出) x d_model x n_heads x d_qkv + 2 (k 和 v) x d_model x n_kv_heads x d_qkv] x n_layers
(2 x 5,120 x 40 x 128 + 2 x 5,120 x 40 x 128) x 40 = 4.2e9

Adding these parameters up, we get 8.5e9 + 4.2e9 + 0.3e9 = 13e9 total parameters, just as expected. As we saw in the previous sections, during training we might store our parameters in bfloat16 with an optimizer state in float32. That may use around 100GB of memory. That pales in comparison to our gradient checkpoints, which can use several TBs.

将这些参数加起来,我们得到 8.5e9 + 4.2e9 + 0.3e9 = 13e9 总参数,正如预期的那样。正如我们在前面的章节中看到的,在训练期间,我们可能会将参数存储在 bfloat16 中,优化器状态存储在 float32 中。这可能会使用大约 100GB 的内存。这与我们的梯度检查点相比相形见绌,后者可以使用几个 TB.

How is inference different? During inference, we store one copy of our parameters, let’s say in bfloat16. That uses 26GB — and in practice we can often do much better than this with quantization. There’s no optimizer state or gradients to keep track of. Because we don’t checkpoint (keep activations around for the backwards pass), our activation footprint is negligible for both prefill4 and generate. If we prefill 8k tokens, a single activation only uses around 8,192 x 5,120 x 2 bytes = 80MB of memory. Longer prefills can be broken down into many smaller forward passes, so it’s not a problem for longer contexts either. Generation uses even fewer tokens than that, so activations are negligible.

推理有什么不同? 在推理期间,我们存储一个参数的副本,比如说在 bfloat16 中。这使用了 26GB —— 在实践中,我们通常可以通过量化做得更好。没有优化器状态或梯度需要跟踪。因为我们不进行检查点 (为后向传播保留激活),我们的激活占用空间对于预填充4和生成都可以忽略不计。如果我们预填充 8k token,单个激活只使用大约 8,192 x 5,120 x 2 bytes = 80MB 的内存。更长的预填充可以分解成许多更小的前向传播,所以对于更长的上下文也不是问题。生成使用的 token 比这还少,所以激活可以忽略不计。

The main difference is the KV cache. These are the keys and value projections for all past tokens, bounded in size only by the maximum allowed sequence length. The total size for TT tokens is

主要区别在于 KV 缓存。这些是所有过去 token 的键和值投影,大小仅受最大允许序列长度的限制。TT 个 token 的总大小是

KV cache size=2⋅bytes per float⋅H⋅K⋅L⋅T\text{KV cache size} = 2 \cdot \text{bytes per float} \cdot H \cdot K \cdot L \cdot T

where HH is the dimension of each head, KK is the number of KV heads, LL is the number of layers, and the 2 comes from storing both the keys and values.

其中 HH 是每个头的维度,KK 是 KV 头的数量,LL 是层数,2 来自于同时存储键和值。

This can get big very quickly, even with modest batch size and context lengths. For LLaMA-13B, a KV cache for a single 8192 sequence at bf16 is

这会很快变得很大,即使批次大小和上下文长度适中。对于 LLaMA-13B,一个 8192 序列在 bf16 下的 KV 缓存是

8192 (T)×40 (K)×128 (H)×40 (L)×2 (bytes)×2=6.7GB8192\ (T) \times 40\ (K) \times 128\ (H) \times 40\ (L) \times 2\ (\text{bytes}) \times 2 = 6.7 \text{GB}

Just 4 of these exceed the memory usage of our parameters! To be clear, LLaMA 2 was not optimized for KV cache size at longer contexts (it isn’t always this bad, since usually KK is much smaller, as in LLaMA-3), but this is still illustrative. We cannot neglect these in memory or latency estimates.

仅仅 4 个这样的缓存就超过了我们参数的内存使用量! 需要明确的是,LLaMA 2 在较长上下文下的 KV 缓存大小方面没有进行优化 (情况并不总是这么糟,因为通常 KK 要小得多,就像 LLaMA-3 中那样),但这仍然具有说明性。我们在内存或延迟估计中不能忽略这些。

Modeling throughput and latency for LLaMA 2-13B为 LLaMA 2-13B 建模吞吐量和延迟

Let’s see what happens if we try to perform generation perfectly efficiently at different batch sizes on 8xTPU v5es, up to the critical batch size (240) derived earlier for maximum theoretical throughput.

让我们看看如果我们尝试在 8xTPU v5es 上以不同的批次大小完美高效地执行生成,直到达到前面为最大理论吞吐量推导出的临界批次大小 (240),会发生什么。

Batch Size
批次大小
18163264240
KV Cache Memory (GiB)
KV 缓存内存 (GiB)
6.753.6107.2214.4428.81608
Total Memory (GiB)
总内存 (GiB)
32.779.6133.2240.4454.81634
Theoretical Step Time (ms)
理论单步耗时 (ms)
4.9812.1320.3036.6569.33249.09
Theoretical Throughput (tokens/s)
理论吞吐量 (token/秒)
200.61659.30787.99873.21923.13963.53

8x TPU v5es gives us 128GiB of HBM, 6.5TiB/s of HBM bandwidth (0.82TiB/s each) and 1600TF/s of compute.

8x TPU v5es 给了我们 128GiB 的 HBM, 6.5TiB/s 的 HBM 带宽 (每个 0.82TiB/s) 和 1600TF/s 的计算能力。

For this model, increasing the batch size does give us better throughput, but we suffer rapidly diminishing returns. We OOM beyond batch size 16, and need an order of magnitude more memory to go near 240. A bigger topology can improve the latency, but we’ve hit a wall on the per chip throughput.

对于这个模型,增加批次大小确实能给我们带来更好的吞吐量,但我们很快就会遇到收益递减。我们在批次大小超过 16 时就会 OOM,并且需要数量级更多的内存才能接近 240。更大的拓扑可以改善延迟,但我们在每个芯片的吞吐量上遇到了瓶颈。

Let’s say we keep the total number of params the same, but magically make the KV cache 5x smaller (say, with 1:5 GMQA, which means we have 8 KV heads shared over the 40 Q heads — see next section for more details).

假设我们保持总参数数量不变,但神奇地将 KV 缓存缩小 5 倍 (比如说,使用 1:5 的 GMQA,这意味着我们有 8 个 KV 头在 40 个 Q 头上共享 —— 更多细节见下一节).

Batch Size
批次大小
18163264240
KV Cache Memory (GiB)
KV 缓存内存 (GiB)
1.3410.7221.4442.8885.76321.6
Total Memory (GiB)
总内存 (GiB)
27.3436.7247.4468.88111.76347.6
Theoretical Step Time (ms)
理论单步耗时 (ms)
4.175.607.2310.5017.0452.99
Theoretical Throughput (tokens/s)
理论吞吐量 (token/秒)
239.941,429.192,212.483,047.623,756.624,529.34

With a smaller KV cache, we still have diminishing returns, but the theoretical throughput per chip continues to scale up to batch size 240. We can fit a much bigger batch of 64, and latency is also consistently better at all batch sizes. The latency, maximum throughput, and maximum batch size all improve dramatically! In fact, later LLaMA generations used this exact optimization — LLaMA-3 8B has 32 query heads and 8 KV heads (source).

使用更小的 KV 缓存,我们仍然有递减的回报,但理论上每个芯片的吞吐量会持续扩展到批次大小 240。我们可以容纳更大的批量 64,并且在所有批次大小下延迟也始终更好。延迟,最大吞吐量和最大批次大小都得到了显著改善!事实上,后来的 LLaMA 代使用了这个确切的优化 —— LLaMA-3 8B 有 32 个查询头和 8 个 KV 头 (来源).

Tricks for Improving Generation Throughput and Latency提高生成吞吐量和延迟的技巧

Since the original Attention is All You Need paper, many techniques have been developed to make the model more efficient, often targeting the KV cache specifically. Generally speaking, a smaller KV cache makes it easier to increase batch size and context length of the generation step without hurting latency, and makes life easier for the systems surrounding the Transformer (like request caching). Ignoring effects on quality, we may see:

自最初的 Attention is All You Need 论文以来,已经开发了许多技术来使模型更高效,通常专门针对 KV 缓存。一般来说,更小的 KV 缓存使得在不影响延迟的情况下更容易增加生成步骤的批次大小和上下文长度,并使 Transformer 周围的系统 (如请求缓存) 的生活更轻松。忽略对质量的影响,我们可能会看到:

Grouped multi-query attention (aka GMQA, GQA): We can reduce the number of KV heads, and share them with many Q heads in the attention mechanism. In the extreme case, it is possible to share a single KV head across all Q heads. This reduces the KV cache by a factor of the Q:KV ratio over pure MHA, and it has been observed that the performance of models is relatively insensitive to this change.

分组查询注意力 (又名 GMQA, GQA): 我们可以减少 KV 头的数量,并在注意力机制中与许多 Q 头共享它们。在极端情况下,可以在所有 Q 头之间共享单个 KV 头。这将 KV 缓存减少了 Q:KV 比率的倍数,相对于纯 MHA,并且已经观察到模型的性能对这种变化相对不敏感。

gmqa

This also effectively increases the arithmetic intensity of the attention computation (see Question 4 in Section 4).

这实际上也增加了注意力计算的算术强度 (参见第 4 节中的问题 4).

Mixing in some local attention layers: Local attention caps the context to a small to moderately sized max length. At training time and prefill time, this involves masking the attention matrix to a diagonal strip instead of a triangle. This effectively caps the size of the max length of the KV cache for the local layers. By mixing in some local layers into the model with some global layers, the KV cache is greatly reduced in size at contexts longer than the local window.

混合一些局部注意力层: 局部注意力将上下文限制在一个小到中等大小的最大长度。在训练时间和预填充时间,这涉及到将注意力矩阵掩码为一个对角条带,而不是一个三角形。这有效地限制了局部层的 KV 缓存的最大长度。通过将一些局部层与一些全局层混合到模型中,在上下文长度超过局部窗口时,KV 缓存的大小会大大减小。

Sharing KVs across layers: The model can learn to share the same KV caches across layers in some pattern. Whilst this does reduce the KV cache size, and provide benefits in increasing batch size, caching, offline storage, etc., shared KV caches may need to be read from HBM multiple times, so it does not necessarily improve the step time.

跨层共享 KV: 模型可以学习以某种模式跨层共享相同的 KV 缓存。虽然这确实减小了 KV 缓存的大小,并在增加批次大小,缓存,离线存储等方面提供了好处,但共享的 KV 缓存可能需要多次从 HBM 读取,因此它不一定能改善单步耗时。

kv sharing

Left: Multiple layers of pure global attention. Right: An example of some global/local interleaving pattern with sharing with adjacent layers. Source: Character.ai blog.

左: 多层纯全局注意力。右: 一些全局/局部交错模式的示例,与相邻层共享。来源:Character.ai 博客.

Quantization: Inference is usually less sensitive to the precision of parameters and KVs. By quantizing the parameters and KV cache (e.g. to int8, int4, fp8 etc.), we can save on memory bandwidth on both, decrease the batch size required to reach the compute roofline and save memory to run at bigger batch sizes. Quantization has the added advantage that even if the model was not trained with quantization it can often be applied post training.

量化: 推理通常对参数和 KV 的精度不太敏感。通过对参数和 KV 缓存进行量化 (例如,int8, int4, fp8 等),我们可以节省两者的内存带宽,减少达到计算屋顶线所需的批次大小,并节省内存以在更大的批次大小下运行。量化还有一个额外的好处,即即使模型没有用量化进行训练,也通常可以在训练后应用。

Using ragged HBM reads and Paged Attention: We allocated 8k of context for each KV cache in the calculations above but it is often not necessary to read the entire KV cache from memory — requests have a wide range of length distributions and don’t use the max context of the model, so we can often implement kernels (e.g. Flash Attention variants) that only read the non-padding part of the KV cache.

使用不规则 HBM 读取和分页注意力: 我们在上面的计算中为每个 KV 缓存分配了 8k 的上下文,但通常不需要从内存中读取整个 KV 缓存 —— 请求具有广泛的长度分布,并且不使用模型的最大上下文,因此我们通常可以实现仅读取 KV 缓存的非填充部分的内核 (例如,Flash Attention 变体).

Paged Attention[2] is a refinement upon this that stores KV caches in OS-style page tables and mostly avoids padding the KV caches altogether. This adds a lot of complexity but means every batch only uses as much memory as it needs. This is a runtime optimization, so again it is indifferent to architecture.

分页注意力[2] 是对此的改进,它将 KV 缓存存储在操作系统风格的页表中,并且基本上完全避免了填充 KV 缓存。这增加了很多复杂性,但意味着每个批次只使用它需要的内存。这是一个运行时优化,因此它同样与架构无关。

paged attention

Figure: during generation, a single token (“forth”) attends to multiple KV cache blocks/pages. By paging the KV cache, we avoid loading or storing more memory than we need to. Taken from the PagedAttention paper.

图: 在生成期间, 单个 token(“forth”)关注多个 KV 缓存块/页. 通过对 KV 缓存进行分页, 我们避免了加载或存储比我们需要更多的内存. 摘自 PagedAttention 论文.

Distributing Inference Over Multiple Accelerators在多个加速器上分布推理

So far we’ve handwaved how we’re scaling beyond a single chip. Following Section 5, let’s explore the different strategies available to us and their tradeoffs. As always, we will look at prefill and generation separately.

到目前为止,我们一直在含糊地讨论如何扩展到单个芯片之外。遵循第 5 节,让我们探讨可用的不同策略及其权衡。与往常一样,我们将分别看待预填充和生成。

Prefill预填充

From a roofline standpoint, prefill is almost identical to training and almost all the same techniques and tradeoffs apply — model (Megatron) parallelism, sequence sharding (for sufficiently long context), pipelining, even FSDP are all viable! You just have to keep the KVs kicking around so you can do generation later. As in training, increasing the number of chips gives us access to more FLOPs/s (for potentially lower TTFT), but adds communication overhead (potentially reducing throughput per chip).

从屋顶线的角度来看,预填充几乎与训练相同,几乎所有相同的技术和权衡都适用 —— 模型 (Megatron) 并行,序列分片 (对于足够长的上下文),流水线,甚至 FSDP 都是可行的!你只需要保留 KV,以便稍后可以进行生成。与训练一样,增加芯片数量可以让我们获得更多的 FLOPs/s (可能降低 TTFT),但会增加通信开销 (可能降低每个芯片的吞吐量).

The general rule for sharding prefill: here’s a general set of rules for prefill. We’ll assume we’re doing prefill on a single sequence only (no batch dimension):

分片预填充的一般规则: 这是预填充的一般规则集。我们假设我们只在一个序列上进行预填充 (没有批处理维度):

  1. Model sharding: We typically do some amount of model parallelism first, up to the point we become ICI-bound. As we saw in Section 5, this is around F/2200F / 2200 for 1 axis (usually around 4-8 way sharding).
  2. Sequence parallelism: Beyond this, we do sequence parallelism (like data parallelism but sharding across the sequence dimension). While sequence parallelism introduces some extra communication in attention, it is typically fairly small at longer contexts. As with training, we can overlap the communication and computation (using collective matmuls for Megatron and ring attention respectively).
  1. 模型分片: 我们通常首先进行一定量的模型并行,直到我们受 ICI 限制。正如我们在第 5 节中看到的,对于 1 个轴,这大约是 F/2200F / 2200 (通常是 4-8 路分片).
  2. 序列并行: 除此之外,我们进行序列并行 (就像数据并行,但在序列维度上进行分片)。虽然序列并行在注意力中引入了一些额外的通信,但在较长的上下文中,它通常相当小。与训练一样,我们可以重叠通信和计算 (分别使用 Megatron 的集合矩阵乘法和环形注意力).

Generation生成

Generation is a more complicated beast than prefill. For one thing, it is harder to get a large batch size because we need to batch many requests together. Latency targets are lower. Together, these mean we are typically more memory-bound and more sensitive to communication overhead, which restrict our sharding strategies:

生成比预填充更复杂。一方面,获得大的批次大小更难,因为我们需要将许多请求批处理在一起。延迟目标更低。总之,这意味着我们通常更受内存限制,对通信开销更敏感,这限制了我们的分片策略:

  1. FSDP is impossible: since we are memory-bound in loading our parameters and KV caches from HBM to the MXU, we do not want to move them via ICI which is orders of magnitudes slower than HBM. We want to move activations rather than weights. This means methods similar to FSDP are usually completely unviable for generation.5
  1. FSDP 是不可能的: 由于我们在从 HBM 加载参数和 KV 缓存到 MXU 时受内存限制,我们不希望通过比 HBM 慢几个数量级的 ICI 来移动它们。我们希望移动激活而不是权重。 这意味着类似于 FSDP 的方法通常对于生成是完全不可行的。5
  1. There is no reason to do data parallelism: pure data parallelism is unhelpful because it replicates our parameters and doesn’t help us load parameters faster. You’re better off spinning up multiple copies of the model instead.6
  1. 没有理由进行数据并行: 纯数据并行没有帮助,因为它复制了我们的参数,并且无助于我们更快地加载参数。你最好启动多个模型的副本。6
  1. No sequence = no sequence sharding. Good luck sequence sharding.
  1. 没有序列 = 没有序列分片。 祝你好运,序列分片。

This mostly leaves us with variants of model sharding for dense model generation. As with prefill, the simplest thing we can do is simple model parallelism (with activations fully replicated, weights fully sharded over hidden dimension for the MLP) up to 4-8 ways when we become ICI bound. However, since we are often memory bandwidth bound, we can actually go beyond this limit to improve latency!

这主要给我们留下了密集模型生成的模型分片变体。与预填充一样,我们可以做的最简单的事情是简单的模型并行 (激活完全复制,权重在 MLP 的隐藏维度上完全分片),直到我们受 ICI 限制的 4-8 路。然而,由于我们经常受内存带宽限制,我们实际上可以超越这个限制来提高延迟!

Note on ICI bounds for generation: during training we want to be compute-bound, so our rooflines look at when our ICI comms take longer than our FLOPs. However, during generation, if we’re memory bandwidth bound by parameter loading, we can increase model sharding beyond this point and improve latency at a minimal throughput cost (in terms of tokens/sec/chip). More model sharding gives us more HBM to load our weights over, and our FLOPs don’t matter.7 Let’s look at how much model parallelism we can do before it becomes the bottleneck.

关于生成 ICI 限制的说明: 在训练期间,我们希望受计算限制,所以我们的屋顶线着眼于我们的 ICI 通信何时比我们的 FLOPs 花费更长的时间。然而,在生成期间,如果我们受参数加载的内存带宽限制,我们可以将模型分片增加到超过这个点,并以最小的吞吐量成本 (以 token/秒/芯片为单位) 提高延迟。更多的模型分片给了我们更多的 HBM 来加载我们的权重,我们的 FLOPs 并不重要。7 让我们看看在它成为瓶颈之前我们可以做多少模型并行。

THBM comms=2DFY⋅WhbmTICI comms=2BDWici\begin{align*}T_\text{HBM comms} = \frac{2DF}{Y \cdot W_\text{hbm}} && T_\text{ICI comms} = \frac{2BD}{W_\text{ici}}\end{align*} TICI comms>THBM comms→WhbmWici>FY⋅B→Y>F/(B⋅β)T_\text{ICI comms} > T_\text{HBM comms} \rightarrow \frac{W_\text{hbm}}{W_\text{ici}} > \frac{F}{Y \cdot B} \rightarrow Y > F / (B \cdot \beta)

where β=Whbm/Wici\beta = W_\text{hbm} / W_\text{ici}. This number is usually around 8 for TPU v5e and TPU v6e. That means e.g. if FF is 16,384 and BB is 32, we can in theory do model parallelism up to 16384 / (32 * 8) = 64 ways without a meaningful hit in throughput. This assumes we can fully shard our KV caches 64-ways which is difficult: we discuss this below.

其中 β=Whbm/Wici\beta = W_\text{hbm} / W_\text{ici}。对于 TPU v5e 和 TPU v6e,这个数字通常在 8 左右。这意味着例如,如果 FF 是 16,384, BB 是 32,我们理论上可以进行模型并行,直到 16384 / (32 * 8) = 64 路,而不会对吞吐量产生有意义的影响。这假设我们可以完全将我们的 KV 缓存分片 64 路,这很困难:我们将在下面讨论这个问题。

For the attention layer, we also model shard attention WQW_Q and WOW_O over heads Megatron style. The KV weights are quite small, and replicating them is often cheaper than sharding beyond KK-way sharding.

对于注意力层,我们也对注意力 WQW_Q 和 WOW_O 在头 Megatron 风格上进行模型分片。KV 权重相当小,复制它们通常比分片超过 KK 路分片更便宜。

Sharding the KV cache分片 KV 缓存

We also have an additional data structure that needs to be sharded — the KV cache. Again, we almost always prefer to avoid replicating the cache, since it is the primary source of attention latency. To do this, we first Megatron-shard the KVs along the head dimension. This is limited to KK-way sharding, so for models with a small number of heads, we shard the head dimension as much as possible and then shard along the batch dimension, i.e. KV[2,BZ,S,KY,H]\text{KV}[2, B_Z, S, K_Y, H]. This means the KV cache is completely distributed.

我们还有一个需要分片的新数据结构 —— KV 缓存。 同样,我们几乎总是倾向于避免复制缓存,因为它是注意力延迟的主要来源。为此,我们首先在头维度上对 KV 进行 Megatron 分片。这仅限于 KK 路分片,因此对于头数较少的模型,我们尽可能多地对头维度进行分片,然后在批处理维度上进行分片,即 KV[2,BZ,S,KY,H]\text{KV}[2, B_Z, S, K_Y, H]。这意味着 KV 缓存是完全分布式的。

esta figure

Figure: comparison of the attention mechanism with (a) Multi head attention with pure model sharding and (b) Multiquery attention with batch sharding of the KV cache. Notice how we need two extra AllToAlls to shift the activations from model sharding to batch sharding, so they can act on the KV caches.

图: (a) 具有纯模型分片的多头注意力和 (b) 具有 KV 缓存批处理分片的多查询注意力的注意力机制比较. 请注意, 我们需要两个额外的 AllToAll 来将激活从模型分片转移到批处理分片, 以便它们可以作用于 KV 缓存.

The cost of this is two AllToAlls every attention layer — one to shift the Q activations to the batch sharding so we can compute attention with batch sharding, and one to shift the batch sharded attention output back to pure model sharded.

这样做的代价是每个注意力层需要两次 AllToAll —— 一次是将 Q 激活转移到批处理分片,以便我们可以用批处理分片计算注意力,另一次是将批处理分片的注意力输出转移回纯模型分片。

Here's the full algorithm! 这是完整的算法!

Here we’ll write out the full attention algorithm with model parallelism over both YY and ZZ. I apologize for using KK for both the key tensor and the KV head dimension. Let M=N/KM=N/K.

在这里,我们将写出在 YY 和 ZZ 上都进行模型并行的完整注意力算法。我为同时使用 KK 表示键张量和 KV 头维度而道歉。设 M=N/KM=N/K.

  1. X[B, D] = … (existing activations, unsharded from previous layer)
  2. K[BZ, S, KY, H], V[BZ, S, KY, H] = … (existing KV cache, batch sharded)
  3. Q[B, NYZ, H] = X[B, D] * WQ[D, NYZ, H]
  4. Q[BZ, NY, H] = AllToAllZ->B(Q[B, NYZ, H])
  5. Q[BZ, KY, M, H] = Reshape(Q[BZ, NY, H])
  6. O[BZ, S, KY, M] = Q[BZ, KY, M, H] *H K[BZ, S, KY, H]
  7. O[BZ, S, KY, M] = SoftmaxS(O[BZ, S, KY, M])
  8. O[BZ, KY, M, H] = O[BZ, S, KY, M] *S V[BZ, S, KY, H]
  9. O[B, KY, MZ, H] = AllToAllZ->M(O[BZ, KY, M, H])
  10. O[B, NYZ, H] = Reshape(O[B, KY, MZ, H])
  11. X[B, D] {UYZ} = WO[NYZ, H, D] *N,H O[B, NYZ, H]
  12. X[B, D] = AllReduce(X[B, D] { UYZ})
  1. X[B, D] = … (上一层未分片的激活值)
  2. K[BZ, S, KY, H], V[BZ, S, KY, H] = … (已存在且沿批次分片的 KV 缓存)
  3. Q[B, NYZ, H] = X[B, D] * WQ[D, NYZ, H]
  4. Q[BZ, NY, H] = AllToAllZ->B(Q[B, NYZ, H])
  5. Q[BZ, KY, M, H] = Reshape(Q[BZ, NY, H])
  6. O[BZ, S, KY, M] = Q[BZ, KY, M, H] *H K[BZ, S, KY, H]
  7. O[BZ, S, KY, M] = SoftmaxS(O[BZ, S, KY, M])
  8. O[BZ, KY, M, H] = O[BZ, S, KY, M] *S V[BZ, S, KY, H]
  9. O[B, KY, MZ, H] = AllToAllZ->M(O[BZ, KY, M, H])
  10. O[B, NYZ, H] = Reshape(O[B, KY, MZ, H])
  11. X[B, D] {UYZ} = WO[NYZ, H, D] *N,H O[B, NYZ, H]
  12. X[B, D] = AllReduce(X[B, D] { UYZ})

This is pretty complicated but you can see generally how it works. The new comms are modestly expensive since they operate on our small activations, while in return we save a huge amount of memory bandwidth loading the KVs (which are stationary).

这一流程比较复杂,但可以看到:新增的通信只涉及较小的激活值,开销有限。KV 缓存则留在原处,因而节省了大量读取 KV 的内存带宽。

  • Sequence sharding: If the batch size is too small, or the context is long, we can sequence shard the KV cache. Again, we pay a collective cost in accumulating the attention across shards here. First we need to AllGather the Q activations, and then accumulate the KVs in a similar fashion to Flash Attention.
  • 序列分片: 如果批次大小太小,或者上下文很长,我们可以对 KV 缓存进行序列分片。同样,我们在这里为跨分片累积注意力付出了集体成本。首先我们需要对 Q 激活进行 AllGather,然后以类似于 Flash Attention 的方式累积 KV.

Designing an Effective Inference Engine设计一个有效的推理引擎

So far we’ve looked at how to optimize and shard the individual prefill and generate operations efficiently in isolation. To actually use them effectively, we need to design an inference engine which can feed these two operations at a point of our choosing on the latency/throughput Pareto frontier.

到目前为止,我们已经研究了如何独立地优化和分片单个预填充和生成操作。为了有效地使用它们,我们需要设计一个推理引擎,它可以将这两个操作馈送到我们选择的延迟/吞吐量帕累托前沿上的一个点。

The simplest method is simply to run a batch of prefill, then a batch of generations:

最简单的方法是简单地运行一批预填充,然后运行一批生成:

batched prefill

Figure: in the simplest setup, requests are aggregated, and the server alternates between running a batch of prefills and calling the generate function until completion for all sequences.

图: 在最简单的设置中, 请求被聚合, 服务器在运行一批预填充和调用生成函数之间交替, 直到所有序列完成.

This is easy to implement and is the first inference setup in most codebases, but it has multiple drawbacks:

这很容易实现,并且是大多数代码库中的第一个推理设置,但它有多个缺点:

  1. Latency is terrible. We couple the prefill and generate batch size. Time to first token (TTFT) is terrible at big prefill batch sizes — you need to finish all prefills before any users can see any tokens. Generate throughput is terrible at small batch sizes.
  2. We block shorter generations on longer ones. Many sequences will finish before others, leaving empty batch slots during generation, hurting generate throughput further. The problem exacerbates as batch size and generation length increases.
  3. Prefills are padded. Prefills are padded to the longest sequence and we waste a lot of compute. There are solutions for this, but historically XLA made it quite difficult to skip these FLOPs. Again this becomes worse the bigger the batch size and prefill sequence length.
  4. We’re forced to share a sharding between prefill and generation. Both prefill and generate live on the same slice, which means we use the same topology and shardings (unless you keep two copies of the weights) for both and is generally unhelpful for performance e.g. generate wants a lot more model sharding.
  1. 延迟很糟糕。 我们将预填充和生成批次大小耦合在一起。在大的预填充批次大小下,首个 token 的时间 (TTFT) 很糟糕 —— 你需要完成所有预填充,然后用户才能看到任何 token。在小的批次大小下,生成吞吐量很糟糕。
  2. 我们用较长的生成阻塞了较短的生成。 许多序列会比其他序列更早完成,在生成期间留下空的批处理槽,进一步损害生成吞吐量。随着批次大小和生成长度的增加,问题会加剧。
  3. 预填充被填充。 预填充被填充到最长的序列,我们浪费了大量的计算。对此有解决方案,但历史上 XLA 使得跳过这些 FLOPs 相当困难。同样,批次大小和预填充序列长度越大,情况就越糟。
  4. 我们被迫在预填充和生成之间共享一个分片。 预填充和生成都存在于同一个切片上,这意味着我们对两者使用相同的拓扑和分片 (除非你保留两份权重),这通常对性能没有帮助,例如,生成需要更多的模型分片。

Therefore this method is only recommended for edge applications (which usually only cares about serving a single user and using hardware with less FLOPs/byte) and rapid iteration early in the lifecycle of a Transformer codebase (due to its simplicity).

因此,这种方法只推荐用于边缘应用 (通常只关心为一个用户提供服务并使用具有较少 FLOPs/字节的硬件) 和 Transformer 代码库生命周期早期的快速迭代 (由于其简单性).

A slightly better approach involves performing prefill at batch size 1 (where it is compute-bound but has reasonable latency) but batch multiple requests together during generation:

一个稍微好一点的方法是在批次大小为 1 时执行预填充 (此时它受计算限制但具有合理的延迟),但在生成期间将多个请求批处理在一起:

interleaving

This will avoid wasted TTFT from batched prefill while keeping generation throughput high. We call this an interleaved configuration, since we “interleave” prefill and generation steps. This is very powerful for bulk generation applications like evaluations where throughput is the main goal. The orchestrator can be configured to prioritise prefill the moment any generation slots open up, ensuring high utilisation even for very large generation batch sizes. We can also avoid padding our prefill to the maximum length, since it isn’t batched with another request.

这将避免批量预填充造成的 TTFT 浪费,同时保持较高的生成吞吐量。我们称之为交错配置,因为我们“交错”了预填充和生成步骤。这对于批量生成应用 (如评估) 非常强大,在这些应用中,吞吐量是主要目标。编排器可以配置为在任何生成槽位空闲时优先进行预填充,即使对于非常大的生成批次大小,也能确保高利用率。我们还可以避免将预填充填充到最大长度,因为它没有与其他请求批处理。

The main disadvantage is that when the server is performing a prefill, the generation of all other requests pauses since all the compute resources will be consumed by the prefill. User A whose response is busy decoding will be blocked by user B whose prefill is occurring. This means even though TTFT has improved, the token generation will be jittery and slow on average, which is not a good user experience for many applications — other user’s prefills are on the critical path of the overall latency of a request.

主要缺点是,当服务器执行预填充时,所有其他请求的生成都会暂停,因为所有计算资源都将被预填充消耗。正在解码其响应的用户 A 将被正在进行预填充的用户 B 阻塞。这意味着即使 TTFT 得到了改善,token 生成平均也会抖动和缓慢,这对于许多应用来说不是一个好的用户体验 —— 其他用户的预填充处于请求总延迟的关键路径上。

To get around this, we separate decode and prefill. While Transformer inference can be done on one server, it is often better from a latency standpoint to execute the two different tasks on two sets of TPUs/GPUs. Prefill servers generate KV caches that get sent across the network to the generate servers, which batch multiple caches together and generate tokens for each of them. We call this “disaggregated” serving.

为了解决这个问题,我们将解码和预填充分开。虽然 Transformer 推理可以在一台服务器上完成,但从延迟的角度来看,在两组 TPU/GPU 上执行这两个不同的任务通常更好。预填充服务器生成 KV 缓存,这些缓存通过网络发送到生成服务器,生成服务器将多个缓存批处理在一起并为每个缓存生成 token。我们称之为**“分离式”**服务。

disaggregation

This provides a few advantages:

这提供了一些优势:

  1. Low latency at scale: A user’s request never blocks on another user’s, except if there is insufficient prefill capacity. The request should be immediately prefilled, then sent to the generation server, then immediately slotted into the generation buffer. If we expect many concurrent requests to come in, we can scale the number of prefill servers independently from the number of generate servers so users are not left in the prefill queue for an extended period of time.
  1. 大规模低延迟:用户的请求永远不会阻塞在另一个用户的请求上,除非预填充容量不足。请求应该立即被预填充,然后发送到生成服务器,然后立即插入到生成缓冲区中。如果我们预计会有许多并发请求进来,我们可以独立于生成服务器的数量来扩展预填充服务器的数量,这样用户就不会长时间停留在预填充队列中。
  1. Specialization: Quite often, the latency-optimal parameter sharding strategy/hardware topology for prefill and generate is quite different (for instance, more model parallelism is useful for generate but not prefill). Constraining the two operations to use the same sharding hurts the performance of both, and having two sets of weights uses memory. Also, by moving prefill onto its own server, it doesn’t need to hold any KV caches except the one it’s currently processing. That means we have a lot more memory free for history caching (see the next section) or optimizing prefill latency.
  1. 专业化: 通常,预填充和生成的延迟最优参数分片策略/硬件拓扑非常不同 (例如,更多的模型并行对生成有用,但对预填充没用)。将这两个操作限制为使用相同的分片会损害两者的性能,并且拥有两套权重会占用内存。此外,通过将预填充移动到自己的服务器上,它不需要持有任何 KV 缓存,除了它当前正在处理的那个。这意味着我们有更多的内存可用于历史缓存 (见下一节) 或优化预填充延迟。

One downside is that the KV cache now needs to be shifted across the network. This is typically acceptable but again provides a motivation for reducing KV cache size.

一个缺点是 KV 缓存现在需要在网络上传输。这通常是可以接受的,但再次为减小 KV 缓存大小提供了动力。

Continuous batching连续批处理

Problem (2) above motivates the concept of continuous batching. We optimize and compile:

上面的问题 (2) 激发了连续批处理的概念。我们优化并编译:

  • A prefill function that handles variable context lengths and inserts results into a KV buffer with some maximum batch size and context length/number of pages.
  • A generate function which takes in the KV cache, and performs the generation step for all currently active requests.
  • 一个预填充函数,处理不同长度的上下文,将结果写入 KV 缓冲区。缓冲区设定最大批次大小与最大上下文长度或页数。
  • 一个生成函数,它接受 KV 缓存,并为所有当前活动的请求执行生成步骤。

We then combine these functions with an orchestrator which queues the incoming requests, calls prefill and generate depending on the available generate slots, handles history caching (see next section) and streams the tokens out.

然后,我们将这些函数与一个编排器结合起来,该编排器对传入的请求进行排队,根据可用的生成槽位调用预填充和生成,处理历史缓存 (见下一节) 并流式传输 token.

continuous batching

Prefix caching前缀缓存

Since prefill is expensive and compute-bound (giving us less headroom), one of the best ways to reduce its cost is to do less of it. Because LLMs are autoregressive, the queries [“I”, “like”, “dogs”] and [“I”, “like”, “cats”] produce KV caches that are identical in the first two tokens. What this means is that, in principle, if we compute the “I like dogs” cache first and then the “I like cats” cache, we only need to do 1 / 3 of the compute. We can save most of the work by reusing the cache. This is particularly powerful in a few specific cases:

由于预填充成本高昂且受计算限制 (给了我们更少的余地),减少其成本的最佳方法之一是减少预填充的次数。因为 LLM 是自回归的,查询 [“我”, “喜欢”, “狗”] 和 [“我”, “喜欢”, “猫”] 产生的 KV 缓存的前两个 token 是相同的。这意味着,原则上,如果我们先计算“我喜欢狗”的缓存,然后再计算“我喜欢猫”的缓存,我们只需要进行 1/3 的计算。我们可以通过重用缓存来节省大部分工作。这在一些特定情况下特别强大:

  1. Chatbots: most chatbot conversations involve a back-and-forth dialog that strictly appends to itself. This means if we can save the KV caches from each dialog turn, we can skip computation for all but the newest tokens.
  2. Few-shot prompting: if we have any kind of few-shot prompt, this can be saved and reused for free. System instructions often have this form as well.
  1. 聊天机器人:大多数聊天机器人对话都涉及严格附加到自身的来回对话。这意味着如果我们能保存每次对话轮次的 KV 缓存,我们就可以跳过除最新 token 之外的所有计算。
  2. 少样本提示:如果我们有任何类型的少样本提示,这可以被保存和重用。系统指令通常也具有这种形式。

The only reason this is hard to do is memory constraints. As we’ve seen, KV caches are big (often many GB), and for caching to be useful we need to keep them around until a follow-up query arrives. Typically, any unused HBM on the prefill servers can be used for a local caching system. Furthermore, accelerators usually have a lot of memory on their CPU hosts (e.g. a 8xTPUv5e server has 128GiB of HBM, but around 450GiB of Host DRAM). This memory is much slower than HBM — too slow to do generation steps usually — but is fast enough for a cache read. In practice:

这之所以难以做到,唯一的限制是内存。正如我们所见,KV 缓存很大 (通常是几个 GB),为了使缓存有用,我们需要将它们保留到后续查询到达。通常,预填充服务器上任何未使用的 HBM 都可以用于本地缓存系统。此外,加速器通常在其 CPU 主机上有很多内存 (例如,一个 8xTPU v5e 服务器有 128GiB 的 HBM,但大约有 450GiB 的主机 DRAM)。这个内存比 HBM 慢得多 —— 通常慢到无法进行生成步骤 —— 但对于缓存读取来说足够快。在实践中:

  • Because the KV cache is local to the set of TPUs that handled the initial request, we need some form of affinity routing to ensure follow-up queries arrive at the same replica. This can cause issues with load balancing.
  • A smaller KV cache is helpful (again) — it enables us to save more KV caches in the same amount of space, and reduce read times.
  • The KV cache and their lookups can be stored quite naturally in a tree or trie. Evictions can happen on an LRU basis.
  • 因为 KV 缓存是处理初始请求的 TPU 集合的本地缓存,我们需要某种形式的亲和路由来确保后续查询到达同一个副本。这可能会导致负载均衡问题。
  • 更小的 KV 缓存是有帮助的 (再次) —— 它使我们能够在相同的空间中保存更多的 KV 缓存,并减少读取时间。
  • KV 缓存及其查找可以很自然地存储在树或 trie 中。可以按 LRU (最近最少使用) 的原则进行驱逐。
prefix caching trie

Figure: KV prefix cache implemented as an LRU trie. We can avoid duplicating KV memory by sharing prefixes. Source: Character.ai blog.

图: 实现为 LRU trie 的 KV 前缀缓存. 我们可以通过共享前缀来避免重复的 KV 内存. 来源: Character.ai 博客.

Let’s look at an implementation: JetStream让我们看一个实现:JetStream

Google has open-sourced a library that implements this logic called JetStream. The server has a set of “prefill engines” and “generate engines”, usually on different TPU slices, which are orchestrated by a single controller. Prefill happens in the “prefill thread”, while generation happens in the “generate thread”. We also have a “transfer thread” that orchestrates copying the KV caches from the prefill to generate slices.

谷歌开源了一个实现此逻辑的库,名为 JetStream。该服务器有一组“预填充引擎”和“生成引擎”,通常在不同的 TPU 切片上,由单个控制器进行编排。预填充发生在“预填充线程”中,而生成发生在“生成线程”中。我们还有一个“传输线程”,负责编排从预填充切片到生成切片的 KV 缓存复制。

The Engine interface (implemented here) is a generic interface that any LLM must provide. The key methods are:

Engine 接口 (在这里实现) 是任何 LLM 都必须提供的通用接口。关键方法是:

  • prefill: takes a set of input tokens and generates a KV cache.
  • insert: takes a KV cache and inserts it into the batch of KV caches that generate is generating from.
  • generate: takes a set of batched KV caches and generates one token per batch entry, appending a single token’s KV cache to the decode state for each token.
  • prefill: 接受一组输入 token 并生成一个 KV 缓存。
  • insert: 接受一个 KV 缓存并将其插入到生成正在生成的 KV 缓存批次中。
  • generate: 接受一组批处理的 KV 缓存,并为每个批处理条目生成一个 token,将单个 token 的 KV 缓存附加到每个 token 的解码状态。

We also have a PyTorch version of JetStream available here.

我们还有一个 PyTorch 版本的 JetStream,可在这里找到。

Worked Problems习题与解答

I’m going to invent a new model based on LLaMA-2 13B for this section. Here are the details:

我将为本节发明一个基于 LLaMA-2 13B 的新模型。以下是详细信息:

hyperparam
超参数
value
值
L (num_layers)
L (层数)
64
D (d_model)4,096
F (ffw_dimension)16,384
N (num_heads)
N (头数)
32
K (num_kv_heads)8
H (qkv_dim)256
V (num_embeddings)32,128

Question 1: How many parameters does the above model have? How large are its KV caches per token in int8? You can assume we share the input and output projection matrices.

问题 1: 上述模型有多少参数?每个 token 的 KV 缓存 (int8) 有多大?你可以假设我们共享输入和输出投影矩阵。

Click here for the answer. 点击这里查看答案.

Parameter count:

参数数量:

  • MLP parameter count: L∗D∗F∗3L * D * F * 3
  • Attention parameter count: L∗2∗D∗H∗(N+K)L * 2 * D * H * (N + K)
  • Vocabulary parameter: D∗VD * V (since we share these matrices)
  • MLP 参数数量:L∗D∗F∗3L * D * F * 3
  • 注意力参数数量:L∗2∗D∗H∗(N+K)L * 2 * D * H * (N + K)
  • 词汇表参数:D∗VD * V (因为我们共享这些矩阵)

Our total parameter count is thus L∗D∗(3F+2H∗(N+K))+D∗VL * D * (3F + 2H * (N + K)) + D * V. Plugging in the numbers above, we have 64 * 4096 * (3*16384 + 2 * 256 * (32 + 8)) + 4096 * 32128 = 18.4e9. Thus, this model has about 18.4 billion parameters.

因此,我们的总参数数量是 L∗D∗(3F+2H∗(N+K))+D∗VL * D * (3F + 2H * (N + K)) + D * V。代入上面的数字,我们有 64 * 4096 * (3*16384 + 2 * 256 * (32 + 8)) + 4096 * 32128 = 18.4e9。因此,这个模型大约有 184 亿个参数。

The KV caches are 2∗L∗K∗H2 * L * K * H per token in int8, which is 2 * 64 * 8 * 256 = 262kB per token.

KV 缓存是每个 token 2∗L∗K∗H2 * L * K * H,即 2 * 64 * 8 * 256 = 262kB.

Question 2: Say we want to serve this model on a TPUv5e 4x4 slice and can fully shard our KV cache over this topology. What’s the largest batch size we can fit, assuming we use int8 for everything and want to support 128k sequences? What if we dropped the number of KV heads to 1?

问题 2: 假设我们想在 TPU v5e 4x4 切片上服务这个模型,并且可以完全在这个拓扑上分片我们的 KV 缓存。假设我们对所有东西都使用 int8,并且想要支持 128k 序列,我们可以容纳的最大批次大小是多少?如果我们将 KV 头的数量减少到 1 呢?

Click here for the answer. 点击这里查看答案.

Our KV caches have size 2⋅L⋅K⋅H2 \cdot L \cdot K \cdot H per token in int8, or 2 * 64 * 8 * 256 = 262kB. For 128k sequences, this means 262e3 * 128e3 = 33.5GB per batch entry. Since each TPU has 16GB of HBM, including our parameters, the largest batch size we can fit is (16 * 16e9 - 18.4e9) / 33.5e9 = 7. If we had K=1K=1, we would have 8 times this, aka about 56.

我们的 KV 缓存每个 token 在 int8 中有 2⋅L⋅K⋅H2 \cdot L \cdot K \cdot H 的大小,或 2 * 64 * 8 * 256 = 262kB。对于 128k 序列,这意味着每个批处理条目 262e3 * 128e3 = 33.5GB。由于每个 TPU 有 16GB 的 HBM,包括我们的参数,我们可以容纳的最大批次大小是 (16 * 16e9 - 18.4e9) / 33.5e9 = 7。如果我们有 K=1K=1,我们将有这个的 8 倍,即大约 56.

Question 3: How long does it take to load all the parameters into the MXU from HBM assuming they’re fully sharded on a TPU v5e 4x4 slice? Assume int8 parameters. This is a good lower bound on the per-step latency.

问题 3: 假设参数在 TPU v5e 4x4 切片上完全分片,将所有参数从 HBM 加载到 MXU 需要多长时间?假设 int8 参数。这是每步延迟的一个很好的下限。

Click here for the answer. 点击这里查看答案.

We have a total of 18.4B parameters, or 18.4e9 bytes in int8. We have 8.2e11 HBM bandwidth per chip, so it will take roughly 18e9 / (8.2e11 * 16) = 1.4ms assuming we can fully use our HBM bandwidth.

我们总共有 18.4B 个参数,或 18.4e9 字节 (int8)。我们每个芯片有 8.2e11 字节/秒的 HBM 带宽,所以大约需要 18e9 / (8.2e11 * 16) = 1.4ms,假设我们可以完全利用我们的 HBM 带宽。

Question 4: Let’s say we want to serve this model on a TPUv5e 4x4 slice using int8 FLOPs and parameters/activations. How would we shard it for both prefill and decode? Hint: maybe answer these questions first:

问题 4: 假设我们想在 TPU v5e 4x4 切片上使用 int8 FLOPs 和参数/激活来服务这个模型。我们将如何为预填充和解码进行分片?提示:也许先回答这些问题:

  1. What does ICI look like on a 4x4?
  2. What’s the roofline bound on tensor parallelism?
  3. How can we shard the KV caches?
  1. 4x4 上的 ICI 是什么样的?
  2. 张量并行的屋顶线限制是什么?
  3. 我们如何对 KV 缓存进行分片?

For this sharding, what is the rough per-step latency for generation?

对于这个分片,生成的粗略每步延迟是多少?

Question 5: Let’s pretend the above model is actually an MoE. An MoE model is effectively a dense model with E copies of the FFW block. Each token passes through k of the FFW blocks and these k are averaged to produce the output. Let’s use E=16 and k=2 with the above settings.

问题 5: 让我们假装上面的模型实际上是一个 MoE. MoE 模型实际上是一个具有 E 个 FFW 块副本的密集模型。每个 token 通过 k 个 FFW 块,这 k 个块被平均以产生输出。让我们使用 E=16 和 k=2 以及上面的设置。

  1. How many total and activated parameters does it have? Activated means used by any given token.
  2. What batch size is needed to become FLOPs bound on TPU v5e?
  3. How large are its KV caches per token?
  4. How many FLOPs are involved in a forward pass with T tokens?
  1. 它总共有多少个和激活的参数?激活的意味着被任何给定的 token 使用。
  2. 在 TPU v5e 上需要多大的批次大小才能受 FLOPs 限制?
  3. 每个 token 的 KV 缓存有多大?
  4. 一个 T token 的前向传播涉及多少 FLOPs?
Click here for the answer. 点击这里查看答案.

(1) As an MoE, each MLP block now has 3∗E∗D∗F3 * E * D * F parameters, an increase of EE over the dense variant. Thus it now has L∗D∗(3EF+2H∗(N+K))+D∗VL * D * (3EF + 2H * (N + K)) + D * V or 64 * 4096 * (3*16*16384 + 2 * 256 * (32 + 8)) + 4096 * 32128 = 212e9 total parameters, an increase of about 12x. For activated parameters, we have kk rather than EE activated parameters, for a total of 64 * 4096 * (3*2*16384 + 2 * 256 * (32 + 8)) + 4096 * 32128 = 31.2e9, an increase of less than 2x over the dense variant.

(1) 作为一个 MoE,每个 MLP 块现在有 3∗E∗D∗F3 * E * D * F 个参数,比密集变体增加了 EE 倍。因此,它现在总共有 L∗D∗(3EF+2H∗(N+K))+D∗VL * D * (3EF + 2H * (N + K)) + D * V 或 64 * 4096 * (3*16*16384 + 2 * 256 * (32 + 8)) + 4096 * 32128 = 212e9 个参数,增加了约 12 倍。对于激活的参数,我们有 kk 而不是 EE 个激活的参数,总共 64 * 4096 * (3*2*16384 + 2 * 256 * (32 + 8)) + 4096 * 32128 = 31.2e9,比密集变体增加了不到 2 倍。

(2) Because we have EE times more parameters for only kk times more FLOPs, our HBM roofline increases by a factor of E/kE/k. That means on a TPU v5e we need about 240 * (16 / 2) = 1920 tokens.

(2) 因为我们有 EE 倍的参数,但只有 kk 倍的 FLOPs,我们的 HBM 屋顶线增加了 E/kE/k 倍。这意味着在 TPU v5e 上,我们需要大约 240 * (16 / 2) = 1920 个 token.

(3) The KV cache size stays the same as the MoE character doesn’t change anything about the attention mechanism.

(3) KV 缓存大小保持不变,因为 MoE 特性不会改变注意力机制的任何东西。

(4) This is still 2⋅activated params⋅T2 \cdot \text{activated params} \cdot T. Thus this is 2∗31.2e9∗T2 * \text{31.2e9} * T.

(4) 仍按 2⋅activated params⋅T2 \cdot \text{activated params} \cdot T 计算,即 2∗31.2e9∗T2 * \text{31.2e9} * T。

Question 6: With MoEs, we can do “expert sharding”, where we split our experts across one axis of our mesh. In our standard notation, our first FFW weight has shape [E, D, F] and we shard it as [EZ, DX, FY] where X is only used during training as our FSDP dimension. Let’s say we want to do inference on a TPU v5e:

问题 6: 对于 MoE,我们可以进行“专家分片”,即我们将我们的专家分布在我们网格的一个轴上。在我们的标准符号中,我们的第一个 FFW 权重的形状为 [E, D, F],我们将其分片为 [EZ, DX, FY],其中 X 仅在训练期间用作我们的 FSDP 维度。假设我们想在 TPU v5e 上进行推理:

  1. What’s the HBM weight loading time for the above model on a TPU v5e 8x16 slice with Y=8, Z=16? How much free HBM is available per TPU?
  2. What is the smallest slice we could fit our model on?
  1. 在 TPU v5e 8x16 切片上,Y=8, Z=16,上述模型的 HBM 权重加载时间是多少?每个 TPU 有多少可用的 HBM?
  2. 我们可以将我们的模型容纳在的最小切片是多少?

Question 7 [2D model sharding]: Here we’ll work through the math of what the ESTI paper calls 2D weight-stationary sharding. We describe this briefly in Appendix B, but try doing this problem first to see if you can work out the math. The basic idea of 2D weight stationary sharding is to shard our weights along both the DD and FF axes so that each chunk is roughly square. This reduces the comms load and allows us to scale slightly farther.

问题 7 [2D 模型分片]: 在这里,我们将详细讲解 ESTI 论文所谓的 2D 权重固定分片的数学原理。我们在附录 B 中简要描述了这一点,但请先尝试做这个问题,看看你是否能算出数学原理。2D 权重固定分片的基本思想是沿 DD 和 FF 轴对我们的权重进行分片,以便每个块大致呈方形。这减少了通信负载,并允许我们进一步扩展。

Here’s the algorithm for 2D weight stationary:

这是 2D 权重固定的算法:

  1. In[B, DX] = AllGatherYZ(In[B, DXYZ])
  2. Tmp[B, FYZ] {UX} = In[B, DX] *D Win[DX, FYZ]
  3. Tmp[B, FYZ] = AllReduceX(Tmp[B, FYZ] {UX})
  4. Out[B, DX] {UYZ} = Tmp[B, FYZ] *F Wout[FYZ, DX]
  5. Out[B, DXYZ] = ReduceScatterYZ(Out[B, DX] {UYZ})

Your goal is to work out TmathT_\text{math} and TcommsT_\text{comms} for this algorithm and find when it will outperform traditional 3D model sharding?

你的目标是为这个算法计算出 TmathT_\text{math} 和 TcommsT_\text{comms},并找出它何时会优于传统的 3D 模型分片?

Click here for the answer! 点击这里查看答案!

Let’s work out TmathT_\text{math} and TcommsT_\text{comms}. All our FLOPs are fully sharded so as before we have Tmath=4BDF/(N⋅C)T_\text{math} = 4BDF / (N \cdot C) but our comms are now

让我们计算 TmathT_\text{math} 和 TcommsT_\text{comms}。我们所有的 FLOPs 都是完全分片的,所以和以前一样,我们有 Tmath=4BDF/(N⋅C)T_\text{math} = 4BDF / (N \cdot C),但我们的通信现在是

T2D comms=2BD2X⋅Wici+4BFYZ⋅Wici+2BD2X⋅Wici=2BDX⋅Wici+4BFYZ⋅Wici\begin{align*} T_\text{2D comms} = \frac{2BD}{2X \cdot W_\text{ici}} + \frac{4BF}{YZ \cdot W_\text{ici}} + \frac{2BD}{2X \cdot W_\text{ici}} = \frac{2BD}{X \cdot W_\text{ici}} + \frac{4BF}{YZ \cdot W_\text{ici}} \end{align*}

where we note that the AllReduce is twice as expensive and we scale our comms by the number of axes over which each operation is performed. Assuming we have freedom to choose our topology and assuming F=4DF=4D (as in LLaMA-2), we claim (by some basic calculus) that the optimal values for XX, YY, and ZZ are X=N/8X = \sqrt{N / 8}, YZ=8NYZ = \sqrt{8N} so the total communication is

其中我们注意到 AllReduce 的成本是两倍,并且我们根据每个操作执行的轴数来缩放我们的通信。假设我们可以自由选择我们的拓扑,并且假设 F=4DF=4D (如 LLaMA-2),我们声称 (通过一些基本的微积分) XX, YY 和 ZZ 的最佳值是 X=N/8X = \sqrt{N / 8}, YZ=8NYZ = \sqrt{8N},所以总通信是

T2D comms=2BWici(DX+8DYZ)=128BDN⋅Wici≈11.3BDN⋅WiciT_\text{2D comms} = \frac{2B}{W_\text{ici}} \left(\frac{D}{X} + \frac{8D}{YZ}\right) = \frac{\sqrt{128} BD}{\sqrt{N} \cdot W_\text{ici}} \approx \frac{11.3 BD}{\sqrt{N} \cdot W_\text{ici}}

Firstly, copying from above, normal 1D model parallelism would have Tmodel parallel comms=4BD/(3⋅Wici)T_\text{model parallel comms} = 4BD / (3 \cdot W_\text{ici}), so when are the new comms smaller? We have

首先,从上面复制,普通的 1D 模型并行将有 Tmodel parallel comms=4BD/(3⋅Wici)T_\text{model parallel comms} = 4BD / (3 \cdot W_\text{ici}),那么新的通信何时更小?我们有

Tmodel parallel comms>T2D comms  ⟺  4BD3⋅Wici>128BDN⋅Wici  ⟺  N>128⋅(34)2=72\begin{align*} T_\text{model parallel comms} > T_\text{2D comms} \iff \frac{4BD}{3 \cdot W_\text{ici}} > \frac{\sqrt{128} BD}{\sqrt{N} \cdot W_\text{ici}} \\ \iff N > 128 \cdot \left(\frac{3}{4}\right)^2 = 72 \end{align*}

For a general FF, we claim this condition is

对于一个通用的 FF,我们声称这个条件是

N>32⋅(FD)⋅(34)2N > 32 \cdot \left(\frac{F}{D}\right) \cdot \left(\frac{3}{4}\right)^2

So that tells us if we have more than 72 chips, we’re better off using this new scheme. Now this is a slightly weird result because we’ve historically found ourselves ICI bound at around ~20 way tensor parallelism. But here, even if we’re communication-bound, our total communication continues to decrease with the number of total chips! What this tells us is that we can continue to increase our chips, increase our batch size, do more parameter scaling, and see reduced latency.

所以这告诉我们,如果我们有超过 72 个芯片,我们最好使用这个新方案。现在这是一个有点奇怪的结果,因为我们历史上发现自己在 ~20 路张量并行时受 ICI 限制。但在这里,即使我们受通信限制,我们的总通信也会随着总芯片数量的增加而持续减少!这告诉我们,我们可以继续增加我们的芯片,增加我们的批次大小,进行更多的参数扩展,并看到延迟降低。

That’s all for Part 7! For Part 8, with a look at how we might serve LLaMA 3 on TPUs, click here.

第 7 部分到此结束!第 8 部分,看看我们如何可能在 TPU 上服务 LLaMA 3,点击 这里.

Appendix附录

Appendix A: How real is the batch size > 240 rule?附录 A:批处理大小 > 240 规则有多真实?

The simple rule we provided above, that our batch size must be greater than 240 tokens to be compute-bound, is roughly true but ignores some ability of the TPU to prefetch the weights while other operations are not using all available HBM, like when doing inter-device communication.

我们上面提供的简单规则,即我们的批次大小必须大于 240 个 token 才能受计算限制,大致是正确的,但忽略了 TPU 在其他操作不使用所有可用 HBM 时预取权重的一些能力,比如在进行设备间通信时。

Here’s an empirical plot of layer time (in microseconds) for a small Transformer with dmodel 8192, dff 32768, and only 2 matmuls per layer. This comes from this Colab notebook. You’ll see that step time increases very slowly up until around batch 240, and then increases linearly.

这是一个小型 Transformer 的层时间 (以微秒为单位) 的实证图,dmodel 为 8192, dff 为 32768,每层只有 2 个矩阵乘法。这来自这个 Colab 笔记本。你会看到单步耗时增长非常缓慢,直到大约批量 240,然后线性增长。

batch scaling latency

Here’s the actual throughput in tokens / us. This makes the argument fairly clearly. Since our layer is about 600M parameters sharded 4 ways here, we’d expect a latency of roughly 365us at minimum.

这是实际的吞吐量,以 token/us 为单位。这很清楚地说明了论点。由于我们的层大约是 600M 参数,在这里分片 4 路,我们预计最小延迟大约是 365us.

batch scaling throughput

So at least in this model, we do in fact see throughput increase until about BS240 per data parallel shard.

所以至少在这个模型中,我们确实看到吞吐量增加,直到每个数据并行分片大约 BS240.

Appendix B: 2D Weight Stationary sharding附录 B: 2D 权重固定分片

As the topology grows, if we have access to higher dimensional meshes (like that of TPUs) it is possible to refine this further with “2D Weight Sharding” by introducing a second sharding axis. We call this “2D Weight Stationary”, and was described in more detail in the Efficiently Scaling Transformer Inference paper.

随着拓扑的增长,如果我们可以访问更高维度的网格 (如 TPU 的网格),就可以通过“2D 权重分片”进一步完善。通过引入第二个分片轴。我们称之为“2D 权重固定”,在高效扩展 Transformer 推理论文中有更详细的描述。

Because we’re only sharding the hidden FF dimension in Megatron, it can become significantly smaller than EE (the dmodeld_\text{model} dimension) once the number of chips grows large with 1D sharding. This means at larger batch sizes, it can be more economical to perform a portion of the collectives over the hidden dimension after the first layer of the MLP is applied.

因为我们只在 Megatron 中对隐藏的 FF 维度进行分片,所以随着芯片数量随着 1D 分片而增长,它可能会变得比 EE ( dmodeld_\text{model} 维度) 小得多。这意味着在更大的批次大小时,在应用 MLP 的第一层后,在隐藏维度上执行一部分集合通信可能更经济。

2d weight stationary

This figure shows:

该图显示:

  1. 1D weight-stationary sharding, a.k.a. Pure Megatron sharding, where activations are fully replicated after AllGather, and weights are fully sharded over the hidden F dimension.
  2. 2D weight stationary sharding, where weights are sharded over both the hidden F and reduction E dimension, and activations are sharded over the E dimension. We perform an AllGather on the (yz) axis before the first layer, then ReduceScatter on the (x) axis.
  1. 1D 权重固定分片,又名纯 Megatron 分片,其中激活在 AllGather 后完全复制,权重在隐藏的 F 维度上完全分片。
  2. 2D 权重固定分片,其中权重在隐藏的 F 和归约 E 维度上都进行分片,激活在 E 维度上进行分片。我们在第一层之前在 (yz) 轴上执行 AllGather,然后在 (x) 轴上执行 ReduceScatter.

For the attention layer, Megatron style sharding is also relatively simple for smaller numbers of chips. However, Megatron happens over the nheadsn_\text{heads} dimension, which puts a limit on the amount of sharding that is possible. Modifying the 2D sharding for attention (instead of sharding the hidden dimension, we shard the nheadsn_\text{heads} dimension), we gain the ability to scale further.

对于注意力层,Megatron 风格的分片对于较少数量的芯片也相对简单。然而,Megatron 发生在 nheadsn_\text{heads} 维度上,这对可能的分片数量设置了限制。通过修改 2D 分片 (不是分片隐藏维度,而是分片 nheadsn_\text{heads} 维度),我们获得了进一步扩展的能力。

Appendix C: Latency bound communications附录 C:受延迟限制的通信

As a recap, in Section 3 we derived the amount of time it takes to perform an AllGather into a tensor of size B on each TPU, over X chips on a 1D ring with links of full-duplex bandwidth of WICI and latency Tmin.

回顾第 3 章的推导。在由 X 台芯片组成的一维环上执行 AllGather,使每台 TPU 得到大小为 B 的张量。设环上链路的全双工带宽为 WICI、延迟为 Tmin,AllGather 耗时如下:

Ttotal=max⁡(Tmin⋅∣X∣2,BWICI)T_{total} = \max\left(\frac{T_{min} \cdot |X|}{2}, \frac{B}{W_{ICI}}\right)

For large B, the wall clock stays relatively constant because as you add more chips to the system, you simultaneously scale the amount of data movement necessary to perform the operation and the total bandwidth available.

对于大的 B,时钟时间相对恒定,因为当你向系统添加更多芯片时,你同时扩展了执行操作所需的数据移动量和可用的总带宽。

all gather

Because of the relatively low amounts of data being moved during latency optimized inference, collectives on activations are often bound by the latency term (especially for small batch sizes). One can visualise the latency quite easily, by counting the number of hops we need to complete before it is completed.

由于在延迟优化的推理期间移动的数据量相对较少,激活上的集合通信通常受延迟项的限制 (特别是对于小批次大小)。通过计算我们需要完成的跳跃次数,可以很容易地可视化延迟。

On TPUs, if the tensor size-dependent part of communication is less than 1 microsecond per hop (a hop is communication between two adjacent devices) we can be bottlenecked by the fixed overhead of actually dispatching the collective. With 4.5e10 unidirectional ICI bandwidth, ICI communication becomes latency bound when: (bytes/nshards)/4.5e10<1e−6(\text{bytes} / n_\text{shards}) / 4.5e10 < 1e-6. For 8-way Megatron sharding, this is when buffer_size < 360kB. This actually is not that small during inference: with BS=16 and D=8192 in int8, our activations will use 16*8192=131kB, so we’re already latency bound.

在 TPU 上,如果通信的张量大小相关部分每跳 (一跳是两个相邻设备之间的通信) 小于 1 微秒,我们可能会受到实际分派集合的固定开销的瓶颈。单向 ICI 带宽为 4.5e10,当 (bytes/nshards)/4.5e10<1e−6(\text{bytes} / n_\text{shards}) / 4.5e10 < 1e-6 时,ICI 通信变得受延迟限制。对于 8 路 Megatron 分片,这是当 buffer_size < 360kB 时。这在推理期间实际上并不那么小: BS=16 和 D=8192 (int8),我们的激活将使用 16*8192=131kB,所以我们已经受延迟限制了。

There’s a parallel to be drawn here with the compute roofline — we are incurring the fixed cost of some small operations (latency for comms, memory bandwidth for matmuls).

这里可以与计算屋顶线进行类比 —— 我们正在承担一些小操作的固定成本 (通信的延迟,矩阵乘法的内存带宽).

Appendix D: Speculative Sampling附录 D:推测性采样

When we really care about end to end latency, there is one extra trick we can employ called speculative sampling[3][4]. As a recap, we usually generate tokens from a large Transformer one by one:

当我们真正关心端到端延迟时,我们可以采用一个额外的技巧,称为推测性采样[3][4]。作为回顾,我们通常从一个大型 Transformer 中逐个生成 token:

spec sampling1

With speculative sampling, we use a smaller, cheaper model to generate tokens and then check the result with the big model. This is easiest to understand with greedy decoding:

通过推测性采样,我们使用一个更小,更便宜的模型来生成 token,然后用大模型检查结果。这最容易用贪婪解码来理解:

spec sampling2
  1. We sample greedily from some smaller, cheaper model. Ideally we use a model trained to match the larger model, e.g. by distillation, but it could be as simple as simply using n-grams or token matching a small corpus of text.
  2. After we’ve generated K tokens, we use the big model to compute the next-token logits for all the tokens we’ve generated so far.
  3. Since we’re decoding greedily, we can just check if the token generated by the smaller model has the highest probability of all possible tokens. If one of the tokens is wrong, we take the longest correct prefix and replace the first wrong token with the correct token, then go back to (1). If all the tokens are correct, we can use the last correct logit to sample an extra token before going back to (1).
  1. 我们从某个更小,更便宜的模型中进行贪婪采样。理想情况下,我们使用一个经过训练以匹配较大模型的模型,例如通过蒸馏,但它也可以像简单地使用 n-gram 或匹配一小部分文本的 token 一样简单。
  2. 在我们生成了 K 个 token 之后,我们使用大模型来计算我们到目前为止生成的所有 token 的下一个 token 的 logits.
  3. 由于我们是贪婪解码,我们可以简单地检查较小模型生成的 token 是否是所有可能 token 中概率最高的。如果其中一个 token 错误,我们取最长的正确前缀,并用正确的 token 替换第一个错误的 token,然后回到 (1)。如果所有 token 都正确,我们可以使用最后一个正确的 logit 来采样一个额外的 token,然后再回到 (1).

Why is this a latency win? This scheme still requires us to do the FLOPs-equivalent of one forward pass through the big model for every token, but because we can batch a bunch of tokens together, we can do all these FLOPs in one forward pass and take advantage of the fact that we’re not compute-bound to score more tokens for free.

为什么这是一个延迟上的胜利? 这个方案仍然要求我们为每个 token 执行相当于大模型一次前向传播的 FLOPs,但因为我们可以将一堆 token 批处理在一起,我们可以将所有这些 FLOPs 放在一次前向传播中完成,并利用我们不受计算限制的事实来免费评分更多的 token.

Every accepted token becomes more expensive in terms of FLOPs on average (since some will be rejected, and we have to call a draft model), but we wring more FLOPs out of the hardware, and the small model is cheap, so we win overall. We also share KV cache loads across multiple steps, so speculative decoding can also be a throughput win for long context. Since everything has been checked by the big model, we don’t change the sampling distribution at all (though the exact trajectory will differ for non-greedy).

平均而言,每个被接受的 token 在 FLOPs 方面变得更加昂贵 (因为有些会被拒绝,而且我们必须调用一个草稿模型),但我们从硬件中榨取了更多的 FLOPs,而且小模型很便宜,所以我们总体上是赢的。我们还在多个步骤之间共享 KV 缓存加载,所以对于长上下文,推测性解码也可以在吞吐量上取得胜利。 由于所有内容都经过了大模型的检查,我们根本没有改变采样分布 (尽管对于非贪婪解码,确切的轨迹会有所不同).

Traditionally, speculative decoding relies on the existence of a smaller model with a similar sampling distribution to the target model, e.g. LLaMA-2 2B for LLaMA-2 70B, which often doesn’t exist. Even when this is available, the smaller drafter can still be too expensive if the acceptance rate is low. Instead, it can be helpful to embed a drafter within the main model, for instance by adding a dedicated drafter head to one of the later layers of the base model[5][6][7]. Because this head shares most of its parameters with the main model, it’s faster to run and matches the sampling distribution more closely.

传统上,推测性解码依赖于存在一个与目标模型具有相似采样分布的较小模型,例如 LLaMA-2 70B 的 LLaMA-2 2B,这通常不存在。即使存在,如果接受率很低,较小的草稿模型仍然可能过于昂贵。相反,将草稿模型嵌入到主模型中可能会有所帮助,例如通过在基础模型的后期层中添加一个专用的草稿头[5][6][7]。因为这个头与主模型共享大部分参数,所以它运行得更快,并且更接近采样分布。

For normal autoregressive sampling the token/s is the same as the step time. We are still beholden to the theoretical minimum step time according to the Arithmetic Intensity section here (in fact, Speculative Sampling step times are usually quite a bit slower than normal autoregressive sampling, but because we get more than 1 token out per step on average we can get much better tokens/s).

对于正常的自回归采样,token/s 与单步耗时相同。我们仍然受限于这里算术强度部分的理论最小单步耗时 (事实上,推测性采样的单步耗时通常比正常的自回归采样慢得多,但因为我们平均每步得到超过 1 个 token,我们可以得到更好的 token/s).

spec sampling3

Figure: this figure shows the per-step latency and speculation success rate for Chinchilla (a 70B model from DeepMind) with a 4B parameter drafter (small model). For XSum (a natural language dataset), the ideal amount of speculation is about 3-4 tokens ahead, while HumanEval (a coding dataset) is more predictable and sees wins from more aggressive speculation.

图: 该图显示了 Chinchilla (一个 70B 模型, 来自 DeepMind) 使用一个 4B 参数的草稿模型 (小模型) 的每步延迟和推测成功率. 对于 XSum (一个自然语言数据集), 理想的推测量大约是提前 3-4 个 token, 而 HumanEval (一个编码数据集) 更可预测, 并且从更激进的推测中获益.

How does this work for non-greedy decoding? This is a bit more complicated, but essentially boils down to a Metropolis-Hastings inspired algorithm where we have Pdraft model(chosen token)P_{\text{draft model}}(\text{chosen token}) and Ptarget model(chosen token)P_{\text{target model}}(\text{chosen token}) derived from the logits, and reject the chosen token probabilistically if the ratio of these probabilities is smaller than some threshold.

这对于非贪婪解码是如何工作的? 这有点复杂,但本质上归结为一个受 Metropolis-Hastings 启发的算法,其中我们有从 logits 派生出的 Pdraft model(chosen token)P_{\text{draft model}}(\text{chosen token}) 和 Ptarget model(chosen token)P_{\text{target model}}(\text{chosen token}),如果这些概率的比率小于某个阈值,则概率性地拒绝选择的 token.

These two papers derived this concurrently and have good examples of how this works in practice.

这两篇 论文 同时推导出了这一点,并提供了很好的例子来说明这在实践中是如何工作的。

References参考文献

  1. Efficiently scaling Transformer inference. Pope, Reiner and Douglas, Sholto and Chowdhery, Aakanksha and Devlin, Jacob and Bradbury, James and Levskaya, Anselm and Heek, Jonathan and Xiao, Kefan and Agrawal, Shivani and Dean, Jeff. 2022.
  2. Efficient memory management for large language model serving with PagedAttention. Kwon, Woosuk and Li, Zhuohan and Zhuang, Siyuan and Sheng, Ying and Zheng, Lianmin and Yu, Cody Hao and Gonzalez, Joseph E and Zhang, Hao and Stoica, Ion. 2023.
  3. Fast inference from Transformers via speculative decoding. Leviathan, Yaniv and Kalman, Matan and Matias, Yossi. 2022.
  4. Accelerating large language model decoding with speculative sampling. Chen, Charlie and Borgeaud, Sebastian and Irving, Geoffrey and Lespiau, Jean-Baptiste and Sifre, Laurent and Jumper, John. 2023.
  5. EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty. Li, Yuhui and Wei, Fangyun and Zhang, Chao and Zhang, Hongyang. 2024.
  6. Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads. Cai, Tianle and Li, Yuhong and Geng, Zhengyang and Peng, Hongwu and Lee, Jason and Chen, Deming and Dao, Tri”. 2024.
  7. DeepSeek-V3 Technical Report. DeepSeek-AI and Liu, Aixin and Feng, Bei and Xue, Bing and Wang, Bingxuan and Wu, Bochao and Lu, Chengda and Zhao, Chenggang and Deng, Chengqi and Zhang, Chenyu and Ruan, Chong and Dai, Damai and Guo, Daya and Yang, Dejian and Chen, Deli and Ji, Dongjie and Li, Erhang and Lin, Fangyun and Dai, Fucong and Luo, Fuli and Hao, Guangbo and Chen, Guanting and Li, Guowei and Zhang, H and Bao, Han and Xu, Hanwei and Wang, Haocheng and Zhang, Haowei and Ding, Honghui and Xin, Huajian and Gao, Huazuo and Li, Hui and Qu, Hui and Cai, J L and Liang, Jian and Guo, Jianzhong and Ni, Jiaqi and Li, Jiashi and Wang, Jiawei and Chen, Jin and Chen, Jingchang and Yuan, Jingyang and Qiu, Junjie and Li, Junlong and Song, Junxiao and Dong, Kai and Hu, Kai and Gao, Kaige and Guan, Kang and Huang, Kexin and Yu, Kuai and Wang, Lean and Zhang, Lecong and Xu, Lei and Xia, Leyi and Zhao, Liang and Wang, Litong and Zhang, Liyue and Li, Meng and Wang, Miaojun and Zhang, Mingchuan and Zhang, Minghua and Tang, Minghui and Li, Mingming and Tian, Ning and Huang, Panpan and Wang, Peiyi and Zhang, Peng and Wang, Qiancheng and Zhu, Qihao and Chen, Qinyu and Du, Qiushi and Chen, R J and Jin, R L and Ge, Ruiqi and Zhang, Ruisong and Pan, Ruizhe and Wang, Runji and Xu, Runxin and Zhang, Ruoyu and Chen, Ruyi and Li, S S and Lu, Shanghao and Zhou, Shangyan and Chen, Shanhuang and Wu, Shaoqing and Ye, Shengfeng and Ye, Shengfeng and Ma, Shirong and Wang, Shiyu and Zhou, Shuang and Yu, Shuiping and Zhou, Shunfeng and Pan, Shuting and Wang, T and Yun, Tao and Pei, Tian and Sun, Tianyu and Xiao, W L and Zeng, Wangding and Zhao, Wanjia and An, Wei and Liu, Wen and Liang, Wenfeng and Gao, Wenjun and Yu, Wenqin and Zhang, Wentao and Li, X Q and Jin, Xiangyue and Wang, Xianzu and Bi, Xiao and Liu, Xiaodong and Wang, Xiaohan and Shen, Xiaojin and Chen, Xiaokang and Zhang, Xiaokang and Chen, Xiaosha and Nie, Xiaotao and Sun, Xiaowen and Wang, Xiaoxiang and Cheng, Xin and Liu, Xin and Xie, Xin and Liu, Xingchao and Yu, Xingkai and Song, Xinnan and Shan, Xinxia and Zhou, Xinyi and Yang, Xinyu and Li, Xinyuan and Su, Xuecheng and Lin, Xuheng and Li, Y K and Wang, Y Q and Wei, Y X and Zhu, Y X and Zhang, Yang and Xu, Yanhong and Xu, Yanhong and Huang, Yanping and Li, Yao and Zhao, Yao and Sun, Yaofeng and Li, Yaohui and Wang, Yaohui and Yu, Yi and Zheng, Yi and Zhang, Yichao and Shi, Yifan and Xiong, Yiliang and He, Ying and Tang, Ying and Piao, Yishi and Wang, Yisong and Tan, Yixuan and Ma, Yiyang and Liu, Yiyuan and Guo, Yongqiang and Wu, Yu and Ou, Yuan and Zhu, Yuchen and Wang, Yuduan and Gong, Yue and Zou, Yuheng and He, Yujia and Zha, Yukun and Xiong, Yunfan and Ma, Yunxian and Yan, Yuting and Luo, Yuxiang and You, Yuxiang and Liu, Yuxuan and Zhou, Yuyang and Wu, Z F and Ren, Z Z and Ren, Zehui and Sha, Zhangli and Fu, Zhe and Xu, Zhean and Huang, Zhen and Zhang, Zhen and Xie, Zhenda and Zhang, Zhengyan and Hao, Zhewen and Gou, Zhibin and Ma, Zhicheng and Yan, Zhigang and Shao, Zhihong and Xu, Zhipeng and Wu, Zhiyu and Zhang, Zhongyu and Li, Zhuoshu and Gu, Zihui and Zhu, Zijia and Liu, Zijun and Li, Zilin and Xie, Ziwei and Song, Ziyang and Gao, Ziyi and Pan, Zizheng. 2024.

BibTeX

Footnotes

  1. Historically, you can do a surprising amount of research on Transformers without ever touching inference — scoring-based multiple choice benchmarks can be run efficiently without a proper KV cache or generation loop implementation. This meant, especially in research codebases, there’s often a lot of low hanging fruit in the inference codepath.

    以往很多 Transformer 研究都可以完全绕开生成式推理。只做打分的多项选择题基准不需要实现完整的 KV 缓存或生成循环。因此,研究代码中的推理路径往往有不少容易获得的性能收益。

    ↩
  2. One thing you’ll notice throughout this section is that inference is much less forgiving than training. We typically have far fewer FLOPs, less opportunity for batching, and a much greater sensitivity to latency. KV caches dramatically complicate inference as well.

    在本节中,你会注意到推理比训练要苛刻得多。我们通常有更少的 FLOPs,更少的批处理机会,以及对延迟的敏感度要高得多。KV 缓存也极大地复杂化了推理。

    ↩
  3. We’re simplifying a fair bit here by ignoring the non-matmul FLOPs in applying the softmax, masks etc. They should be overlapped with computation or HBM reads, but this can be non-trivial to do on certain TPU generations. While these details don’t change the main message, which is that KV caches are usually memory bound, they are worth paying attention to.

    我们在这里简化了很多,忽略了应用 softmax,掩码等中的非矩阵乘法 FLOPs。这部分计算应当与其他计算或 HBM 读取重叠,不过在某几代 TPU 上实现这种重叠并不容易。KV 缓存通常受内存带宽限制,实际实现时仍要留意这些细节。

    ↩
  4. Particularly thanks to Flash Attention, which avoids materializing our attention matrix

    特别感谢 Flash Attention,它避免了物化我们的注意力矩阵

    ↩
  5. Accidentally leaving it on after training is an easy and common way to have order of magnitude regressions

    训练后意外地将其保留是一个简单而常见的导致数量级回归的方式

    ↩
  6. By this we mean, spin up multiple servers with copies of the model at a smaller batch size. Data parallelism at the model level is strictly worse.

    我们的意思是,启动多个服务器,每个服务器都有一个较小批次大小的模型副本。模型级别的数据并行严格来说更差。

    ↩
  7. In the sense that FLOPs time isn’t bottlenecking us, so the thing we need to worry about is ICI time exceeding parameter loading time.

    从某种意义上说,FLOPs 时间不是我们的瓶颈,所以我们需要担心的是 ICI 时间超过参数加载时间。

    ↩

补充说明

*Work done at Google DeepMind, now at MatX.

*这项工作完成于 Google DeepMind,现任职于 MatX。

引用

For attribution in academic contexts, please cite this work as:

学术写作中请按以下格式引用本书。

Austin et al., "How to Scale Your Model", Google DeepMind, online, 2025.

or as a BibTeX entry:

也可使用以下 BibTeX 条目。

@article{scaling-book,
  title = {How to Scale Your Model},
  author = {Austin, Jacob and Douglas, Sholto and Frostig, Roy and Levskaya, Anselm and Chen, Charlie and Vikram, Sharad
    and Lebron, Federico and Choy, Peter and Ramasesh, Vinay and Webson, Albert and Pope, Reiner},
  publisher = {Google DeepMind},
  howpublished = {Online},
  note = {Retrieved from https://jax-ml.github.io/scaling-book/},
  year = {2025}
}
原版章节与讨论