第137讲SGLang 的架构
SGLang 和 vLLM 是今天用得最多的两个开源推理引擎。它最初来自一篇论文(Zheng 等,SGLang: Efficient Execution of Structured Language Model Programs),要解决的问题是:一个 LLM 应用往往不是一次调用,而是一串调用(多轮对话、思维链、先生成再检查、按 JSON 格式输出),这些调用之间共享大量的前缀,输出还要满足格式约束。论文提出了两样东西:RadixAttention(用一棵基数树做前缀缓存,自动复用任意请求之间的公共前缀)和压缩的有限状态机(加速约束解码)。后来的版本又加上了零开销调度(CPU 调度和 GPU 计算重叠)。
这一讲读这三样,以及 SGLang 的整体结构。读的是 2026 年 11 月 9 日 main 分支的提交 48da6bd(Apache-2.0 许可),只取下了 srt/managers、srt/mem_cache、srt/model_executor、srt/constrained 等几个目录。和上一讲一样,只读源码,没有运行。
三个进程
和 vLLM 一样,SGLang 也把分词、调度、反分词放在不同的进程里。最大的不同在中间:vLLM 的 EngineCore 只有一份,调度结果广播给各个 worker 进程;SGLang 是每张卡一个调度器进程,调度器和执行模型的 TpModelWorker 在同一个进程里。rank 0 从 ZMQ 收到请求后,用 broadcast_pyobj 发给其余的 rank(managers/scheduler_components/request_receiver.py),每个 rank 各自跑一遍同样的调度,得到同样的结果,然后各自执行。
这样做省掉了“调度结果每步跨进程发给 worker”这一步:调度器直接在本进程里调用模型。代价是每张卡都重复做一遍调度的 CPU 工作,并且必须保证各 rank 的调度结果完全一致。
RadixAttention:前缀缓存是一棵树
第 128 讲、nano-vllm 和 vLLM 的前缀缓存都是“块哈希”:把序列切成固定大小的块,每块按“前面所有块 + 本块”算哈希,只能整块地命中。SGLang 换了一个数据结构:基数树(radix tree,压缩的前缀树)。
- 每个节点存一段 token(
key)和这些 token 的 KV 在内存池里的槽位(value)。 - 从根到某个节点的路径,拼起来就是一段完整的前缀。
- 一个节点的孩子按第一个 token 区分,同一段公共前缀只存一次。
class TreeNode:
counter = 0
def __init__(self, id: Optional[int] = None, priority: int = 0):
self.children = defaultdict(TreeNode)
self.parent: TreeNode = None
self.key: RadixKey = None
self.value: Optional[torch.Tensor] = None
self.lock_ref = 0
self.last_access_time = time.monotonic()
self.creation_time = time.monotonic()
self.hit_count = 0
# store hash values of each pages
self.hash_value: Optional[List[str]] = None
# Namespace-aware hashes used only for external KV events.
self.event_hash_value: Optional[List[str]] = None
# priority for priority-aware eviction
self.priority = priority
self.id = TreeNode.counter if id is None else id
TreeNode.counter += 1
@property
def evicted(self):
return self.value is None
def __lt__(self, other: TreeNode):
return self.last_access_time < other.last_access_time
-
children:按孩子的第一个 token(页大小大于 1 时是第一页)索引。key:这个节点的 token 段。value:这段 token 的 KV 槽位,一个整数张量。lock_ref:有几个正在运行的请求在用这个节点,大于 0 就不能淘汰。last_access_time:LRU 淘汰用。 -
value为空表示它的 KV 已经不在显存里了(打开分层缓存时,可能还在 CPU 内存里,第 113 讲)。节点之间按最近访问时间比较大小,放进堆里就能取出最久没访问的。
匹配:从根往下走,停在中间就劈开
def _match_prefix_helper(self, node: TreeNode, key: RadixKey):
access_time = time.monotonic()
node.last_access_time = access_time
child_key = key.child_key(self.page_size)
value = []
while len(key) > 0 and child_key in node.children.keys():
child = node.children[child_key]
child.last_access_time = access_time
prefix_len = child.key.match(key, page_size=self.page_size)
if prefix_len < len(child.key):
new_node = self._split_node(child.key, child, prefix_len)
value.append(new_node.value)
node = new_node
break
else:
value.append(child.value)
node = child
key = key[prefix_len:]
if len(key):
child_key = key.child_key(self.page_size)
return value, node
def _split_node(self, key: RadixKey, child: TreeNode, split_len: int):
# new_node -> child
# New node inherits child's priority (represents shared prefix)
new_node = TreeNode(priority=child.priority)
new_node.hit_count = child.hit_count
new_node.children = {key[split_len:].child_key(self.page_size): child}
new_node.parent = child.parent
new_node.lock_ref = child.lock_ref
new_node.key = child.key[:split_len]
new_node.value = child.value[:split_len].clone()
child.parent = new_node
child.key = child.key[split_len:]
child.value = child.value[split_len:].clone()
new_node.parent.children[key.child_key(self.page_size)] = new_node
# Split hash_value if it was already computed, otherwise leave as None
new_node.hash_value, child.hash_value = split_node_hash_value(
child.hash_value, split_len, self.page_size
)
new_node.event_hash_value, child.event_hash_value = split_node_hash_value(
child.event_hash_value, split_len, self.page_size
)
return new_node-
从根开始,用请求剩余 token 的第一个找孩子;找到了,算这个孩子的 key 和请求剩余部分的公共前缀有多长。路过的节点都刷新访问时间。
-
公共前缀比孩子的 key 短,说明请求在这个节点的中间分叉了。把节点劈成两段,前一段成为新的父节点,匹配到此为止。劈开不复制 KV,只是把槽位张量切成两段。
-
孩子的 key 全部匹配上,就收下它的槽位,继续用剩下的 token 往下找。返回的是一路收下的槽位列表和最后停在的节点。
-
新节点拿走 key 和 value 的前 split_len 个,原节点留下后面的部分,挂在新节点下面。引用计数、命中次数、优先级都继承下来。
插入、加锁、淘汰
def evict(self, params: EvictParams) -> EvictResult:
if self.disable:
return EvictResult()
start_time = time.perf_counter()
num_tokens = params.num_tokens
leaves = list(self.evictable_leaves)
eviction_heap = [
(self.eviction_strategy.get_priority(node), node) for node in leaves
]
heapq.heapify(eviction_heap)
num_evicted = 0
while num_evicted < num_tokens and len(eviction_heap):
_priority, x = heapq.heappop(eviction_heap)
# Tree values are page-aligned copies of a kv row: page-exact segment.
self.token_to_kv_pool_allocator.free_segment(x.value, start_pos=0)
num_evicted += len(x.value)
self._delete_leaf(x)
if len(x.parent.children) == 0 and x.parent.lock_ref == 0:
new_priority = self.eviction_strategy.get_priority(x.parent)
heapq.heappush(eviction_heap, (new_priority, x.parent))
self.kv_events.record_remove(x)
self.update_eviction_metrics(num_evicted, start_time)
return EvictResult(num_tokens_evicted=num_evicted)
def inc_lock_ref(self, node: TreeNode) -> IncLockRefResult:
if self.disable:
return IncLockRefResult(delta=0)
delta = 0
while node != self.root_node:
if node.lock_ref == 0:
self.evictable_size_ -= len(node.key)
self.protected_size_ += len(node.key)
delta -= len(node.key)
node.lock_ref += 1
self._update_leaf_status(node)
node = node.parent
return IncLockRefResult(delta=delta)
def dec_lock_ref(
self, node: TreeNode, params: Optional[DecLockRefParams] = None
) -> DecLockRefResult:
if self.disable:
return DecLockRefResult(delta=0)
delta = 0
while node != self.root_node:
if node.lock_ref == 1:
self.evictable_size_ += len(node.key)
self.protected_size_ -= len(node.key)
delta += len(node.key)
node.lock_ref -= 1
self._update_leaf_status(node)
if node.parent is None:
assert node is self.root_node, (
"This request holds the node from another tree"
)
node = node.parent
return DecLockRefResult(delta=delta)-
需要腾出 num_tokens 个槽位时,把所有可淘汰的叶子(没有孩子、没人在用)放进一个堆,按淘汰策略(默认 LRU)一个个弹出:把它的槽位还给内存池,从树上删掉。删掉之后,如果父节点也变成了没人用的叶子,就把父节点也放进堆里。所以淘汰总是从树的末梢往根部推进:公共前缀(靠近根的节点)被很多请求访问过,最后才会被淘汰。
-
一个请求开始用某条前缀时,从它停在的节点一直到根,每个节点的
lock_ref加一。从 0 变成 1 的节点,从“可淘汰”移到“受保护”。正在运行的请求所用的前缀绝不会被淘汰。 -
请求结束(或这一段 prefill 完成、换了更深的节点)时一路减回去,减到 0 的节点又可以被淘汰了。这对应块哈希方案里的引用计数。
插入(第 712–767 行的 _insert_helper)和匹配几乎一样:沿树往下走,在分叉处劈开节点,最后把没匹配上的部分作为一个新的叶子挂上去。请求结束时,它的全部 token(提示 + 输出)都插入树中,KV 的槽位交给树管理,而不是还给内存池。下一轮对话进来时,就能匹配上整个上一轮。
内存:槽位是一个个 token,不是块
基数树的 value 是逐个 token 的槽位编号,这背后是 SGLang 的两级内存池(mem_cache/memory_pool.py):
class ReqToTokenPool:
"""A memory pool that maps a request to its token locations."""
enable_mamba_extra_buffer_lazy: bool = False
# Extra pre-allocation headroom (reserved for in-transfer decode requests).
# 0 for a plain pool; the decode-flavored pool (DecodeReqToTokenPool) sets a
# positive value. Declared here so callers can read it without getattr.
pre_alloc_size: int = 0
# Class default: some decode pools borrow another __init__ (see
# DecodeReqToTokenPool) but inherit alloc_rows.
_on_alloc_rows: Optional[Callable[[List[int]], None]] = None
# A table without recurrent state holds no state slots: no state pool, slot
# allocator or checkpoint pool. Tables with state set all three.
mamba_pool: Optional[MambaPool] = None
mamba_allocator = None
mamba_ckpt_pool = None
state: Optional[StateStorage] = None
# Whether a row names its request's state slot (the hybrid tables).
holds_state_slots: bool = False
def __init__(
self,
size: int,
max_context_len: int,
device: str,
enable_memory_saver: bool,
):
memory_saver_adapter = TorchMemorySaverAdapter.create(
enable=enable_memory_saver
)
self.size = size
# +1 padding row at index 0: cuda-graph padded batches default
# req_pool_indices to 0, so dummy reads/writes land here harmlessly.
self._alloc_size = size + 1
self.max_context_len = max_context_len
self.device = device
with memory_saver_adapter.region(GPU_MEMORY_TYPE_KV_CACHE):
self.req_to_token = torch.zeros(
(self._alloc_size, max_context_len), dtype=torch.int32, device=device
)
self.free_slots = list(range(1, self._alloc_size))
self.req_generation = torch.zeros(self._alloc_size, dtype=torch.int64)
self._aux_cache: Any = None
def write(self, indices, values):
self.req_to_token[indices] = values
def available_size(self):
return len(self.free_slots)
def alloc(self, reqs: list[Req]) -> Optional[List[int]]:
# Indices of reqs that already have a req_pool_idx and will reuse
# their existing slot (e.g. chunked prefill continuing across chunks).
reusing = [i for i, r in enumerate(reqs) if r.kv.holds_kv]
assert all(reqs[i].kv.kv_allocated_len > 0 for i in reusing), (
"a reused row must carry allocated KV"
)
select_index = self.alloc_rows(len(reqs) - len(reusing))
if select_index is None:
return None
offset = 0
for r in reqs:
if not r.kv.holds_kv:
r.kv.req_pool_idx = select_index[offset]
offset += 1
return [r.kv.req_pool_idx for r in reqs]
def alloc_rows(self, need_size: int) -> Optional[List[int]]:
"""Take need_size rows and bump their generation, with no Req bound to
them. alloc() layers Req binding on top; beam member rows have no Req."""
if need_size > len(self.free_slots):
return None
if need_size == 0:
# Handled separately: free_slots[-0:] is the entire list, not [].
return []
# Pop from the tail: O(need_size), unlike a prefix pop which is
# O(len(free_slots)).
select_index = self.free_slots[-need_size:]
del self.free_slots[-need_size:]
self.req_generation[select_index] += 1
if self._on_alloc_rows is not None:
self._on_alloc_rows(select_index)
return select_index
def free_rows(self, indices: List[int]) -> None:
# Per-row, so beam member rows release their aux entries too: they reach
# alloc_aux_to_lengths via the decode batch's req_pool_indices_cpu.
if self._aux_cache is not None:
for index in indices:
self._aux_cache.free(index)
self.free_slots.extend(indices)
def free(self, req: Req):
assert req.kv.holds_kv, "request must have req_pool_idx"
self.free_rows([req.kv.req_pool_idx])
req.kv.req_pool_idx = None-
一个形状为 [请求数上限, 最长上下文] 的 int32 张量
req_to_token:第 r 行第 i 列,是第 r 个请求第 i 个 token 的 KV 在 KV 池里的槽位号。它相当于块表,只是粒度是 token:每个 token 单独记一个槽位,不要求连续。第 0 行留空,CUDA Graph 补齐出来的空请求都指向它,读写无害(和 nano-vllm 用 −1 的思路一样)。 -
新请求从空闲行里拿一行。分块 prefill 的后续段沿用已有的行。
-
请求结束时只还“行”。行里指向的 KV 槽位并不在这里释放:它们已经交给基数树了,由树决定什么时候淘汰。
第二级是 KV 池(token_to_kv_pool):一个按槽位编号的大张量,存每一层每个 token 的 K、V。分配器在 mem_cache/allocator 里。打开 page_size 大于 1 时,分配、匹配和淘汰都按页对齐,粒度变粗,但有的注意力后端要求按页存(和 nano-vllm 的 256、vLLM 的块是同一类约束)。
把两种前缀缓存放在一起比较:
| 块哈希(vLLM、nano-vllm、miniinfer) | 基数树(SGLang) | |
|---|---|---|
| 命中粒度 | 整块(16–256 个 token) | 1 个 token(或一页) |
| 查找 | 逐块算哈希、查表 | 沿树往下比较 token |
| 结构维护 | 哈希表 + 空闲队列 | 劈开、插入节点;锁要一路加到根 |
| 淘汰 | LRU 的空闲块队列,倒着还让前缀留得久 | 从叶子开始的 LRU,公共前缀自然最后被淘汰 |
| 跨机器共享 | 哈希可以跨进程稳定,便于做全局的 KV 池 | 需要额外给页算哈希(节点上的 hash_value) |
| 额外开销 | 每块一次哈希 | 树的 Python 操作,前缀很多时匹配较慢 |
两者在实际的命中率上差得并不多(块足够小时),差别更多在工程上:基数树天然适合“多轮对话、思维链分叉”这类前缀呈树状的负载;块哈希更简单,也更适合跨机器的 KV 共享。
缓存感知的调度
有了前缀缓存,调度器选谁先 prefill 也会影响命中率。SGLang 的 SchedulePolicy(managers/schedule_policy.py)提供了几种策略:
class CacheAwarePolicy(Enum):
"""Scheduling policies that are aware of the tree cache."""
LPM = "lpm" # longest prefix match
DFS_WEIGHT = "dfs-weight" # depth-first search weighting
HRRN = "hrrn" # highest response ratio next, token-based aging
SHORTEST_PREFILL_FIRST = "shortest-prefill-first"
class CacheAgnosticPolicy(Enum):
"""Scheduling policies that are not aware of the tree cache."""
FCFS = "fcfs" # first come first serve
LOF = "lof" # longest output first
RANDOM = "random"
ROUTING_KEY = "routing-key" # prioritize by routing key frequency in running batch
class SchedulePolicy:
Policy = Union[CacheAwarePolicy, CacheAgnosticPolicy]
def __init__(
self,
policy: str,
tree_cache: BasePrefixCache,
enable_hierarchical_cache: bool,
enable_priority_scheduling: bool,
schedule_low_priority_values_first: bool,
):
self.policy = self._validate_and_adjust_policy(policy, tree_cache)
self.tree_cache = tree_cache
self.enable_hierarchical_cache = enable_hierarchical_cache
self.enable_priority_scheduling = enable_priority_scheduling
self.schedule_low_priority_values_first = schedule_low_priority_values_first
self.priority_sign = 1 if schedule_low_priority_values_first else -1
self._shortest_prefill_calls = 0
self._waiting_prefix_refresh_calls = 0
# It is used to find the matching prefix for in-batch prefix caching.
self.waiting_queue_radix_tree = RadixCache.create_simulated()
def calc_priority(
self,
waiting: Iterable[Req],
running_batch: Optional[ScheduleBatch] = None,
processed_tokens: int = 0,
bootstrap_queue: Iterable[Req] = (),
) -> List[Req]:
"""The waiting requests in the order the policy admits them."""
waiting_queue = list(waiting)
policy = self._determine_active_policy(waiting_queue)
# Cache-agnostic policies sort without matching; match anyway so the load
# snapshot sees num_matched_prefix_tokens. Decode never prefills.
if (
not isinstance(policy, CacheAwarePolicy)
and self.tree_cache.supports_fast_match_prefix()
and get_disagg().disaggregation_mode != "decode"
):
for r in waiting_queue:
match_kv_cache(r, self.tree_cache)
if self.policy == CacheAgnosticPolicy.FCFS:
if self.enable_priority_scheduling:
SchedulePolicy._sort_by_priority_and_fcfs(
waiting_queue, self.priority_sign
)
elif isinstance(policy, CacheAwarePolicy):
temporary_deprioritized = self._compute_prefix_matches(
waiting_queue, policy
)
if policy == CacheAwarePolicy.LPM:
SchedulePolicy._sort_by_longest_prefix(
waiting_queue, temporary_deprioritized
)
elif policy == CacheAwarePolicy.DFS_WEIGHT:
SchedulePolicy._sort_by_dfs_weight(waiting_queue, self.tree_cache)
elif policy == CacheAwarePolicy.HRRN:
SchedulePolicy._sort_by_hrrn(
waiting_queue, temporary_deprioritized, processed_tokens
)
elif policy == CacheAwarePolicy.SHORTEST_PREFILL_FIRST:
SchedulePolicy._sort_by_shortest_prefill(
waiting_queue, temporary_deprioritized
)
self._shortest_prefill_calls += 1
if waiting_queue and self._shortest_prefill_calls % 128 == 1:
logger.info(
"Experimental shortest-prefill-first: queue=%d shortest_uncached=%d",
len(waiting_queue),
self._shortest_prefill_work(waiting_queue[0]),
)
else:
raise ValueError(f"Unknown CacheAware Policy: {policy=}")-
缓存感知的:lpm(最长前缀匹配优先)、dfs-weight(按树的深度优先顺序,让同一棵子树下的请求挨着跑)、hrrn、最短 prefill 优先。不感知缓存的:fcfs(先来先到)、lof(最长输出优先)、随机等。
-
即使是 fcfs,也会先对每个等待的请求做一次前缀匹配,知道它有多少 token 不用再算,后面算预算时要用。
-
命中前缀越长的请求越先放进来。道理是:它命中的那段前缀现在还在缓存里,越早跑,越不容易被淘汰;而且它需要算的 token 少,同样的预算能放进更多请求。
两个值得注意的细节:等待队列超过 128 个请求时,lpm 会退化成 fcfs(_determine_active_policy,第 312 行),因为对每个请求做匹配再排序太慢了;这个提交里默认的策略是 fcfs(srt/arg_groups/fields/schedule.py),缓存感知的排序要显式打开。缓存感知的调度能提高命中率,但会让前缀不常见的请求等得更久,默认值偏向公平。
零开销调度:发射这一步,再处理上一步
第 135 讲看到,vLLM 用占位的办法让调度和执行重叠。SGLang 的调度循环更直接地体现了这个思路:
def event_loop_normal(self):
"""A normal scheduler loop."""
while True:
if self.gracefully_exit:
break
self.increment_scheduler_iterations()
# Receive requests
self.ingest_requests()
if self.pause_state.paused:
self._record_scheduler_state_for_paused_engine()
continue
# Get the next batch to run
plan = self.get_next_batch_to_run(
running_batch=self.running_batch, last_batch=self.last_batch
)
self.running_batch = plan.running_batch
batch = plan.batch_to_run
self.cur_batch_for_debug = batch
# Launch the current batch
if batch:
result = self.run_batch(batch)
self.process_batch_result(batch, result)
else:
# When the server is idle, do self-check and re-init some states.
self._sched_idled = True
self.on_idle()
# Update last_batch
self.last_batch = batch
self.invariant_checker.run(CheckPhase.BUSY, batch)
@DynamicGradMode()
def event_loop_overlap(self):
"""A scheduler loop that overlaps the CPU processing and GPU computation."""
self.enable_skip_finishing_decode = True
self.result_queue: Deque[
Tuple[ScheduleBatch, Union[GenerationBatchResult, EmbeddingBatchResult]]
] = deque()
def pop_and_process():
# Process the results of the last batch
tmp_batch, tmp_result = self.result_queue.popleft()
self.process_batch_result(tmp_batch, tmp_result)
while True:
if self.gracefully_exit:
break
self.increment_scheduler_iterations()
# Receive requests
self.ingest_requests()
if self.pause_state.paused:
self._record_scheduler_state_for_paused_engine()
continue
process_last_batch_early = self.should_process_last_batch_early(
self.last_batch
)
if process_last_batch_early:
pop_and_process()
# Opportunistic flush at the early-processing sync boundary:
# forward_stream is idle (prev forward drained, next not launched),
# so `_flush`'s non-urgent guard compacts freely. Sync-free. A
# failure propagates: a move that stopped midway leaves the pool's
# page tables and ledger inconsistent.
if self.enable_unified_memory:
self.token_to_kv_pool_allocator.flush_opportunistic()
# Get the next batch to run
plan = self.get_next_batch_to_run(
running_batch=self.running_batch, last_batch=self.last_batch
)
self.running_batch = plan.running_batch
batch = plan.batch_to_run
self.cur_batch_for_debug = batch
# Launch the current batch
if batch:
batch_result = self.run_batch(batch)
# Fence result processing behind this forward's shared reads.
self._apply_war_barrier()
self.result_queue.append((batch.copy(), batch_result))
else:
batch_result = None
self._sched_idled = True
# Process the last batch
if self.last_batch:
if not process_last_batch_early:
pop_and_process()
elif batch is None:
# When the server is idle, do self-check and re-init some states
self.on_idle()
# Run sample of the current batch
# It depends on the result of the last batch (e.g., grammar), so we run it after the last batch is processed.
if self.is_generation:
self.launch_batch_sample_if_needed(batch_result, batch)
# Update last_batch
self.last_batch = batch
self.invariant_checker.run(CheckPhase.BUSY, batch)-
收请求 → 决定下一批 → 执行 → 处理结果,严格串行。和 nano-vllm 的
step()一样。 -
执行的结果不立刻处理,而是连同这一批放进队列。
pop_and_process处理队首那一批的结果。 -
决定下一批、调用
run_batch。在重叠模式下,run_batch把计算排进 GPU 的流就返回,不等算完。结果(还在 GPU 上的张量)放进队列。 -
GPU 正在算这一步,CPU 去处理上一步的结果:追加 token、检查结束、把 KV 插入基数树、释放结束的请求。处理时要从 GPU 取上一步采样的 token,这时上一步早已算完,不用等。
-
如果上一步的结果会影响这一步该放谁(比如上一步有请求结束了,不处理就会把它再放进这一步),就先处理再调度,牺牲一点重叠,保证正确。
-
这一步的采样依赖上一步的结果(比如约束解码的语法状态要先接受上一步的 token,才能算出这一步允许哪些 token),所以等上一步处理完再发射采样。
重叠有一个隐含的前提:调度第 i + 1 步时还不知道第 i 步采样出的 token。SGLang 让 GPU 上的输入直接引用第 i 步的输出张量(token 不回到 CPU 再送下去),所以 i + 1 步的输入在 GPU 上自然就是对的。这和 vLLM 的占位是同一个思路的两种写法。重叠模式默认打开,--disable-overlap-schedule 可以关掉。
调度规则:prefill 优先,可以混合
get_next_batch_to_run(managers/scheduler.py 第 4158 行)的主干是:先把上一步的 prefill 批并入运行中的 batch;然后尝试组一个新的 prefill 批(get_new_batch_prefill);组得出来就跑 prefill,组不出来才跑 decode(update_running_batch,KV 不够时会“撤回”一部分请求,相当于抢占)。这和 nano-vllm 的 prefill 优先一样。打开 --enable-mixed-chunk 后,分块 prefill 的批可以把运行中的 decode 请求也带上(mix_with_running,第 4701 行),一步里混合两种,这又接近 vLLM 的做法了。
约束解码:每一步一个词表掩码
第 80 讲讲过约束解码的原理:按语法(JSON Schema、正则、EBNF)维护一个状态机,每一步算出“下一个 token 可以是哪些”,把其余 token 的打分设成 −∞。SGLang 支持 xgrammar、outlines、llguidance 几个后端(srt/constrained/),默认用 xgrammar:
class XGrammarGrammar(BaseGrammarObject):
def __init__(
self,
matcher: GrammarMatcher,
vocab_size: int,
ctx: CompiledGrammar,
override_stop_tokens: Optional[Union[List[int], int]],
key_string: Optional[str] = None,
grammar_stats: Optional[GrammarStats] = GrammarStats(),
) -> None:
super().__init__()
self.matcher = matcher
self.vocab_size = vocab_size
self.ctx = ctx
self.override_stop_tokens = override_stop_tokens
self.accepted_tokens = []
self.key_string = key_string
self.grammar_stats = grammar_stats
def accept_token(self, token: int):
if not self.is_terminated():
self.current_token = token
accepted = self.matcher.accept_token(token)
if not accepted:
# log for debugging
raise ValueError(
f"Tokens not accepted: {token}\n"
f"Accepted tokens: {self.accepted_tokens}\n"
f"Key string: {self.key_string}"
)
else:
self.accepted_tokens.append(token)
def rollback(self, k: int):
self.matcher.rollback(k)
self.accepted_tokens = self.accepted_tokens[:-k]
def is_terminated(self):
return self.matcher.is_terminated()
def allocate_vocab_mask(
self, vocab_size: int, batch_size: int, device
) -> torch.Tensor:
return _allocate_token_bitmask(vocab_size, batch_size)
def fill_vocab_mask(self, vocab_mask: torch.Tensor, idx: int) -> None:
self.matcher.fill_next_token_bitmask(vocab_mask, idx)
@staticmethod
def move_vocab_mask(vocab_mask: torch.Tensor, device) -> torch.Tensor:
return vocab_mask.to(device, non_blocking=True)
def apply_vocab_mask(self, logits: torch.Tensor, vocab_mask: torch.Tensor) -> None:
if logits.device.type in {"cuda", "xpu", "musa"}:
if _is_hip:
apply_token_bitmask_inplace_cuda(logits, vocab_mask)
else:
apply_token_bitmask_inplace_triton(logits, vocab_mask)
elif logits.device.type == "npu":
import sgl_kernel_npu # noqa: F401
torch.ops.npu.apply_token_bitmask(logits, vocab_mask)
elif logits.device.type == "cpu":
# Used by the MLX backend, which builds its additive mask rows
# on the CPU before inserting them into the lazy graph.
from xgrammar import apply_token_bitmask_inplace
apply_token_bitmask_inplace(logits, vocab_mask, backend="cpu")
else:
raise RuntimeError(f"Unsupported device: {logits.device.type}")
def copy(self):
matcher = GrammarMatcher(
self.ctx,
max_rollback_tokens=MAX_ROLLBACK_TOKENS,
override_stop_tokens=self.override_stop_tokens,
)
if grammar_stats := self.grammar_stats:
grammar_stats = dataclasses.replace(
grammar_stats, is_cache_hit=True, tree_traversal_time=[]
)
return XGrammarGrammar(
matcher,
self.vocab_size,
self.ctx,
self.override_stop_tokens,
self.key_string,
grammar_stats,
)
def try_jump_forward(self, tokenizer) -> Optional[Tuple[List[int], str]]:
s = self.matcher.find_jump_forward_string()
if s:
return [], s
return None
def jump_forward_str_state(self, helper: Tuple[List[int], str]) -> Tuple[str, int]:
_, data = helper
return data, -1
def jump_and_retokenize(
self, old_output_ids: List[int], new_output_ids: List[int], next_state: int
):
k = 0
for i, old_id in enumerate(old_output_ids):
if old_id == new_output_ids[i]:
k = i + 1
else:
break
# rollback to the last token that is the same
if k < len(old_output_ids):
self.matcher.rollback(len(old_output_ids) - k)
for i in range(k, len(new_output_ids)):
if not self.matcher.accept_token(new_output_ids[i]):
raise ValueError(
f"Token not accepted during retokenization: {new_output_ids[i]} "
f"at position {i}\n"
f"Old output IDs: {old_output_ids}\n"
f"New output IDs: {new_output_ids}\n"
f"Key string: {self.key_string}"
)-
每个请求一个
GrammarMatcher,记着语法走到了哪里。采样出 token 后调用accept_token推进状态。不被接受说明前面的掩码有 bug,直接报错。 -
投机解码时,被拒绝的草稿 token 已经被状态机接受过了,要退回 k 步。这和 KV 的回滚(num_computed_tokens 减回去)是同一件事在语法状态上的版本。
-
fill_next_token_bitmask把“下一个允许的 token”写成一个位图(每个 token 一位,15 万个词约 19 KB)。整个 batch 的位图拼起来送到 GPU,一个 Triton kernel 把不允许的位置的打分设成 −∞。位图在 CPU 上算,这一步可以和 GPU 的前向重叠(上一节的“采样放在最后”)。 -
有时语法规定接下来只能是一串固定的字符(比如 JSON 的
{"name": "),没必要一个 token 一个 token 地生成。try_jump_forward问状态机“接下来有没有唯一确定的字符串”,有就直接接上,再重新分词(jump_and_retokenize处理新旧 token 不一致时的回退)。这就是论文里“压缩的有限状态机”的用途。注意:在本讲取下的几个目录里,调度器并没有直接调用
try_jump_forward,只有语法后端之间互相包装时用到。读源码时,“接口还在”不等于“功能在用”,要顺着调用链确认。
回顾
SGLang 和 vLLM 走到了相近的地方:都分了进程、都有分页(或逐 token)的 KV 和前缀缓存、都让调度和执行重叠、都支持投机解码和约束解码。差别主要在几处取舍:前缀缓存用树还是用哈希;调度结果是广播给 worker,还是每张卡各算一遍;prefill 和 decode 默认分开跑还是混着跑。读懂这些取舍背后的原因,比记住哪个引擎有哪个功能更有用,因为功能会互相借鉴,取舍的道理不会变。
下一讲把视野放宽:TensorRT-LLM、LMDeploy、llama.cpp 这些引擎各自的定位,以及 PD 分离、大规模专家并行在这些引擎里是怎么落地的。下一讲:其他引擎与规模化部署。