Skip to content
quboliu
Go back

Repost · Bilingual

Building an LLM Inference Engine from Scratch从零构建大语言模型推理引擎

Area: AI 与 AgentEdit page

Inference engine overview: scheduler, overlap scheduling, ragged batch, paged KV cache and the Qwen3 model, with each optimization in red

Glossary · 术语表
  • TTFT · time to first token: how long from a request arriving until its first output token comes back.
  • TPOT · time per output token: the average gap between a request’s output tokens, after the first one.
  • ITL · inter-token latency: the time between two consecutive tokens of the same request.
  • E2E · end-to-end latency: the total time from a request arriving to its last token.
  • TPS · tokens per second: output tokens generated per second, across all requests.
  • KV cache · the attention keys and values of tokens already processed, stored so they don’t have to be recomputed every step.
  • prefill · the first pass over a prompt: every prompt token is processed at once, filling the KV cache.
  • decode · generating new tokens, one per request per step, reading everything earlier from the KV cache.
  • HBM · the GPU’s main memory (VRAM): large, but far slower than the on-chip memory kernels compute from.
  • TTFT · 首 token 延迟:从请求到达到首个输出 token 返回的时间。
  • TPOT · 每输出 token 耗时:从首个输出 token 之后计算,同一请求的平均输出间隔。
  • ITL · 相邻 token 延迟:同一请求中相邻两个输出 token 的时间间隔。
  • E2E · 端到端延迟:从请求到达到最后一个 token 返回的总时间。
  • TPS · 每秒 token 数:所有请求合计每秒生成的输出 token 数。
  • KV cache · 缓存已处理 token 的注意力键和值,避免逐步重复计算。
  • prefill · 首先处理整个提示词,一次计算全部输入 token,填充 KV 缓存。
  • decode · 读取先前的 KV 缓存,每一步为每个请求生成一个新 token。
  • HBM · GPU 的主显存(VRAM),容量大,但远慢于内核计算所用的片上存储。

TL;DR: Running an LLM is a simple loop. Serving it up to many users, making it fast, and fully utilizing the GPU is a systems problem. Through 10 optimizations, I’ll show how to build an inference engine to serve up Qwen3-0.6B, getting close to the open-source engines behind most inference APIs (vLLM & SGLang).

**简而言之:**运行大语言模型只需要一个简单的循环。要同时服务许多用户、降低延迟并充分利用 GPU,就成了系统工程问题。我会通过 10 项优化,从零搭建一个服务 Qwen3-0.6B 的推理引擎,让它的性能接近许多推理 API 背后的开源引擎 vLLM 和 SGLang。

There’s a surprising amount of machinery behind every request you send to an inference API. Each request is added to a waiting queue amongst thousands of other requests. It has to be sliced and batched to run on GPU. The computation needs to compete with hundreds of other requests for very constrained GPU memory. And all this needs to be handled fast enough so you don’t perceive a huge delay in your chats.

一次推理 API 请求背后有不少工作。请求要和成千上万条其他请求一起排队,再切分、组批,交给 GPU 执行。计算还要和数百条其他请求争用有限的显存。这些工作必须足够快,聊天时才不会感到明显的延迟。

Most of these core concepts work on a single GPU. We’ll iteratively write the code and work through the following optimizations

  1. Static Batching
  2. KV Caching
  3. Continuous Batching
  4. Chunked Prefill (+ policy)
  5. Flash Attention (+ Ragged Tensors)
  6. Paged KV Cache
  7. Prefix Caching
  8. CUDA Graphs
  9. Overlap Scheduling
  10. torch.compile

这些核心概念大多可在单块 GPU 上实践。我们会逐步编写代码,实现以下优化。

  1. 静态批处理
  2. KV 缓存
  3. 连续批处理
  4. 分块预填充,以及调度策略
  5. FlashAttention,以及变长张量
  6. 分页 KV 缓存
  7. 前缀缓存
  8. CUDA 图
  9. 重叠调度
  10. torch.compile

Results & Benchmarking结果与基准测试

Serve: TTFT

Serve: TTFT

服务基准:首 token 延迟

Serve: TPOT

Serve: TPOT

服务基准:每个输出 token 耗时

Serve: ITL

Serve: ITL

服务基准:相邻输出 token 的延迟

Serve: E2E

Serve: E2E

服务基准:端到端延迟

Max throughput

Max throughput

最大吞吐量

Shared prefix: TTFT

Shared prefix: TTFT

共享前缀:首 token 延迟

Latency: decode step

Latency: decode step

闭环延迟:单步解码

Latency: whole batch

Latency: whole batch

闭环延迟:整个批次

We’re benchmarking a Qwen3-0.6B in bf16 on an RTX 3060 12GB. We check for correctness against HuggingFace’s implementation.

我们在一块配有 12 GB 显存的 RTX 3060 上,以 bf16 精度测试 Qwen3-0.6B,并对照 Hugging Face 的实现验证正确性。

We collect the following metrics:

  • TTFT - time to first token (how long it takes for the first generation)
  • TPOT - time per output token
  • ITL - inter-token latency (the time between tokens)
  • E2E - the whole generation, end to end

我们记录以下指标。

  • TTFT:首 token 延迟,即请求到达至生成首个 token 的耗时。
  • TPOT:平均每个输出 token 的耗时。
  • ITL:相邻两个输出 token 的间隔。
  • E2E:整个生成过程的端到端延迟。

We record the p50/p90/p99 of it, because different optimizations will affect different percentiles.

我们记录 p50、p90 和 p99,因为不同优化会影响不同的分位数。

To find this, we run 3 benchmarks:

  • serve, which simulates users arriving at 1.8 req/s (Poisson). This is the main benchmark, as it simulates real-world behavior and tests the engine under uneven arrivals
  • latency, which times how long a step of the engine takes. This is used to find any kernel / engine-side improvements
  • throughput, which sends a bunch of requests all at once and sees the TPS that the engine achieves.

我们运行三项基准测试。

  • serve:以每秒 1.8 个请求的泊松过程模拟用户到达。这是主要基准,用于测试不均匀到达的请求对引擎的影响。
  • latency:测量引擎每一步的耗时,用于判断 GPU 内核或引擎本身的改进。
  • throughput:一次性提交大量请求,测量引擎每秒能输出多少 token。

We mainly focus on the serve benchmark, as it is the most relevant to the real world.

下文主要看 serve,因为它最接近实际部署。

We always do a warmup before benchmarking, for all of the JIT code to compile, kernels to be selected, etc.

每次测试前都先预热,让 JIT 完成编译,并选定所用的 GPU 内核。

Each serve run sends 100 requests with random-token prompts: 512 input / 128 output tokens, with each length drawn uniformly within ±80%. Generation stops at EOS like a real server would, so outputs average ~90 tokens. Every number is from a single run, except SGLang’s max TPS (mean of 3). vLLM 0.34.0 and SGLang 0.5.23 run with their defaults in bf16 (prefix caching off for the main table, on for the shared-prefix one), with SGLang capturing decode CUDA graphs up to batch 128. Our engine is benchmarked in-process while vLLM and SGLang go through their HTTP servers, which gives us a small edge on every latency number.1

每次 serve 测试提交 100 个由随机 token 组成的请求。输入和输出长度的标称值分别为 512 和 128 token,实际长度在各自标称值的 ±80% 内均匀采样。生成和实际服务一样,遇到 EOS 即停止,所以输出平均约 90 token。除 SGLang 的最大吞吐量取三次平均外,数据都来自单次运行。vLLM 0.34.0 和 SGLang 0.5.23 使用 bf16 默认配置,主表关闭前缀缓存,共享前缀表则开启。SGLang 为最大批大小 128 捕获解码 CUDA 图。我们的引擎在进程内直接测量,vLLM 和 SGLang 则经由 HTTP 服务测量,因此我们的延迟数据略占优势。1

Full results tables are in the appendix.

完整数据见附录。

All code is on GitHub

全部代码见 GitHub。

Summary of QwenQwen 架构概览

Qwen3 architecture: 28 stacked decoder layers

Qwen3 architecture: 28 stacked decoder layers

Qwen3 架构:堆叠的 28 层解码器

Qwen is very similar to the original attention paper with the following changes:

  • RoPE (good resource): A way of introducing “position” into the attention mechanism by rotating vectors
  • Grouped-Query Attention: Every head of attention gets a query matrix, but the key and value matrix are shared between some heads.
  • RMSNorm (instead of LayerNorm): A more computationally efficient normalization scheme
  • QKNorm: Apply RMS Norm to the key and query vectors, before RoPE and their dot product
  • SwiGLU: Train a “gate matrix”, and multiply the output by that gate matrix. Uses the SiLU activation function for the gate matrix. Allows it to selectively scale individual neurons.

Qwen 的结构与原始注意力论文很相似,主要有以下改动。

  • RoPE(参考讲解):通过旋转向量把位置信息传给注意力机制。
  • 分组查询注意力:每个注意力头都有自己的查询矩阵,多个头共享键矩阵和值矩阵。
  • RMSNorm:替换 LayerNorm,以降低归一化开销。
  • QKNorm:在应用 RoPE 并计算点积之前,先对键向量和查询向量做 RMSNorm。
  • SwiGLU:训练一个门控矩阵,以 SiLU 激活函数处理门控分支,再用它与输出相乘,从而有选择地缩放各神经元的输出。

You can check out the PyTorch implementation of Qwen3 at commit 0d4e790

提交 0d4e790 中有 Qwen3 的 PyTorch 实现。

We will wrap our model with the following entry point:

模型用下面的入口封装。

def forward(self, input_ids: torch.Tensor, meta: BatchMeta, kv_cache) -> torch.Tensor:
    pass

where input_ids is the token ids, and BatchMeta stores information about our current batch.

其中 input_ids 是 token ID,BatchMeta 保存当前批次的信息。

@dataclass
class BatchMeta:
    pass

Our scheduler will have the following contract:

调度器遵循下面的接口约定。

class Engine(Protocol):
    def add_request(self, request: Request) -> None: ...

    def step(self) -> list[TokenEvent]:
        ...

    def has_unfinished(self) -> bool: ...

Static Batching静态批处理

Generating tokens is memory-bound. The GPU has to stream the entire model’s weights from memory for every decode step, which only generates one token per sequence. For example, Qwen3-0.6B takes roughly 1.2 GB (bf16) in model weights. Assuming a memory bandwidth of 360 GB/s (on my 3060)2,

生成 token 受显存带宽限制。每一步解码,GPU 都要从显存读取整套权重,而每条序列只生成一个 token。例如,bf16 的 Qwen3-0.6B 权重约占 1.2 GB。假设显存带宽为 360 GB/s(我使用的 RTX 3060),可以得到下面的上限。2

TPS=Memory BandwidthModel Weight Size=3601.2=300  tok/s\text{TPS} = \frac{\text{Memory Bandwidth}}{\text{Model Weight Size}} = \frac{360}{1.2}=300\;\text{tok/s}
Roofline model for an RTX 3060: performance rises with batch size at 360 GB/s until it reaches 51.2 TFLOP/s at batch 142.Roofline model (RTX 3060)memory-boundcompute-bound0501001502002503002040batch size (= FLOP / byte of weights)TFLOP/sslope = 360 GB/speak = 51.2 TFLOP/sridge pointbatch ≈ 142
拖动滑块调整批大小
Batch 8 · memory-bound · ≤ 2,400 tokens/s批大小 8 · 受显存带宽限制 · ≤ 2,400 token/s

But that’s only for one sequence! Small requests don’t saturate our compute cores, and are bottlenecked by our memory bandwidth. We can usually increase our batch size (which reuses each weight read across the whole batch) and increase our total tok/s roughly proportionally3 (to a point, until compute dominates).4

这个估算只适用于一条序列。请求少时,计算核心用不满,显存带宽成为瓶颈。提高批大小后,从显存读取一次的权重可供全批次复用,总吞吐量通常会近似按比例增加3,直到计算能力成为瓶颈。4

So the first strategy in our serving engine is to:

  1. Maintain a queue of requests
  2. Drain the queue, with some max amount
  3. Generate tokens with (hopefully) more than 1 sequence at once until they’re all done
  4. Output / stream the tokens

所以,推理引擎的第一种批处理策略是:

  1. 维护一个请求队列。
  2. 从队列取出请求,直到达到批大小上限。
  3. 尽可能同时为多条序列生成 token,等整批完成。
  4. 输出 token,或通过流式接口逐步返回。

KV CachingKV 缓存

Attention involves 3 vectors calculated from each embedding: key, query, value. Each one is calculated using a matmul, and is dependent on the output of the previous layer. This makes recomputing an entire sequence particularly expensive.

注意力机制会从每个嵌入生成键、查询和值三个向量。它们各自需要一次矩阵乘法,而且依赖前一层的输出,因此每一步重新计算整条序列的代价很高。

The K and V of previous tokens don’t change when we add a new token! So we can cache them. Since attention is causal (backward looking), we actually don’t need to store queries, since old queries won’t be reused.

加入一个新 token 不会改变此前 token 的 K 和 V,所以可以缓存它们。注意力是因果的,只向前文看。旧的查询向量后续不会再用到,无需保存。

KV cache: reuse past keys, values

KV cache: reuse past keys, values

KV 缓存复用此前 token 的键和值

So with KV caching, we can split up our engine into two phases: prefill (prompt processing), where we attend to every token on every layer, storing the KV cache, and decode, where we use the KV cache to calculate the next token and grow the cache by 1 token.

有了 KV 缓存,引擎可分成两个阶段。预填充阶段处理提示词,在每一层对所有 token 做注意力计算,建立 KV 缓存。解码阶段利用缓存计算下一个 token,并为缓存增加一个 token。

We add positions to the BatchMeta

先在 BatchMeta 中加入位置信息。

 @dataclass
 class BatchMeta:
     lengths: torch.Tensor
+    positions: torch.Tensor

We store our KV cache as two big tensors, zero-allocated once up front:

KV 缓存由两个大张量组成,启动时一次性分配并清零。

@dataclass
class KVCache:
    k: torch.Tensor  # (layers, batch, num_kv_heads, max_len, head_dim)
    v: torch.Tensor

And within the attention mechanism, we write to the KV cache as well as perform attention on it.

在注意力模块里,先写入 KV 缓存,再读取缓存做注意力计算。

-v_expanded = torch.repeat_interleave(v_head, self.groups, dim=1)
-k_expanded = torch.repeat_interleave(k_rope, self.groups, dim=1)
+(k_cache, v_cache) = kv_cache
+rows = torch.arange(nb, device=x.device)[:, None]  # [B, 1]
+k_cache[rows, :, positions] = k_rope.transpose(
+    1, 2
+)  # [B, T, kv_heads, head_dim]
+v_cache[rows, :, positions] = v_head.transpose(
+    1, 2
+)  # [B, T, kv_heads, head_dim]
+
+# mask is (num_batch, num_toks, max_toks), True = blocked: causal by position
+max_toks = int(positions.max()) + 1
+mask = torch.arange(max_toks, device=x.device) > positions[:, :, None]
+k_all = k_cache[:, :, :max_toks, :]  # (nb, kvh, max_toks, hd)
+v_all = v_cache[:, :, :max_toks, :]
+
+v_expanded = torch.repeat_interleave(v_all, self.groups, dim=1)
+k_expanded = torch.repeat_interleave(k_all, self.groups, dim=1)

 att = q_rope @ k_expanded.transpose(2, 3)
-att_masked = att.masked_fill(mask, -torch.inf)
+att_masked = att.masked_fill(mask[:, None], -torch.inf)  # mask over all heads
 att_weights = torch.softmax(
     att_masked / self.head_dim**0.5, dim=-1, dtype=torch.float32
 ).to(x.dtype)

This decreases each decode step from 83.6ms -> 11.2ms (7.5x!)

单步解码从 83.6 ms 降到了 11.2 ms,约快 7.5 倍。

Continuous Batching连续批处理

Static versus continuous batching, slot by slot

Static versus continuous batching, slot by slot

逐槽位对比静态批处理和连续批处理

We can improve our batching methods as well. Currently we wait until all sequences are done, which means long generations will stall short ones. We’ll modify it so the queue is dynamic.

组批还有改进空间。现在要等整批序列全部完成,生成较多 token 的请求会拖住短请求。我们把队列改为动态调度。

If at any step, a sequence ends, it gets removed from the queue and a new one is added in.

每一步只要有一条序列完成,就移出它,并加入一条新序列。

In our code, this means that we’ll need to give each request a “slot” to store its KV cache in, since they can move in and out:

请求可以随时加入或离开,因此代码需要给每个请求分配一个保存 KV 缓存的槽位。

 @dataclass
 class BatchMeta:
     lengths: torch.Tensor
+    slot_ids: torch.Tensor
     positions: torch.Tensor

We’ll store the free_kv slots in the engine

在引擎中保存空闲 KV 槽位 free_kv。

 def __init__(self, model: Model, n_batch=8, max_len=2048):
     self.n_batch = n_batch
     self.max_len = max_len
     self.model = model
-    self.waiting_queue: list[Request] = []
+    self.waiting_queue: deque[Request] = deque()
     self.running: list[RunningReq] = []
+    self.free_kv_slots = [i for i in range(n_batch)]
     self.cache = model.alloc_cache(n_batch, max_len)
     self.prefill = False

On admission, we give it a free KV slot and mark it to prefill

接纳请求时,为它分配一个空闲 KV 槽位,并标记为待预填充。

while self.waiting_queue and len(self.running) < self.n_batch:
    r = self.waiting_queue.popleft()
    new = RunningReq(
        r.req_id,
        list(r.prompt_ids),
        r.max_tokens,
        self.model.eos_token_ids,
        self.free_kv_slots.pop(),
    )
    to_prefill.append(new)
    self.running.append(new)

After processing the tokens:

处理完 token 后执行以下操作。

-for req, t in zip(self.running, next_toks):
-    if req.done:
-        continue  # finished rows still ride along in the batch, but stay silent
+for req, t in next_toks:
     req.toks.append(t)
     req.generated += 1
+
+    if req.done:
+        self.free_kv_slots.append(req.slot)
     toks.append(TokenEvent(req.req_id, t, req.done))

+self.running = [r for r in self.running if not r.done]

Since we’re no longer blocking waiting for our entire batch, TTFT p50 drops from 2241 -> 57 ms (39x). We see similar gains in E2E p50 (3740 -> 1622 ms) and max TPS (150 -> 224). TPOT remains unchanged since we only really change how we schedule, not the engine steps itself.

请求不用再等整批完成,TTFT 的 p50 从 2241 ms 降至 57 ms,约快 39 倍。E2E 的 p50 从 3740 ms 降至 1622 ms,最大吞吐量从 150 增至 224 token/s。TPOT 基本没变,因为优化集中在调度,引擎的单步执行方式没有变化。

This comes at the cost of higher ITL p99 (22.8 -> 75.9), since a new request’s prefill causes a spike and stalls everyone’s decode, which we’ll solve in the next section.

代价是 ITL 的 p99 从 22.8 ms 上升到 75.9 ms。新请求突然进行预填充时,会拖住所有正在解码的请求。下一节解决这个问题。

Chunked Prefill分块预填充

Currently, on admission, we prefill the entire prompt, so our batching strategy looks a little more like this:

目前,请求一被接纳就会一次性预填充整个提示词,组批过程大致如下。

Unchunked prefill stalls every decoding sequence

Unchunked prefill stalls every decoding sequence

不分块的预填充会阻塞所有解码序列

How we choose to schedule our prefills/decode depends on our policy. We’re gonna copy vLLM’s policy here: set a token_budget, representing the amount of tokens we process. Decode always needs a token_budget of 1 (since previous tokens are cached, and we don’t need them), while a prefill’s token_budget is the number of tokens not in the KV Cache yet.

预填充和解码的执行顺序取决于调度策略。这里沿用 vLLM 的方法,设置 token_budget 来限制每步处理的 token 数。每个解码请求只占 1 个 token 的预算,因为先前的 token 已在缓存里。预填充请求需要的预算等于尚未写入 KV 缓存的 token 数。

We prioritize all of the decodes, and then prefill the remaining token_budget tokens. Since decode is memory bound, prefills ride “for free” (up to a certain point).

优先安排全部解码请求,再用剩余预算安排预填充。解码受显存带宽限制,所以只要预填充的计算量适中,就能顺带做掉,几乎不增加耗时。

Since our requests now might not be fully prefilled, we need a way to store how many tokens we have prefilled. We store num_computed, which is the number of prefilled tokens. Note that for all decode, toks - num_computed = 1.

一个请求的提示词现在可能只处理了一部分,所以用 num_computed 记录已计算的 token 数。对于解码请求,toks - num_computed 始终等于 1。

 @dataclass
 class RunningReq:
     req_id: int
     toks: list[int]
     max_tokens: int
     eos_ids: frozenset[int]
     slot: int
     generated: int = 0
+    num_computed: int = 0

We add a core loop to check for the “budget”:

在调度主循环中检查预算。

+while prefill_list and budget > 0:
+    req = prefill_list.popleft()
+    wants = len(req.toks) - req.num_computed
+    b = min(budget, wants)
+    to_prefill.append((req, b))
+    budget -= b

And with this, our ITL p99 goes from 75.9 -> 65.7. It does come at the cost of slightly higher TTFT (57 -> 75.1ms) since we don’t prefill the entire sequence immediately, so long sequences will need to wait multiple steps for their first token.

ITL 的 p99 从 75.9 ms 降到了 65.7 ms。TTFT 则从 57 ms 略升至 75.1 ms,因为长提示词要分几步处理完才能生成首个 token。

Flash AttentionFlashAttention

Currently, our attention is materializing an n×nn \times n matrix. This is bad for 2 reasons:

  1. Moving that huge matrix in and out of HBM/VRAM is slow, which is necessary when the GPU needs to perform ops like softmax
  2. Uses O(n^2) space, which means that running our model will need a lot of free space so that it won’t OOM during inference, decreasing our KV cache size

目前的注意力实现会显式构造一个 n×nn \times n 矩阵,有两个问题。

  1. softmax 等运算需要将这个大矩阵在计算单元和 HBM(显存)之间来回搬运,速度较慢。
  2. 矩阵占用 O(n2)O(n^2) 空间。为避免推理时显存不足,必须为它留出更多空间,可用于 KV 缓存的空间就变小了。

Every query scores against every key

Every query scores against every key

每个查询都与每个键计算相似度

We’ll use fast attention kernels like FlashAttention. The core optimization behind FlashAttention is tiling Q, K and V through on-chip SRAM in one fused kernel, so the n×nn \times n matrix never gets written to HBM/VRAM. What makes that possible is online softmax (running softmax). If we’re able to somehow make an “accumulator” for each row of softmax, we can decrease our memory from O(n^2) to O(n) (one accumulator per row) by calculating an element, updating the accumulator and then discarding it.

我们改用 FlashAttention 这样的高效注意力内核。它的关键做法是在一个融合内核里将 Q、K 和 V 分块送入片上 SRAM,使 n×nn \times n 矩阵无需写入 HBM。能做到这一点,靠的是在线 softmax。只要给每一行维护一个累加状态,就可以计算一个元素、更新状态,再丢弃该元素,把内存开销从 O(n2)O(n^2) 降到 O(n)O(n)。

The hard part is how do we do online softmax. For numerically stable softmax, we need to subtract the maximum value (to prevent overflows)

难点在于如何做在线 softmax。为了避免溢出,数值稳定的 softmax 需要先减去最大值。

exi−max⁡(x)∑jexj−max⁡(x)\frac{e^{x_i-\max(x)}}{\sum_{j} e^{x_j - \max(x)}}

which we don’t know without knowing the full sequence!

但在看完整条序列之前,我们无法确定这个值。

What we can do instead is:

  1. store the running max, and running denominator
  2. on a new element, find the new max and rescale denominator by multiplying eold_max−new_maxe^{\mathrm{old\_max} - \mathrm{new\_max}}

可以这么做:

  1. 保存当前已处理元素的最大值,以及分母的累加值。
  2. 读到新元素后,找出新的最大值,将已有分母乘以 eold_max−new_maxe^{\mathrm{old\_max} - \mathrm{new\_max}},把它换算到新的基准。

Here’s a math visualization of why this works:

下面用公式说明为什么这个换算成立。

(ex1−mold+ex2−mold+ex3−mold)(emold−mnew)=(ex1−mold)(emold−mnew)+(ex2−mold)(emold−mnew)+(ex3−mold)(emold−mnew)=(ex1−mold+mold−mnew)+(ex2−mold+mold−mnew)+(ex3−mold+mold−mnew)=(ex1−mnew+ex2−mnew+ex3−mnew)\begin{aligned} &(e^{x_{1} - m_{old}} + e^{x_{2} - m_{old}} + e^{x_{3} - m_{old}})(e^{m_{old} - m_{new}}) \\ &= (e^{x_{1}-m_{old}})(e^{m_{old}-m_{new}}) + (e^{x_{2}-m_{old}})(e^{m_{old}-m_{new}}) + (e^{x_{3}-m_{old}})(e^{m_{old}-m_{new}}) \\ &= (e^{x_{1}-m_{old}+m_{old}-m_{new}}) + (e^{x_{2}-m_{old}+m_{old}-m_{new}}) + (e^{x_{3}-m_{old}+m_{old}-m_{new}}) \\ &= (e^{x_{1} - m_{new}} + e^{x_{2} - m_{new}} + e^{x_{3} - m_{new}}) \end{aligned}

However, we still would need a value for each element of the row for the numerator! But remembering that attention multiplies each softmax value by their respective value vectors, we realize:

分子似乎仍需要这一行的每个元素。但注意力会把每个 softmax 权重乘以相应的值向量,因此可以把这些项合并到同一个分子里。

ex1−max⁡(x)∑jexj−max⁡(x)⋅V1+ex2−max⁡(x)∑jexj−max⁡(x)⋅V2+ex3−max⁡(x)∑jexj−max⁡(x)⋅V3=(∑iexi−max⁡(x)⋅Vi)∑jexj−max⁡(x)\begin{aligned} &\frac{e^{x_1-\max(x)}}{\sum_{j} e^{x_j - \max(x)}} \cdot V_{1} + \frac{e^{x_2-\max(x)}}{\sum_{j} e^{x_j - \max(x)}} \cdot V_{2} + \frac{e^{x_3-\max(x)}}{\sum_{j} e^{x_j - \max(x)}} \cdot V_{3} \\ &= \frac{\left( \sum_{i} e^{x_{i} - \max(x)}\cdot V_{i} \right)}{\sum_{j} e^{x_j - \max(x)}} \end{aligned}

And since this sum term also has a max, we can similarly do the rescaling trick we described earlier.5

分子的求和项也依赖最大值,所以同样可以用前面的方法,把累加值换算到新的基准。5

Online softmax allows us to calculate the value one at a time, updating the accumulator, and discarding it. This means we’ll calculate the full n×nn \times n matrix, but we won’t need to materialize the full thing in our memory.

在线 softmax 允许逐个计算、累加并丢弃中间值。我们仍然做了整个 n×nn \times n 矩阵所需的计算,却不用在显存中存下整个矩阵。

We’ll use FlashInfer for our kernels.

我们用 FlashInfer 提供的内核。

Ragged Tensors变长张量

Before we can dive into the implementation, we’ll have to make everything have ragged tensors.6

在开始实现之前,要把相关输入都改成变长张量。6

Padded batch versus ragged CSR layout

Padded batch versus ragged CSR layout

补齐的批次与变长 CSR 布局对比

Ragged tensors store it as two elements: a list of “pointers” and the data. The iith element of the “pointers” is where the iith data starts in the data list. The i+1i+1th element of pointers is where the iith data ends (non-inclusive). In other words, data_ptr stores the ranges of each piece of data.

变长张量由一组偏移量和一组数据组成。第 ii 个偏移量指出第 ii 段数据在数据数组中的起点,第 i+1i+1 个指出它的终点(不含)。也就是说,data_ptr 记录每段数据在数组里占用的区间。

This is optimal because it allows us to avoid padding uneven sequences into a tensor, saving us memory. Many attention kernels, FlashInfer’s included, use this layout.

这种布局无需把不同长度的序列补齐到同一个张量,省下了显存。包括 FlashInfer 在内,很多注意力内核都使用这种布局。


+indptr = torch.nn.functional.pad(meta.lengths.cumsum(0), (1, 0)).int()
+paged_kv_indptr = torch.arange(len(meta.slot_ids) + 1).int()
+paged_kv_indices = meta.slot_ids.int()
+last_page_lens = (meta.positions[:, 0] + meta.lengths).int()
+self.prefill_wrapper.plan(
+    indptr,
+    paged_kv_indptr,
+    paged_kv_indices,
+    last_page_lens,
+    self.cfg.num_attention_heads,
+    self.cfg.num_key_value_heads,
+    self.cfg.head_dim,
+    kv_cache.k.shape[3],
+    causal=True,
+    q_data_type=self.embed_tokens.weight.dtype,
+)

FlashInfer requires us to call plan() first with the indptr (the pointer part of the input_ids ragged tensor), as well as a ragged tensor of where the paged_kv lives7. For now, each slot is just one giant page of size max_len; we’ll make real pages later.

调用 FlashInfer 时,首先执行 plan(),传入 indptr(input_ids 变长张量的偏移数组),以及指明分页 KV 位置的变长张量。7 当前每个槽位仍是大小为 max_len 的一个大页,稍后再实现真正的分页。

+rows = meta.slot_ids.repeat_interleave(meta.lengths)
+k_cache[rows, :, positions] = k_rope
+v_cache[rows, :, positions] = v_head
+
+out = prefill_wrapper.run(q_rope, (k_cache, v_cache))  # (N, qh, hd)

Once we’ve stored into the KV cache, we just call FlashInfer’s kernel on it to get our value.

数据写入 KV 缓存后,直接调用 FlashInfer 的内核得到注意力输出。

This new attention kernel (and getting rid of padding) speeds up our prefill, bringing our p99 latency from 191 -> 72.6ms.

新的注意力内核加上去除填充,让预填充更快,p99 延迟从 191 ms 降到 72.6 ms。

Thanks to the optimizations with ragged tensors + more optimized kernels, it also has an impact on our decode, bringing our TPOT p50 from 18.1 -> 10.6 ms and p99 from 29.4 -> 12.1. Because we’re speeding up how long it takes to calculate a token, it also helps out with E2E, max TPS, and ITL.

变长张量和更高效的内核也加快了解码。TPOT 的 p50 从 18.1 ms 降至 10.6 ms,p99 从 29.4 ms 降至 12.1 ms。单个 token 的计算时间缩短,也改善了 E2E、最大吞吐量和 ITL。

Paged KV Cache分页 KV 缓存

Our current KV Cache allocates the maximum size for a fixed seq length, which is correct, but inefficient, since most requests will not be at maximum context length.

当前的 KV 缓存按固定序列长度的上限分配。计算结果正确,但大多数请求用不到最大上下文长度,所以这会浪费显存。

Contiguous KV fragments; paged blocks fit

Contiguous KV fragments; paged blocks fit

连续 KV 缓存容易产生碎片,分页块可以填入空闲页

We need a way of dynamically allocating KV cache. However, instead of the current approach with contiguous chunks (which will require dynamic resizing, leading to fragmentation), we’ll store small pages, and an overall KV is a collection of these small pages8. We only allocate the pages a request actually uses, so many more requests fit at once without over-provisioning. It also gives us an easy way to re-use KV across requests (which we’ll cover soon, called prefix caching).

我们需要动态分配 KV 缓存。连续分配的大块空间在动态调整时容易产生碎片,所以这里改用小页,把每个请求的 KV 缓存存成一组小页。8 只分配请求实际用到的页,可以避免预留过多,让更多请求同时运行。分页也便于在不同请求之间复用 KV,这就是后文的前缀缓存。

We change the shape of our KV cache:

修改 KV 缓存的张量形状。

+@dataclass
+class PagedKVCache:
+    kv: torch.Tensor  # (layers, num_blocks, 2, num_kv_heads, block_size, head_dim)
+
+    @classmethod
+    def alloc(
+        cls, layers, num_pages, num_kv_heads, page_size, head_dim, device, dtype
+    ) -> Self:
+        return cls(
+            torch.zeros(
+                (layers, num_pages, 2, num_kv_heads, page_size, head_dim),
+                dtype=dtype,
+                device=device,
+            )
+        )

Now that we have more complex paging mechanism, the engine needs to be the one calculating much of the attention metadata:

分页机制复杂后,注意力相关的许多元数据要由引擎计算。

 @dataclass
 class BatchMeta:
     lengths: torch.Tensor
-    slot_ids: torch.Tensor
+    paged_kv_indptr: torch.Tensor
+    paged_kv_indices: torch.Tensor
+    slot_mappings: torch.Tensor
     positions: torch.Tensor
+    indptr: torch.Tensor
+    last_page_lens: torch.Tensor
+    page_size: int

Our engine will now need to:

  1. On admission, allocate KV cache
  2. On completion, deallocating
  3. Preempt if there’s not enough space

现在引擎需要做到:

  1. 接纳时分配 KV 缓存。
  2. 请求完成时释放缓存。
  3. 空间不足时抢占请求。

Preemption for this engine will mean putting back into the waiting queue, and re-prefilling once there’s enough space.

在这个引擎里,抢占是指将请求放回等待队列,有足够空间后再做预填充。

# 1) admission: only admit if the prompt's pages fit
while self.waiting_queue:
    r = self.waiting_queue[0]
    num_pages_needed = ceil((len(r.prompt_ids)) / self.page_size)
    # keep one free page per running request, so each can cross its next
    # page boundary before anyone needs preempting
    reserve = len(self.running)
    if num_pages_needed + reserve <= len(self.free_kv_slots):
        new = RunningReq(
            r.req_id,
            list(r.prompt_ids),
            r.max_tokens,
            self.model.eos_token_ids,
            [self.free_kv_slots.popleft() for _ in range(num_pages_needed)],
        )
        self.running.append(new)
        self.waiting_queue.popleft()
    else:
        break
# 2) completion: give the pages back
if req.done:
    self.free_kv_slots.extend(req.pages_idx)
# 3) a decode crossing into a new page, with no free page left: preempt
if len(r.toks) > self.page_size * len(r.pages_idx):
    if self.free_kv_slots:
        r.pages_idx.append(self.free_kv_slots.popleft())
    else:
        # find the last
        idx = -1
        while self.running[idx].req_id in preempted:
            idx -= 1
        to_preempt = self.running[idx]

        self.free_kv_slots.extend(to_preempt.pages_idx)
        self.waiting_queue.appendleft(
            Request(
                to_preempt.req_id,
                to_preempt.toks,
                to_preempt.max_tokens - to_preempt.generated,
                -1,
            )
        )
        preempted.add(to_preempt.req_id)
        if to_preempt.req_id == r.req_id:
            # self preemption
            break
        else:
            r.pages_idx.append(self.free_kv_slots.popleft())

Now our engine handles more concurrent requests with the same amount of memory. Before, we fixed it at n_batch=8 and we reserved the whole max_len=2048 of KV cache, which will very rarely be fully utilized. Our paged KV cache allows each request to take a dynamic amount of memory. This increases our max TPS from 577 -> 1315 tok/s, while other metrics remain the same.

现在,同样的显存能支持更多并发请求。之前批大小固定为 n_batch=8,每个请求预留 max_len=2048 的全部 KV 缓存,却很少用满。分页之后,每个请求按实际需要占用显存。最大吞吐量从 577 增至 1315 token/s,其他指标基本不变。

Prefix Caching前缀缓存

A token’s KV only depends on the tokens before it, so prompts that share a prefix have the same KV for that prefix. So we can use this to find common prefixes between our requests, and share the KV cache between them.

一个 token 的 KV 只依赖它前面的 token,所以具有相同前缀的提示词,在这一段的 KV 也相同。我们可以查找多个请求的公共前缀,让它们共享这段 KV 缓存。

Prefix caching: hash chains over full blocks

Prefix caching: hash chains over full blocks

前缀缓存:对完整的块构建哈希链

We’re going to do vLLM-style hash-based prefix lookups.9 Each block is hashed based on the previous block’s hash and its current token ids. When we admit a request, we similarly compute its block hashes to find the longest prefix match, and instead of recomputing, mark the prefix computed and use those blocks.

我们采用 vLLM 式的哈希前缀查找。9 每个块的哈希由前一个块的哈希和当前块的 token ID 得出。接纳请求时,同样计算各块的哈希,找到可匹配的最长前缀,将这段标记为已计算,直接使用对应的块。

Note that blocks that aren’t 100% full won’t be counted, since they might still be written into.

尚未完全填满的块暂不纳入查找,因为后续还有可能继续写入。

Block pool: ref counts, free queue

Block pool: ref counts, free queue

块池:引用计数和空闲队列

We use ref-counting because many requests might be sharing a block. One thing to note: we maintain a deque for the free blocks. When a used block is free (ref count goes down to 0), we put it to the end of free queue. When we need a new block, we pop from the start of the free queue. This allows for recent requests to keep their cache “warm” for longer, which is natural for turn-based conversations, agents, etc.

多个请求可能共用一个块,所以要记录引用计数。我们还用双端队列保存空闲块。当某个在用块的引用计数降为零时,将它放到空闲队列末尾。需要新块时,从队首取出。这样近期请求的缓存可保留更久,符合多轮对话、智能体等负载的行为。

+@dataclass
+class Block:
+    hash: int
+    block_idx: int
+    ref_count: int
+
 @dataclass
 class RunningReq:
     req_id: int
     toks: list[int]
     max_tokens: int
     eos_ids: frozenset[int]
-    pages_idx: list[int]
+    pages: list[Block]
     generated: int = 0
     num_computed: int = 0

We’ll store a way to lookup blocks by dict:

用字典保存用于查找的缓存块。

+self.hash_to_blocks = {}

Here’s the code for the hashing scheme:

下面是计算哈希的代码。

# (after the forward, for each page that just filled up)
# hash the blocks
for i in range(
    req.num_computed // self.page_size,
    (req.num_computed + b) // self.page_size,
):
    # starting block
    prev_hash = None
    if i > 0:
        prev_hash = req.pages[i - 1].hash

    h = hash(
        (
            prev_hash,
            tuple(
                req.toks[i * self.page_size : (i + 1) * self.page_size]
            ),
        )
    )
    req.pages[i].hash = h

    # keep the first block registered for h; a later duplicate stays private
    self.hash_to_blocks.setdefault(h, req.pages[i])

We’ll change the free queue to handle O(1) deletions from anywhere, which is possible now when a match is found

匹配到缓存块时,可能需要从队列中间将它移出。因此把空闲队列改为支持从任意位置做 O(1)O(1) 删除。

-self.free_kv_slots = deque(range(num_pages))
+self.free_kv_slots = OrderedDict(
+    {i: Block(None, i, 0) for i in range(num_pages)}
+)

On admission, we hash the sequence and greedily find the longest prefix match, using those blocks and increasing their refcount by 1, with a special case if that takes a block out of the free queue.

接纳请求时,对序列分块计算哈希,贪心查找最长匹配前缀,复用这些块并把引用计数加一。如果命中的块原本在空闲队列中,还要把它移出队列。

# greedy match
prev_hash = None
for i in range((len(r.prompt_ids) - 1) // self.page_size):
    t = r.prompt_ids[i * self.page_size : (i + 1) * self.page_size]
    h = hash((prev_hash, tuple(t)))
    prev_hash = h
    if h in self.hash_to_blocks:
        b = self.hash_to_blocks[h]
        pages.append(b)
        if b.ref_count == 0:
            del self.free_kv_slots[b.block_idx]
        num_pages_needed -= 1
        num_computed += self.page_size
        b.ref_count += 1

    else:
        break

for _ in range(num_pages_needed):
    _, blk = self.free_kv_slots.popitem(last=False)
    # only drop the map entry if it points to this block (a duplicate copy
    # of the same prefix shares the hash but isn't the registered one)
    if self.hash_to_blocks.get(blk.hash) is blk:
        del self.hash_to_blocks[blk.hash]
    blk.hash = None
    blk.ref_count += 1
    pages.append(blk)

On completion, we decrease the ref count of the block. Special care is handled if refcount drops to 0, which means it’s free again

请求完成后,将引用计数减一。降为零时,块再次变为空闲,需要将它放回空闲队列。

 if req.done:
-    self.free_kv_slots.extend(req.pages_idx)
+    for blk in reversed(req.pages):
+        blk.ref_count -= 1
+        if blk.ref_count == 0:
+            self.free_kv_slots[blk.block_idx] = blk

We’ll make a special benchmark for this, a shared-prefix workload (which is very similar to real world multi-turn chat workloads & system prompts). On this new workload, TTFT p50 goes from 47 -> 17.8 ms and p99 98 -> 31ms.

我们专门加入共享前缀负载做测试。它接近多轮对话和共享系统提示词的实际场景。在这个负载下,TTFT 的 p50 从 47 ms 降至 17.8 ms,p99 从 98 ms 降至 31 ms。

CUDA GraphsCUDA 图

Eager launches versus one CUDA graph

Eager launches versus one CUDA graph

普通即时调用与一次 CUDA 图重放对比

Right now, we’re executing in eager mode, meaning our PyTorch code is going step by step, queuing kernels. The problem is that the time it takes to prepare + launch the kernel is longer than it takes for the GPU to run the kernel! So we are overhead bound, and our GPU is sitting idle waiting for the next instruction.

目前使用的是 eager(即时执行)模式,PyTorch 会逐步提交 GPU 内核。问题在于,CPU 准备并发起内核的时间,甚至长于 GPU 执行它的时间。瓶颈变成了启动开销,GPU 只能空等下一条指令。

CUDA Graphs solves that. You can record a series of kernel launches, and then instantly replay with no additional CPU work. The only constraint is that everything has to be the same: the same GPU buffers, same buffer sizes, same kernels, etc. These restrictions only make it feasible for decode, where the input shapes are consistent (1 token per request).

CUDA 图可以先捕获一系列内核调用,再直接重放,CPU 无需逐个准备。约束是重放时必须使用相同的 GPU 缓冲区、相同的大小、相同的内核等。解码阶段每个请求只有一个 token,输入形状一致,才适合这样做。

Since buffer sizes have to be the same, we will record at batch size 1, 2, 4, 8, 16, 32, 64. We will then find the nearest one, and pad our inputs up to that batch size and replay the graph. The padding rows write into a reserved “dummy” KV cache page, so they never touch a real request’s cache.

由于缓冲区大小必须固定,我们为批大小 1、2、4、8、16、32 和 64 分别捕获 CUDA 图。执行时选择能容纳当前批次的最小档位,将输入补齐后重放。补齐的行只写入专门预留的虚拟 KV 页,避免碰到实际请求的缓存。

One thing to note: since our policy can mix prefills and decodes, if there’s ever a mixed batch, our graph can’t handle that.10

我们的策略允许在一个批次中混合预填充和解码,而这样的混合批次无法使用这套 CUDA 图。10

We keep static GPU buffers (input ids, positions, slot mappings, page tables) allocated once at the biggest batch size. Each step copies its batch into them, since a graph can only read from the addresses it was recorded with.

输入 ID、位置、槽位映射和页表等 GPU 缓冲区按最大批大小一次性分配。每一步将当前批次复制进去,因为 CUDA 图只能读取捕获时记录的地址。

We’ll make a function that records decode graphs:

编写一个捕获解码图的函数。

for b in reversed(self.buckets):
    decode = BatchDecodeWithPagedKVCacheWrapper(
        self.ws,
        kv_layout="HND",
        use_cuda_graph=True,
        use_tensor_cores=True,
        paged_kv_indptr_buffer=self.data.paged_kv_indptr_gpu[: b + 1],
        paged_kv_indices_buffer=self.data.paged_kv_indices_gpu,
        paged_kv_last_page_len_buffer=self.data.last_page_lens_gpu[:b],
    )

    # meta = a dummy batch of b decodes
    meta_gpu = self.data.view(meta, b)
    decode.plan(...)

    with torch.inference_mode():
        # warmup:
        for _ in range(3):
            self.net(self.data.input_ids_gpu[:b], meta_gpu, kv_cache, decode)

        g = torch.cuda.CUDAGraph()
        with torch.cuda.graph(g, pool=mem_pool):
            out = self.net(
                self.data.input_ids_gpu[:b], meta_gpu, kv_cache, decode
            )

    output[b] = (decode, g, out)

We’ll allow decode-only requests to pad, and look up decode requests

允许纯解码批次补齐到可重放的大小,并为它查找相应的 CUDA 图。

 self.free_kv_slots = OrderedDict(
-    {i: Block(None, i, 0) for i in range(num_pages)}
+    # page 0 is the dummy page the CUDA graphs' padding rows write into
+    {i: Block(None, i, 0) for i in range(1, num_pages)}
 )
if nt == b and nt <= self.max_buckets:
    # we can replay a graph

    # find max graph we can calc
    pad_buckets = self.buckets[bisect_left(self.buckets, nt)]
    return self.replay_graph(input_ids, meta, kv_cache, pad_buckets)

else:
    # eager mode
def replay_graph(self, input_ids, meta, kv_cache, pad_to):
    nt = input_ids.shape[0]
    self.data.view(meta, pad_to)  # copy this batch into the static buffers
    self.data.input_ids_gpu[:nt].copy_(input_ids)

    (decode_wrapper, g, out) = self.graphs[pad_to]
    # pad indptr / indices / last_page_lens so rows nt..pad_to point at the dummy page
    decode_wrapper.plan(...)

    g.replay()
    return out[:nt]

Since this optimizes our decode step, it mainly affects TPOT, with p50 going from 9.6 -> 6.7 (-30%), and consequently ITL (p99 23.3 -> 17.1), E2E and max TPS.

这项优化主要加快解码。TPOT 的 p50 从 9.6 ms 降至 6.7 ms,约下降 30%。ITL 的 p99 也从 23.3 ms 降到 17.1 ms,E2E 和最大吞吐量都有改善。

Overlap Scheduling重叠调度

Overlap: CPU runs one step ahead

Overlap: CPU runs one step ahead

重叠调度:CPU 提前执行一步

Currently, our code runs a forward pass, waits for the GPU to finish, appends the tokens, and repeats. But we waste time by waiting for the GPU. During this time, we can do CPU computation (attention kernel planning, shuffling buffers, etc) and queue up the n+1n + 1‘th step.

现在,代码先发起一次前向计算,等 GPU 完成,再把生成的 token 追加到序列,重复这一循环。等待 GPU 的时间可以用来在 CPU 上做注意力内核规划、整理缓冲区等工作,并将第 n+1n+1 步排入 GPU 队列。

This reduces “bubbling” (idle gaps on GPU waiting for CPU)

这样可以减少 GPU 等待 CPU 的空闲间隙,也就是调度气泡。

A consequence of this is that we process step n, and we realize it’s already done, but we’ve already launched the kernels for step n+1! There is some slightly wasted computation, but since output sequence lengths are usually long, an extra token won’t be much. We discard it safely.

因此我们可能在取回第 nn 步结果时才发现请求已完成,可第 n+1n+1 步的内核早已启动。这会浪费少量计算,但输出序列通常较长,多算一个 token 的开销不大,安全丢弃即可。

This will require us refactoring to the following structure

为此,把代码重构为以下结构。

def step():
    new = schedule()             # build + launch step N+1, don't wait for it
    out = []
    if in_flight is not None:
        out = process(*in_flight)  # wait for step N, append its tokens
    in_flight = new
    return out

def schedule():
    admit, pick decodes + prefill chunks (counting num_scheduled as already done)
    input_ids = known tokens from CPU, placeholders for tokens step N hasn't returned
    fill placeholders on the GPU from step N's argmax
    out = model.forward(input_ids, meta, cache)    # async
    next_gpu = out.argmax(-1)                     # stays on GPU for step N+2
    next_cpu = copy next_gpu to CPU (non_blocking) + record an event
    return to_process, next_gpu, next_cpu, event

def process(to_process, next_gpu, next_cpu, event):
    event.synchronize()                           # waits for N only
    append tokens, hash full pages, free finished requests

Each request also tracks num_scheduled (tokens launched but not processed yet), so the scheduler counts in-flight work as already done. The tricky part is that step N+1’s inputs include tokens step N hasn’t produced yet. We leave placeholders and fill them on the GPU straight from N’s argmax:

每个请求还记录 num_scheduled,即已提交、尚未处理的 token 数。调度器把正在执行的工作也计入进度。难点在于,第 N+1 步的输入需要第 N 步还没生成的 token。我们先留出占位符,再直接在 GPU 上用第 N 步的 argmax 结果填进去。

row_of = {}
if self.in_flight is not None:
    prev_batch = self.in_flight[0]  # to_process
    row_of = {r.req_id: j for j, (r, b) in enumerate(prev_batch)}

if to_process:
    ids, dst, src = [], [], []
    for x, b in to_process:
        start = x.num_computed + x.num_scheduled - b
        if start < len(x.toks):
            ids.extend(x.toks[start : start + b])  # known, from the CPU
        else:
            dst.append(len(ids))  # flat position in the packed input
            src.append(row_of[x.req_id])  # r's row in N
            ids.append(0)  # placeholder

    # pinned + non_blocking: a blocking copy would wait for step N to finish
    ids_gpu = torch.tensor(ids).pin_memory().to(self.device, non_blocking=True)
    if dst:
        dst_gpu = (
            torch.tensor(dst).pin_memory().to(self.device, non_blocking=True)
        )
        src_gpu = (
            torch.tensor(src).pin_memory().to(self.device, non_blocking=True)
        )
        ids_gpu[dst_gpu] = self.in_flight[1][src_gpu]

This didn’t do as much as I would have expected, likely since CUDA graphs already helped us a lot. Perhaps our decode steps are also a little too short to gain full benefit from it, which is likely the result of using a tiny 0.6B model.

这项改动带来的收益低于我的预期,可能是因为 CUDA 图已经省掉了不少开销。也可能是 0.6B 模型太小,解码步本身太短,重叠起来省不了多少。

However, under load (8 req/s, shared prefix), our ITL p99 drops from 16.2 -> 12.3 ms and TPOT p99 from 9.2 -> 8.3 ms. This is likely because under load, more steps mix prefills with decodes. Those steps run eagerly (no CUDA graph) and need more scheduling work, so there’s more CPU time per step for overlapping to hide.

不过,在每秒 8 个请求且共享前缀的负载下,ITL 的 p99 从 16.2 ms 降至 12.3 ms,TPOT 的 p99 从 9.2 ms 降至 8.3 ms。负载增加后,更多步骤混合了预填充和解码,只能用 eager 模式,不能用 CUDA 图,调度的工作量也更大。因此 CPU 每步有更多耗时能够被重叠调度隐藏。

It isn’t a free win though: TTFT got worse, with p99 going 66.7 -> 75.8 ms on the main benchmark and p50 17.0 -> 22.4 ms on the shared-prefix one.

TTFT 则有所退步。在主基准中,p99 从 66.7 ms 升至 75.8 ms。在共享前缀基准中,p50 从 17.0 ms 升至 22.4 ms。

torch.compiletorch.compile 编译

PyTorch eager mode runs separate kernels for each operation, reading & writing to HBM many times. torch.compile() takes it and fuses the kernels together11, to make only one trip.

PyTorch 的 eager 模式为每个操作启动独立的内核,反复读写 HBM。torch.compile() 将这些内核融合11,整个过程只需读入和写回一次。

Fusion: fewer round trips to memory

Fusion: fewer round trips to memory

内核融合减少数据往返显存

Compiling is one line:

编译只需一行。

self.net.forward = torch.compile(self.net.forward, dynamic=True)

and we disable optimizations for some non-PyTorch native steps in attention12:

注意力中的几个非 PyTorch 原生步骤需要关闭该优化。12

@torch.compiler.disable
def _write_kv_and_attend(meta, kv_cache, k_rope, v_head, q_rope, wrapper):
    page_idx = meta.slot_mappings // meta.page_size
    offset_idx = meta.slot_mappings % meta.page_size
    kv_cache[page_idx, 0, :, offset_idx] = k_rope
    kv_cache[page_idx, 1, :, offset_idx] = v_head
    return wrapper.run(q_rope, kv_cache)

We’ll also tune our parameters with a quick hand sweep. Raising token_budget 512 -> 2048 is the big one: when lots of requests arrive at once, each step can prefill more of them. We also bump num_pages 2048 -> 4096 (enough for the whole benchmark) and record CUDA graphs up to batch 128.

我们也手动试调了几组参数。最主要的是把 token_budget 从 512 提至 2048。大量请求同时到达时,每步便可为更多请求做预填充。此外,把 num_pages 从 2048 提至 4096,足够覆盖整个基准,并把捕获 CUDA 图的批大小上限提高到 128。

At 1.8 req/s, compile does almost all of the work: on its own it takes TPOT p50 from 6.1 -> 4.6ms and TTFT p50 from 39 -> 27ms, and tuning barely moves those. Tuning matters at max load instead: compile alone takes max TPS from 1451 -> 1911, and tuning gets the rest of the way to 2143. Together, that puts us right next to vLLM on throughput.

每秒 1.8 个请求时,优化收益几乎都来自编译。仅编译就能让 TPOT 的 p50 从 6.1 ms 降至 4.6 ms,TTFT 的 p50 从 39 ms 降至 27 ms,参数调整影响很小。参数调整的价值体现在满负载。仅编译让最大吞吐量从 1451 增至 1911 token/s,再经调参提高到 2143 token/s,已经接近 vLLM。

Final Results最终结果

The serve benchmark above only has about one request in flight at a time, so I also swept the arrival rate from 1 to 16 req/s. At low load we’re 0.3-0.5 ms/token behind both engines, but as batches grow, the overhead gets spread across more tokens. By 8 req/s we’re ahead of vLLM, and we stay within ~6% of SGLang.

前面的 serve 基准平均约只有一个正在处理的请求。因此,我还以每秒 1 至 16 个请求的到达率做了扫描。低负载下,我们比两个引擎都慢 0.3–0.5 ms/token。批次变大后,固定开销分摊到更多 token。达到每秒 8 个请求时,我们超过了 vLLM,并与 SGLang 保持在约 6% 的差距内。

Load sweep: TPOT vs arrival rate

Load sweep: TPOT vs arrival rate

负载扫描:不同请求到达率下的每 token 耗时

Conclusion结论

We roughly 14x’d our tok/s at max load in 8 steps (150 -> 2143), and our TTFT p50 went from 2241 to 24ms.

经过 8 步优化,满负载下的吞吐量提高到原来的约 14 倍,从 150 增至 2143 token/s。TTFT 的 p50 从 2241 ms 降到了 24 ms。

Big TPOT gains came mainly from kernel/engine work, whereas TTFT and ITL were usually shaped by scheduling decisions. On the same 3060, we’re currently at about 98% of vLLM’s throughput. In the future, we’ll try techniques like speculative decoding, and maybe try this engine on bigger models & GPUs, which will require all sorts of parallelism techniques across GPUs.

TPOT 的主要收益来自内核和引擎优化。TTFT 和 ITL 通常更受调度决策影响。在同一块 RTX 3060 上,我们的吞吐量现在约为 vLLM 的 98%。接下来会尝试推测解码等方法,也可能把引擎用到更大的模型和更多的 GPU 上,那时就需要多种跨 GPU 并行技术。

Implementing all of the rungs was very fun. The concepts were simple, but deciding how the server should behave under load is the hard part. It’s extremely easy to come up with policies that have great average latencies / throughputs, but terrible tails due to starvation.

逐步实现这些优化很有意思。概念本身不复杂,困难在于决定服务承压时应该怎样调度。很容易找到平均延迟和吞吐都很好看的策略,却让部分请求因长期得不到执行机会而出现糟糕的尾延迟。

I really enjoyed writing this, and I hope you learnt something from this too :)

我很享受写这篇文章的过程,也希望你读完有所收获 :)

Acknowledgements致谢

Thanks to Ian and Daniel for reading over a draft of this post.

感谢 Ian 和 Daniel 阅读本文初稿。

Resources参考资料

Appendix: Full Results附录:完整结果

Serve, random prompts at 1.8 req/s, plus max TPS (ms, p50 / p90 / p99)

服务基准:每秒 1.8 个随机提示词请求,另列最大吞吐量(延迟单位为 ms,按 p50、p90、p99 排列)

Implementation
实现
TTFT ↗TPOT ↗ITL ↗E2E ↗max TPS
最大吞吐量 ↗
naive
朴素实现
(too slow to count)
运行过慢,未计量
(too slow to count)
运行过慢,未计量
(too slow to count)
运行过慢,未计量
(too slow to count)
运行过慢,未计量
(too slow to count)
运行过慢,未计量
kv cache
KV 缓存
2241 / 4767 / 758918.1 / 21.5 / 29.118.1 / 21.5 / 22.83740 / 7422 / 9642150
continuous
连续批处理
57.2 / 97.6 / 18417.9 / 23.9 / 28.916.1 / 24.4 / 75.91622 / 3852 / 4640224
chunked
分块预填充
75.1 / 143 / 19118.1 / 24.2 / 29.416.4 / 25.4 / 65.71616 / 3863 / 4582222
flash-attn
FlashAttention
42.1 / 61.1 / 72.610.6 / 11.3 / 12.110.2 / 11.6 / 26.4884 / 2169 / 2454577
paged
分页 KV
41.0 / 59.7 / 70.29.6 / 10.8 / 12.09.0 / 10.7 / 23.1808 / 1924 / 21441315
prefix
前缀缓存
41.4 / 59.9 / 70.79.6 / 10.3 / 11.29.2 / 10.7 / 23.3858 / 1974 / 22321296
graphs
CUDA 图
40.4 / 56.9 / 66.76.7 / 7.4 / 8.76.5 / 6.9 / 17.1588 / 1403 / 16351380
overlap
重叠调度
39.1 / 61.0 / 75.86.1 / 6.8 / 7.26.0 / 6.3 / 16.3550 / 1299 / 15061451
compile + tuned
编译并调参
24.1 / 33.5 / 48.14.7 / 5.3 / 5.94.5 / 4.9 / 8.8428 / 975 / 11492143
vLLM24.9 / 34.9 / 46.04.2 / 4.6 / 4.84.3 / 4.6 / 5.2381 / 908 / 10392176
SGLang24.3 / 34.3 / 46.24.0 / 4.4 / 5.04.0 / 4.3 / 6.0355 / 848 / 9882187

Serve, shared prefix (384 shared + ~128 own tokens) at 8 req/s (ms, p50 / p90 / p99)

服务基准:每秒 8 个共享前缀请求,共用 384 token,各自另有约 128 token(延迟单位为 ms,按 p50、p90、p99 排列)

Implementation
实现
TTFT ↗TPOTITLE2Eout tok/s
输出 token/s
paged (no prefix cache)
分页 KV(关闭前缀缓存)
47.0 / 70.8 / 97.911.6 / 13.7 / 31.79.9 / 12.4 / 32.5926 / 2219 / 2796601
prefix
前缀缓存
17.8 / 23.4 / 30.89.2 / 10.1 / 11.98.7 / 10.5 / 16.3757 / 1709 / 2090619
graphs
CUDA 图
17.0 / 21.4 / 28.27.2 / 7.9 / 9.26.9 / 7.6 / 16.2607 / 1352 / 1689636
overlap
重叠调度
22.4 / 27.0 / 33.86.6 / 7.1 / 8.36.4 / 7.1 / 12.3538 / 1236 / 1522633
compile + tuned
编译并调参
16.0 / 18.9 / 23.54.9 / 5.2 / 5.84.8 / 5.1 / 9.5382 / 910 / 1138623
vLLM18.0 / 20.9 / 26.34.7 / 5.0 / 6.14.6 / 4.9 / 10.4359 / 878 / 1123610
SGLang17.7 / 21.5 / 25.84.4 / 4.8 / 7.14.2 / 4.5 / 12.2351 / 843 / 1051641

Latency, closed loop: batch 8, 128 in / 64 out (ms, p50 / p90 / p99)

闭环延迟基准:批大小 8,输入 128 token,输出 64 token(延迟单位为 ms,按 p50、p90、p99 排列)

Implementation
实现
decode step
解码步 ↗
prefill
预填充
batch
整批 ↗
naive
朴素实现
83.6 / 99.9 / 10366.0 / 66.1 / 66.15482 / 5483 / 5484
kv cache
KV 缓存
11.2 / 12.3 / 12.868.0 / 68.9 / 69.1793 / 796 / 797
continuous
连续批处理
12.3 / 13.0 / 13.970.1 / 70.1 / 70.1846 / 847 / 847
chunked
分块预填充
12.8 / 13.5 / 49.038.6 / 38.6 / 38.6910 / 920 / 922
flash-attn
FlashAttention
9.6 / 10.8 / 30.930.6 / 30.7 / 30.8684 / 712 / 718
paged
分页 KV
9.1 / 10.6 / 29.929.4 / 29.5 / 29.5661 / 664 / 665
prefix
前缀缓存
9.4 / 10.4 / 11.211.0 / 11.1 / 11.1*606 / 615 / 617
graphs
CUDA 图
6.7 / 6.9 / 7.112.0 / 12.5 / 12.6435 / 435 / 436
overlap
重叠调度
6.1 / 6.2 / 6.39.3 / 9.7 / 9.8405 / 405 / 405
compile + tuned
编译并调参
4.6 / 4.7 / 4.75.9 / 6.2 / 8.2305 / 306 / 307

*Prefix cache hits: the bench reruns the same prompts.

*此处命中前缀缓存,因为基准会重复运行同一组提示词。

Footnotes

  1. Our engine is benchmarked in-process: the bench driver calls engine.step() directly and timestamps tokens right away, with no HTTP, tokenization or detokenization. vLLM and SGLang are measured through their OpenAI-compatible HTTP servers with streaming. At ~4–5 ms per token that overhead isn’t negligible, so this favors our engine.

    我们的基准直接在同一进程中调用 engine.step(),马上给 token 记录时间戳,不经过 HTTP、分词或反分词。vLLM 和 SGLang 则通过兼容 OpenAI 的 HTTP 服务以流式方式测量。当每个 token 只花 4–5 ms 时,这部分额外开销不可忽略,因此基准对我们的引擎有利。

    ↩ ↩2
  2. 360 GB/s and 51.2 TFLOP/s are the 3060’s spec-sheet numbers, and they’re what the roofline uses. My card is overclocked and measures about 403 GB/s and 55.7 TFLOP/s, so real numbers can land slightly above these estimates.

    360 GB/s 和 51.2 TFLOP/s 是 RTX 3060 的规格数据,也是屋顶线所用的数值。我的卡做了超频,实测约为 403 GB/s 和 55.7 TFLOP/s,因此实测结果可能略高于估算。

    ↩ ↩2
  3. The roofline is an idealized upper bound: it only counts the weight matmuls and assumes kernels reach peak bandwidth and compute. Real decode steps also read each sequence’s own KV cache for attention (which isn’t shared across the batch) and pay kernel-launch overhead, so measured throughput sits below the roof, most of all near the ridge.

    屋顶线给出的是理想上限,只计算权重矩阵乘法,并假设内核能达到峰值带宽和算力。在实际解码中,注意力还要读取每条序列各自的 KV 缓存,无法在批次内共享这部分读取,并且会有内核启动开销。所以实际吞吐量低于屋顶线,在拐点附近差距尤其大。

    ↩ ↩2
  4. The ridge point is peak compute ÷ memory bandwidth: 51.2 TFLOP/s ÷ 360 GB/s ≈ 142 FLOP per byte. Each bf16 weight is 2 bytes and does 2 FLOPs (a multiply and an add) for every sequence in the batch, so a batch of BB does BB FLOPs per byte of weights read, and the ridge sits at a batch of ≈ 142.

    拐点由峰值算力除以显存带宽得到,即 51.2 TFLOP/s÷360 GB/s≈142 FLOP/byte51.2\ \text{TFLOP/s} \div 360\ \text{GB/s} \approx 142\ \text{FLOP/byte}。每个 bf16 权重占 2 字节,对批次中的每条序列执行 2 次浮点运算(一次乘法和一次加法)。因此批大小为 BB 时,每读取 1 字节权重就执行 BB 次浮点运算,拐点对应批大小约为 142。

    ↩ ↩2
  5. This is what makes FlashAttention’s tiling work: each tile’s softmax can be rescaled as later tiles arrive, so Q, K and V stream through on-chip SRAM in one fused kernel and the n×nn \times n score matrix never hits HBM (Dao et al., 2022). FlashAttention-2 then improves work partitioning (fewer non-matmul FLOPs, parallelizing over sequence length, better splitting across warps), and, for decode, Flash-Decoding (Dao, Haziza, Massa & Sizov, 2023) splits the KV sequence across thread blocks.

    这就是 FlashAttention 可以分块计算的原因。后续块到达时,可以对已有块的 softmax 结果重新缩放,让 Q、K 和 V 在同一个融合内核中流经片上 SRAM,n×nn \times n 打分矩阵始终无需写入 HBM(Dao 等,2022)。FlashAttention-2进一步优化任务划分,减少非矩阵乘法运算、沿序列长度并行,并改进 warp 间的划分。解码时,Flash-Decoding(Dao、Haziza、Massa 和 Sizov,2023)会把 KV 序列分给多个线程块。

    ↩ ↩2
  6. Also may be referred to as Compressed Sparse Row (CSR) layout

    这种布局也称为压缩稀疏行(CSR)。

    ↩ ↩2
  7. This is because FlashInfer needs to know the lengths of the sequences to build a load-balanced schedule for the GPU

    FlashInfer 需要知道序列的长度,才能为 GPU 制定负载均衡的调度计划。

    ↩ ↩2
  8. This takes inspiration from virtual memory in operating systems: a table maps each request’s logical KV positions to blocks, the same way a page table maps virtual pages to physical memory (Kwon et al., 2023).

    这借鉴了操作系统的虚拟内存。引擎通过表将每个请求的逻辑 KV 位置映射到物理块,就像页表把虚拟页映射到物理内存一样(Kwon 等,2023)。

    ↩ ↩2
  9. SGLang instead stores cached prefixes in a radix tree (RadixAttention, Zheng et al., 2023). This allows token-level rather than block-level prefix matching, and scheduling policies that use the tree’s structure.

    SGLang 使用基数树保存已缓存的前缀,即 RadixAttention(Zheng 等,2023)。它能逐 token 而非逐块匹配前缀,还可以利用树结构制定调度策略。

    ↩ ↩2
  10. vLLM has a couple ways around this. It can record piecewise graphs for all the ops (since they operate per-token) except attention, which runs eagerly in between. It can also record a full graph, attention included, depending on the attention backend (like FlashAttention3). SGLang avoids this problem since their scheduler doesn’t mix prefill/decode, but that can be changed with --enable-mixed-chunk (thanks to Reese for pointing this out!)

    vLLM 有几种办法。一种是为注意力以外的算子分段捕获 CUDA 图,因为它们按 token 运算,并在图之间以 eager 模式执行注意力。另一种方法视注意力后端而定,例如使用 FlashAttention3 时,可将注意力也捕获到整张图里。SGLang 的调度器默认不混合预填充和解码,因而避开了该问题。通过 --enable-mixed-chunk 可以改变这个行为。感谢 Reese 指出这一点!

    ↩ ↩2
  11. TorchInductor, torch.compile’s default backend, generates Triton kernels on GPU with the fused ops.

    torch.compile 的默认后端 TorchInductor 会为融合后的操作生成 GPU Triton 内核。

    ↩ ↩2
  12. PyTorch optimizations cause the in-place KV write to turn into a copy, update and copy back

    PyTorch 的优化会把原地写入 KV 缓存变成复制、更新、再复制回去。

    ↩ ↩2

Edit page
Share this post:

Comments


Next Post
How to Scale Your Model|如何扩展你的模型