← 人工智能返回顶部

Serving Optimization:推理服务性能优化

LLM Serving Engine 需要同时优化请求调度、KV Cache 内存、GPU 执行效率和多 GPU 分布式推理。

1. 核心技术分类

LLM Serving Engine
│
├── Scheduler
│   ├── Continuous Batching
│   └── Chunked Prefill
│
├── Memory / KV Cache
│   ├── PagedAttention
│   ├── KV Cache Management
│   └── Prefix Caching
│
├── Execution Optimization
│   ├── FlashAttention
│   ├── CUDA Graph
│   └── Speculative Decoding
│
└── Distributed Runtime
    ├── Tensor Parallel(TP)
    ├── Pipeline Parallel(PP)
    ├── Data Parallel(DP)
    ├── Expert Parallel(EP)
    └── Prefill-Decode Disaggregation

2. Continuous Batching

Continuous Batching 允许不同请求在不同时间加入或退出 GPU Batch。

传统 Static Batching:

Batch:
A B C D

A → 20 tokens
B → 100 tokens
C → 300 tokens
D → 500 tokens

固定批处理如果不能动态移除或补充请求,就容易产生无效计算和资源浪费。

Continuous Batching:

Step 1: A B C D
Step 2: E B C D   ← A 完成,E 加入
Step 3: E F C D   ← B 完成,F 加入

主要收益:

  • 提高 GPU Utilization。
  • 提高 Throughput。
  • 减少批处理中的空闲资源。

代价:

  • 更复杂的请求调度。
  • 更多并发请求可能占用更多 KV Cache。
  • 高负载下仍可能增加排队延迟。

Continuous Batching 通常需要与动态 KV Cache Management 配合。

3. Chunked Prefill

长 Prompt 的 Prefill 可能占用 GPU 较长时间,影响已经在 Decode 的请求。

例如:

Request A: Prefill 100K tokens
Request B/C/D: Decode

GPU:
AAAAAAAAAAAAAAAAAAAA
B/C/D 等待

Chunked Prefill 将长 Prompt 分成多个 Chunk:

A1: 2048 tokens
A2: 2048 tokens
A3: 2048 tokens
...

调度器可以在不同调度步骤组合 Prefill 与 Decode:

Step 1: A1 + B/C/D Decode
Step 2: A2 + B/C/D Decode
Step 3: A3 + B/C/D Decode

核心目的是改善 Prefill 与 Decode 之间的调度关系。

可能收益:

  • 降低 Decode 被长 Prefill 阻塞的风险。
  • 改善 TPOT 和 Tail Latency。
  • 提高混合负载下的调度效率。

代价是长 Prompt 的 Prefill 可能需要更多调度轮次,单请求 TTFT 不一定降低。

4. PagedAttention

PagedAttention 将 KV Cache 分成固定大小的 Block,通过逻辑与物理地址映射进行管理。

传统预留方式:

Request A: [Used=====................]
Request B: [Used===========..........]
Request C: [Used==...................]

如果按最大 Context Length 预留显存,会造成大量浪费。

PagedAttention:

Request A:
Logical Block 0 → Physical Block 7
Logical Block 1 → Physical Block 2
Logical Block 2 → Physical Block 9

Request B:
Logical Block 0 → Physical Block 4
Logical Block 1 → Physical Block 1

KV Block 不要求在物理显存中连续。

主要价值:

  • 减少 KV Cache 内存碎片。
  • 避免为每个请求预留完整 Context Length。
  • 按需分配和回收 KV Block。
  • 支持更高并发。
  • 为 Block 级别的 Prefix Sharing 提供基础。

PagedAttention 借鉴了操作系统分页内存管理的思想,但它处理的是 GPU KV Cache。

5. Prefix Cache / Prompt Caching

多个请求如果具有相同的 Token Prefix,可以复用已经计算出的 KV Cache。

例如:

Request A:
[System Prompt] + [Question A]

Request B:
[System Prompt] + [Question B]

共同部分:

System Prompt
      ↓
Prefill
      ↓
Cached KV Blocks
      ├── Request A
      └── Request B

主要收益:

  • 减少重复 Prefill。
  • 降低 TTFT。
  • 降低 GPU 计算开销。

重要限制:

  • 必须满足相应的前缀匹配规则。
  • Prompt 中间相同的一段文本,不一定能够直接作为 Prefix Cache 复用。
  • Chat Template、Token IDs 和模型配置需要兼容。
  • Cache 命中率取决于请求模式。

例如 vLLM 可以根据 KV Block 的 Token 内容及其之前的完整前缀计算缓存标识,实现 Automatic Prefix Caching。

6. KV Cache Management

KV Cache Management 是 Serving Engine 的核心内存管理模块。

需要解决:

KV Cache Manager
├── Allocation
├── Growth
├── Sharing
├── Reuse
├── Eviction
├── Reclamation
└── Memory Pressure Handling

主要问题包括:

  • 哪些请求能够获得 KV Cache?
  • 每个请求分配多少 Block?
  • 请求完成后何时释放?
  • 哪些 Prefix 可以保留?
  • 显存不足时应该驱逐哪些缓存?
  • 是否需要暂停或重新计算部分请求?

KV Cache 是限制长上下文和高并发推理的重要资源。

7. FlashAttention

FlashAttention 优化的是 Attention 的计算过程和 GPU 内存访问。

普通 Attention:

softmax⁡(QKTd)V\operatorname{softmax}\left(\frac{QK^T}{\sqrt{d}}\right)V

如果直接将完整的 Attention Matrix 写入 HBM,会造成大量内存读写。

FlashAttention 使用 Tiling 和 Online Softmax 等方法:

Q Block
K Block
V Block
   ↓
Compute Attention Tile
   ↓
Online Softmax
   ↓
Accumulate Output

尽可能让中间计算在 GPU 的 SRAM / Registers 等更快的片上存储中完成,减少 HBM 访问。

FlashAttention 与 PagedAttention

技术主要优化对象
FlashAttentionAttention Kernel 的计算与 IO
PagedAttentionKV Cache 的分页存储与访问
Prefix Caching重复 Prompt 的 KV 复用

三者可以互相配合,而不是替代关系。

8. Speculative Decoding

普通自回归生成通常需要逐个 Token 执行 Target Model。

Speculative Decoding 先产生多个候选 Token,再让 Target Model 并行验证。

Draft Model(Small)
        ↓
Generate 5 Candidate Tokens
        ↓
Target Model(Large)
        ↓
Verify Candidates
        ↓
Accept Valid Prefix
        ↓
Continue Generation

例如:

Draft:
The capital of France is Paris

Target Verification:
capital ✓
of      ✓
France  ✓
is      ✓
Paris   ×

可以接受符合验证条件的连续前缀,再继续生成。

为什么可能加速?

Target Model 可以在一次验证 Forward 中处理多个候选位置,而不是为每一个候选 Token 单独执行一次完整自回归步骤。

常见方案:

  • Draft Model。
  • N-gram Speculation。
  • EAGLE 等专门的推测生成机制。

代价与限制

  • Draft 生成本身需要计算。
  • 候选接受率低时收益可能很小。
  • Batch 较大时不一定加速。
  • 需要额外的验证和 KV Cache 管理。

在使用正确的接受与校正算法时,Speculative Decoding 可以保持目标模型原始采样分布;但不同实现及近似方案不一定具有完全相同的保证。

核心指标是 Acceptance Rate 和实际获得的 Decode Speedup。

9. Tensor Parallel(TP)

Tensor Parallel 将模型某一层的计算拆分到多张 GPU。

例如:

Transformer Layer
        ↓
Matrix Multiplication
        ├── GPU 0
        ├── GPU 1
        ├── GPU 2
        └── GPU 3
        ↓
Communication / Synchronization

主要用途:

  • 单张 GPU 无法容纳模型。
  • 利用多 GPU 提高单模型计算能力。

代价是 GPU 之间需要频繁通信。

因此 TP 对 GPU 互联带宽和通信库的性能要求较高,例如 NVLink / NVSwitch 和 NCCL。

TP 不保证 GPU 数量翻倍就能获得两倍性能。

10. Pipeline Parallel(PP)

Pipeline Parallel 按模型层划分计算。

例如 80 层模型:

GPU 0: Layers 0–19
GPU 1: Layers 20–39
GPU 2: Layers 40–59
GPU 3: Layers 60–79

执行过程:

Input
  ↓
GPU 0
  ↓
GPU 1
  ↓
GPU 2
  ↓
GPU 3
  ↓
Output

主要价值是把模型分散到多个设备上。

Pipeline Bubble

如果只有一个请求,不同 GPU 可能出现等待:

Time →
GPU 0: A ----
GPU 1:      A ----
GPU 2:           A ----

通过多个 Micro-batch 交错执行,可以提高流水线利用率:

Time →
GPU 0: A → B → C
GPU 1:     A → B → C
GPU 2:         A → B → C

不过流水线方式更适合特定的多请求或多 Micro-batch 负载,不代表单请求延迟一定降低。

11. Data Parallel(DP)

Data Parallel 通过多个模型副本处理不同请求。

Request Queue
      ↓
Load Balancer
      ├── Model Replica 1
      ├── Model Replica 2
      └── Model Replica 3

如果模型能够放入单张 GPU:

GPU 0 → Full Model
GPU 1 → Full Model
GPU 2 → Full Model

如果模型必须使用多张 GPU,也可以复制多个 TP/PP 模型实例。

例如:

TP = 4
DP = 2

Replica A: GPU 0–3
Replica B: GPU 4–7

Total GPUs = 8

主要用途是提高系统总吞吐量与请求处理容量。

DP 通常不能降低单个模型副本的参数规模。

12. Expert Parallel(EP)

Expert Parallel 主要用于 Mixture-of-Experts(MoE)模型。

MoE 模型中,不同 Token 可以通过 Router 选择部分 Expert 参与计算。

Token Hidden State
        ↓
      Router
        ↓
Select Top-k Experts
        ↓
Expert Computation
        ↓
Combine Outputs

Expert Parallel 将不同 Expert 分配到不同 GPU。

GPU 0 → Expert 0, 1
GPU 1 → Expert 2, 3
GPU 2 → Expert 4, 5
GPU 3 → Expert 6, 7

主要收益:

  • 分散大量 Expert 权重。
  • 支持更大型的 MoE 模型。
  • 实现多 GPU Expert 计算。

主要挑战:

  • Token Dispatch。
  • All-to-All Communication。
  • Expert Load Balancing。

如果大量 Token 都选择同一个 Expert,可能产生局部负载不均衡。

EP 是部署 DeepSeek 等大型 MoE 模型时值得了解的重要技术。

13. Prefill-Decode Disaggregation

Prefill 与 Decode 通常具有不同的资源需求:

Prefill → Compute-intensive
Decode  → Memory-bandwidth-intensive

PD Disaggregation 将两个阶段部署到不同的 Worker。

HTTP Request
      ↓
Prefill Worker
      ↓
Transfer KV Cache
      ↓
Decode Worker
      ↓
Generated Tokens

主要优势:

  • 独立配置 Prefill 和 Decode 资源。
  • 减少长 Prefill 对 Decode 的干扰。
  • 有机会优化 TTFT、TPOT 与高负载 Tail Latency。

主要代价:

  • KV Cache 跨 Worker 传输。
  • 更复杂的路由和资源管理。
  • 更高的部署与运维成本。

SGLang 提供相关架构和传输后端支持,实际性能取决于互联速度、工作负载和调度配置。

对于单 GPU 推理,通常没有必要进行 PD 分离。

14. CUDA Graph

正常情况下,CPU 需要逐个提交 GPU Kernel:

CPU:
Launch Kernel A
Launch Kernel B
Launch Kernel C
Launch Kernel D

Decode 会重复执行大量类似的计算步骤,Kernel Launch Overhead 可能变得明显。

CUDA Graph 可以捕获一组 GPU 操作:

Capture:
A → B → C → D
       ↓
   CUDA Graph
       ↓
Repeated Replay

这样后续可以减少重复的 CPU Kernel Launch 开销。

限制

CUDA Graph 通常对执行结构、内存地址和形状稳定性有一定要求。

LLM Serving 中 Batch Size、序列长度等可能动态变化,因此推理引擎往往需要针对不同形状进行 Graph Capture 或采用其他适配方式。

CUDA Graph 优化的是 CPU 到 GPU 的调度开销,不会直接减少模型权重大小,也不会消除 KV Cache 的内存需求。

15. 技术与性能指标对应关系

技术主要优化对象主要影响
Continuous Batching请求调度Throughput
Chunked PrefillPrefill / Decode 调度TPOT、Tail Latency
PagedAttentionKV Cache 显存管理并发、显存利用率
Prefix Caching重复 Prompt PrefillTTFT、计算成本
KV Cache Management显存资源分配并发、稳定性
FlashAttentionAttention IO计算速度、内存开销
Speculative Decoding自回归生成TPOT
CUDA GraphKernel LaunchTPOT、执行延迟
Tensor Parallel单模型多 GPU 计算模型容量、单请求性能
Pipeline Parallel模型层分布模型容量
Data Parallel多模型副本总 Throughput
Expert ParallelMoE Expert 分布MoE 模型容量与效率
PD DisaggregationPrefill / Decode 资源隔离Tail Latency、资源利用率

实际效果取决于模型、硬件、请求长度和并发量,不是所有优化都会同时改善 TTFT、TPOT 和 Throughput。

总结

可以将 LLM Serving 的优化理解为四个问题:

问题解决技术
GPU 如何同时处理更多请求?Continuous Batching、Chunked Prefill
KV Cache 如何高效存储和复用?PagedAttention、Prefix Cache
如何提高单次 GPU 计算效率?FlashAttention、CUDA Graph、Speculative Decoding
如何让模型利用多张 GPU?TP、PP、DP、EP、PD Disaggregation

核心关系:

Requests
    ↓
Scheduler
    ├── Continuous Batching
    └── Chunked Prefill
    ↓
KV Cache Manager
    ├── PagedAttention
    └── Prefix Caching
    ↓
Execution Engine
    ├── FlashAttention
    ├── CUDA Graph
    └── Speculative Decoding
    ↓
Distributed Runtime(按需)
    ├── TP / PP / DP / EP
    └── PD Disaggregation
    ↓
GPU

对于初步学习 vLLM/SGLang,应该优先理解:

  1. Continuous Batching 与 Chunked Prefill。
  2. PagedAttention 与 Prefix Caching。
  3. FlashAttention 与 CUDA Graph。
  4. Speculative Decoding。
  5. TP、PP、DP 的区别。

Expert Parallel 和 PD Disaggregation 是大型分布式推理的重要技术,但可以在实际需要多 GPU 或 MoE 部署时进一步学习。


参考文档