Skip to content

SGLang 架构设计与 RadixAttention

SGLang 是一种面向大语言模型的推理引擎与编程语言,其核心创新 RadixAttention 通过基数树自动复用 KV Cache,在多轮对话和复杂推理场景中实现了显著的性能提升。

SGLang架构与RadixAttention

SGLang 整体架构

SGLang 系统由两个核心组件构成:

  • SGLang Runtime (SRT):高性能推理运行时,支持 RadixAttention 和 Continuous Batching
  • SGLang Language:结构化生成语言,支持约束解码和分支控制
python
# SGLang Runtime 基本使用
import sglang as sgl

# 启动运行时
runtime = sgl.Runtime(
    model_path="meta-llama/Llama-2-7b-hf",
    tp_size=1,
)

# 执行推理
result = runtime.generate(
    "请解释什么是深度学习",
    max_new_tokens=256,
)
print(result)

RadixAttention 原理

RadixAttention 使用基数树(Radix Tree)管理 KV Cache 的前缀复用:

  1. 前缀匹配:新请求的 Prompt 在基数树中查找最长公共前缀
  2. 缓存复用:匹配到的前缀 KV Cache 直接复用,无需重新计算
  3. 增量计算:仅计算新增 Token 的 KV Cache
  4. 引用计数:通过引用计数管理缓存的生命周期
python
# RadixAttention 前缀复用示意
class RadixAttentionTree:
    def __init__(self):
        self.root = RadixNode()
        self.cache = {}  # prefix_hash -> kv_cache_blocks

    def match_prefix(self, tokens):
        """在基数树中查找最长匹配前缀"""
        node = self.root
        matched_len = 0
        for i, token in enumerate(tokens):
            if token in node.children:
                node = node.children[token]
                matched_len = i + 1
            else:
                break
        return matched_len, self.cache.get(node.hash)

    def insert(self, tokens, kv_cache_blocks):
        """将新前缀插入基数树"""
        node = self.root
        for token in tokens:
            if token not in node.children:
                node.children[token] = RadixNode()
            node = node.children[token]
            node.ref_count += 1
        self.cache[node.hash] = kv_cache_blocks

与 PagedAttention 对比

特性PagedAttentionRadixAttention
核心优化显存碎片管理前缀缓存复用
适用场景通用推理多轮对话、Agent
缓存复用Copy-on-Write自动前缀匹配
管理结构块表基数树

最佳场景

RadixAttention 在以下场景效果最显著:多轮对话(前缀复用率高)、Agent 系统(系统提示词固定)、批量相似请求(共享前缀多)。

性能提升

RadixAttention 在典型场景下的性能提升:

  • 多轮对话:首轮之后每轮延迟降低 40-60%
  • Agent 系统:系统提示词复用,吞吐量提升 2-3x
  • 批量相似请求:前缀复用率 80%+ 时,吞吐量提升 3-5x

缓存淘汰

基数树中的 KV Cache 需要淘汰策略。当显存不足时,SGLang 采用 LRU 策略淘汰引用计数最低的节点。高频使用的系统提示词应设置高优先级避免被淘汰。

相关资源

最近更新