Pidoku

SGLang and RadixAttention (2023)

Module 30 Lesson 30.r 35 min Difficulty 3/5

Prerequisites 12.m, 30.o, 12.o


Before you start: words you need#

WordPlain meaning
LM programAn application that calls a language model many times with structure: multi-turn chat, few-shot prompts, branching (“try three ideas”), agents, retrieval pipelines, forced JSON output.
PrefixThe shared beginning of several prompts: a system prompt, few-shot examples, chat history, a document.
Radix treeA tree whose edges are labelled with runs of tokens; any prompt is a path from the root. Prompts with a common start share a path (15.b).
LRU evictionWhen memory is full, throw away what was used least recently.
Cache hit rateFraction of prompt tokens whose KV cache is reused instead of computed.
Constrained decodingForcing output to match a grammar or JSON schema by masking forbidden tokens at each step (18.e).
Finite state machine (FSM)A set of states and allowed transitions; a regular expression or JSON schema can be compiled into one.

1. The paper#

  • Title: “SGLang: Efficient Execution of Structured Language Model Programs”
  • Authors: Lianmin Zheng, Liangsheng Yin, Zhiqiang Xie, Chuyue Sun, Jeff Huang, Cody Hao Yu, Shiyi Cao, Christos Kozyrakis, Ion Stoica, Joseph E. Gonzalez, Clark Barrett, Ying Sheng (Stanford, UC Berkeley, Shanghai Jiao Tong, Texas A&M and others)
  • Venue: NeurIPS 2024 (arXiv December 2023).
  • Link: arXiv:2312.07104 · code: sgl-project/sglang

Several authors overlap with vLLM (30.o). SGLang is taught as an engine in 15.b; this lesson is about the paper’s ideas.


2. The problem#

By late 2023, real applications were not single prompts. An agent loop, a tree-of-thought search or a chat with a long system prompt sends the model many requests that share long prefixes. Serving engines of the time threw each request’s KV cache away when it finished. The next request with the same 2,000-token prefix recomputed it from scratch.

vLLM could share blocks within a request (parallel samples, beam search) and, by hand, across requests with a declared shared prefix. There was no automatic way to find and reuse any shared prefix across requests over time.

Two more costs: programs were written with slow, sequential client libraries, and constrained JSON output was decoded one token at a time even where the grammar left only one possible next string.


3. The idea#

Two halves: a frontend language (Python primitives like gen, select, fork, join) that exposes a program’s structure, and a runtime that exploits it. The runtime’s three ideas:

  1. RadixAttention. Keep the KV cache of finished requests in GPU memory, indexed by a radix tree of token sequences. A new request walks the tree, reuses the longest cached prefix, and only computes the rest. Evict leaves by LRU when memory is needed, never evicting a node a running request is using.
  2. Cache-aware scheduling. Order waiting requests so that ones sharing prefixes run close together (longest-shared-prefix first), which keeps their prefix in cache. For a batch, this order is a depth-first walk of the tree, which the paper proves gives the best hit rate.
  3. Compressed finite state machine. Compile a regex or JSON schema to an FSM, then merge runs of states that have only one way forward (for example {"name": "), so the engine emits the whole fixed string in one step instead of one token at a time. (A third trick, API speculative execution, targets closed API models and is less relevant here.)
flowchart TD
  ROOT["root"] --> SYS["System prompt (cached once)"]
  SYS --> C1["Chat A history"]
  SYS --> C2["Chat B history"]
  C1 --> Q1["New question in chat A: only this part is computed"]
  SYS --> FS["Few-shot examples"]
  FS --> Q2["Question 1"]
  FS --> Q3["Question 2"]
  class ROOT neutral
  class SYS,C1,C2,FS memory
  class Q1,Q2,Q3 compute

4. How it works#

  • Tree nodes hold token runs and pointers to their KV blocks (paged, block size 1 token in the original design, so any prefix length can match).
  • Matching: on arrival, walk the tree comparing tokens; the matched prefix’s KV is attached to the request, and only the suffix goes through prefill.
  • Insertion: when a request finishes (or a prefill completes), its new tokens become a new branch.
  • Reference counts protect nodes in use; only unreferenced leaves can be evicted, oldest first.
  • Scheduling: with continuous batching the order of waiting requests decides what stays cached. Pure longest-prefix-first can starve unrelated requests, so the paper discusses fairness trade-offs.
  • Frontend: fork launches parallel branches from one state, so the runtime sees shared prefixes explicitly; the interpreter sends requests asynchronously and in batches.

Compared with vLLM’s later automatic prefix caching (17.f), which hashes fixed-size blocks, the radix tree matches at token granularity and makes the shared structure explicit. Both reach the same goal.


5. Results#

Hardware: NVIDIA A10G and A100; models Llama-7B/70B, Mixtral-8x7B, LLaVA vision models; baselines vLLM (an earlier version without its experimental prefix caching), Guidance and LMQL.

ClaimResult
Throughput across agent, reasoning, few-shot, JSON, RAG and chat workloadsup to 6.4× higher
Latencyup to 3.7× lower
Cache hit rate on these benchmarks50%–99%
Cache-aware scheduling vs optimal hit rateabout 96% of optimal on average
Multi-turn chat with long outputsalmost no speed-up (decode dominates, little to share)

The gains are workload-dependent by design: large when prompts share long prefixes and outputs are short, near zero when every request is unique and long. That is the honest way to read “up to 6.4×”.


6. What held up and what did not#

Held up

  • Cross-request prefix caching is standard. vLLM (automatic prefix caching, on by default), TensorRT-LLM, and every hosted API’s “prompt caching” discount (12.m) rest on this idea. Agents and multi-turn chat make it one of the largest cost levers in 2026 (27.b).
  • SGLang the engine. It grew from a research prototype into one of the two leading open-source engines, used in production by many labs and clouds, with strong support for DeepSeek-style MoE and MLA models.
  • Prefix-aware routing across replicas (21.h) extends the same idea to a whole fleet: send a request to the replica that already caches its prefix.
  • Jump-forward for fixed grammar segments is a standard structured-output optimisation (18.e); grammar engines such as XGrammar (also from this community) made constrained decoding nearly free.

Did not, or changed

  • The frontend language was used far less than the runtime. Most users call SGLang through its OpenAI-compatible server; agent frameworks write the programs.
  • Cache-aware scheduling is not the default. In SGLang v0.5.23 the default policy is first-come-first-served; longest-prefix-match is optional and falls back to FCFS when the queue is long, because matching costs CPU time (15.b).
  • GPU memory is too small for big caches. Prefix caches now spill to CPU memory and SSD and are shared across machines (LMCache, Mooncake; 14.k, 30.w).
  • The original radix cache matched at token granularity (page size 1). Engines can now also match at larger page sizes, trading a little reuse for cheaper bookkeeping and kernels; vLLM matches whole 16-token blocks (17.f).

7. Where it lives in 2026#

  • Taught in depth: prefix and prompt caching in 12.m, SGLang’s architecture in 15.b, vLLM’s prefix cache in 17.f, prefix-aware routing in 21.h, structured output in 18.e, agent workloads in 27.b.
  • SGLang’s latest release is v0.5.23 (2 November 2026); RadixAttention remains its prefix cache.

Checked on 13 November 2026.


8. Questions#

  1. What does RadixAttention store after a request finishes, and why is that new?
  2. Walk through what happens when a new chat turn arrives for a conversation whose history is cached.
  3. Why does scheduling order affect the cache hit rate? What is the risk of always choosing the longest shared prefix?
  4. Which nodes can be evicted, and in what order?
  5. What does a compressed FSM save during JSON decoding?
  6. Why did multi-turn chat with long outputs see almost no speed-up?
  7. How would you extend prefix caching across 50 replicas behind a load balancer?

9. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in