
24 November 2026 · Inference engine notes · 1/4
Inference Engines 01: How mini-sglang Fits Together
mini-sglang code walkthrough, here it is! I've been reading the ML System book, which talks about plenty of inference optimizations, so this time I'm looking at how a real inference engine actually writes them, and I picked mini-sglang (read as a total beginner). This post starts with how it's put together: which processes a request goes through, what the Scheduler is busy with each round, how the KV cache is managed, and, held up against the usual inference-engine tricks, which ones it implements.
What it is
- A small teaching version of SGLang from LMSYS: about 7.5k lines of Python, CUDA only
- The core pieces are all there: paged KV, Radix cache, continuous batching, chunked prefill, overlap scheduling, CUDA Graph, TP
- All the code is under
python/minisgl/, split by module:server/,tokenizer/,scheduler/,engine/,models/,attention/,kvcache/
Processes
- A request passes through 4 kinds of process: API Server → Tokenizer → Scheduler → Detokenizer → API Server
- Processes talk only through ZMQ (push / pull), passing msg objects
- API Server (main process, FastAPI)
- Gives each request a
uid;ack_map+event_mapwork as its mailbox - Sends a
TokenizeMsgto the tokenizer, then waits for the reply inwait_for_ack stream=Truegoes throughStreamingResponse; otherwise it collects everything and returns once
- Gives each request a
- Tokenizer (you can run several): applies the chat template + encodes → sends
UserMsg(input_ids)to the Scheduler - Detokenizer (exactly 1): the same function as the tokenizer,
tokenize_worker, listening on a different address; takesDetokenizeMsg→ decodes incrementally → sendsUserReplyback to the API Server - Scheduler (one per TP rank)
- The Engine lives inside the Scheduler process, not in a process of its own
- With several GPUs, rank 0 receives messages and broadcasts them to the other ranks
- Startup:
server/launch.pystarts the scheduler, detokenizer and tokenizer subprocesses, and waits on anack_queueuntil all of them are ready
One Scheduler round
- The main loop is
overlap_loop(ornormal_loop). Each round:receive_msg: only blocks when there is nothing to do_process_one_msg: aUserMsggoes intoPrefillManager.pending_list; amax_tokensbeyond the model's length gets cut down_schedule_next_batch: prefill first, decode only when there is no prefill (there's a TODO in the code about supporting decode first)_prepare_batch: pads the batch for CUDA Graph, pages withallocate_paged, computes positions, reads where to write KV frompage_table, prepares attention metadata and sampling parameters_forward: takes input_ids fromtoken_pool→Engine.forward_batch→ writes the new tokens back totoken_pool_process_last_data: checks who is finished (hitmax_tokensor EOS), frees their resources, stores them into the Radix cache withcache_req, and sends results to the detokenizer
- A round is one kind only: all prefill or all decode, never mixed
- Three gates for admission (
PrefillAdder.try_add_one)- Token budget:
--max-extend-length(alias--max-prefill-length), default 8192 - Seats:
--max-running-requests, default 256 - Memory: reserves as if every request writes its full
max_tokens, and leaves room for requests already decoding (inflight_tokens)
- Token budget:
- Strictly first come, first served: if the head of the queue doesn't fit, nobody behind it is tried
- Reserving for the worst case → it never runs out midway → no preemption needed (SGLang admits optimistically and retracts when memory runs short)
- A prompt too long to fit → becomes a
ChunkedReq; the rest goes back to the head of the queue next round (chunked prefill)
A request's progress
- Just three numbers:
cached_len(KV already computed),device_len(tokens already on the GPU),max_device_len(prompt +max_tokens) - Each round computes only the span
[cached_len, device_len) - In the code, prefill and decode are the same thing with a different span length: decode is always 1
- After a step,
complete_one():cached_len = device_len,device_len += 1 - Tokens live in
token_poolon the GPU, so nothing is copied from the CPU each round
Overlap scheduling
- While the GPU runs batch N, the CPU handles batch N−1's results and prepares batch N+1
- How: the Scheduler and Engine use two CUDA streams; sampled tokens are copied back to the CPU asynchronously (a
copy_doneevent) and read only in the next round - An environment variable turns it off and falls back to
normal_loop
Engine and model
Engine.forward_batch: decode uses CUDA Graphreplaywhen it can, otherwisemodel.forward()- CUDA Graphs are recorded ahead of time for a few batch sizes (1, 2, 4, 8…); the real batch is padded up
- One Qwen3 forward: embedding → N layers (RMSNorm → QKV → RoPE + q/k norm → write KV → FlashAttention with
page_table→ O proj → RMSNorm + MLP) → LM head → sampling - Prefill computes logits only for each request's last row; the rest aren't needed
- Sampling: argmax for greedy, otherwise FlashInfer's sampling kernels
- Attention backends:
attention/fa.py,fi.py,trtllm.py
KV cache
- At startup, the remaining GPU memory is allocated once as a KV pool and cut into pages
page_table:[max requests + 1, max length], holding each token's slot number in the poolpage_sizedefaults to 1; the trtllm backend forces 64- The free-page list is in
scheduler/cache.py(allocate_paged,free_slots) - Radix cache (
kvcache/radix_cache.py)- Tree nodes store "token ids → slot numbers", not the KV itself; the KV stays in the pool
- A new request first runs
match_reqto find the longest common prefix, and reuses the KV it hits - Matching skips the last token, so at least 1 token is computed and there are logits to sample from
ref_countkeeps entries in use from being deleted; when memory runs short, leaves are evicted LRU
- Without radix it uses
naive_cache.py, with nothing shared between requests
TP
--tp-sizesets the number of GPUs; each GPU gets one Scheduler + Engine- QKV and the MLP up-projection are split by column; O proj and the MLP down-projection by row, followed by
all_reduce(layers/linear.py) - Two all_reduces per layer, so it only suits NVLink inside one machine
Against the inference-engine toolbox
Most inference-engine tricks answer one of four questions. mini-sglang does some of them; full SGLang has nearly all the rest:
| Question | Technique | How | mini-sglang |
|---|---|---|---|
| Don't waste memory | Paged KV | Pages + a page table, allocate on demand | Yes |
| Prefix caching (RadixAttention) | Look up a tree by content, reuse KV for shared beginnings | Yes | |
| KV quantization (FP8) | Store K/V in 8 bits | No | |
| Tiered cache (HiCache) | Move evicted prefixes to CPU memory / SSD | No | |
| Preemption and recompute | Admit optimistically, evict when short (retract) | No, reserves for the worst case | |
| Keep the GPU busy | Continuous batching | Regroup every round | Yes |
| Chunked prefill | Read a long prompt over several rounds | Yes | |
| Mixed prefill / decode batches | Both kinds in the same round | No | |
| Overlap scheduling | GPU runs this round while the CPU prepares the next | Yes | |
| CUDA Graph | Record once, replay every round | Yes | |
| PD disaggregation | Prefill and decode on different machines, ship the KV | No | |
| Faster, better-behaved output | FlashAttention / FlashInfer | Compute attention tile by tile on chip | Calls existing kernels |
| Weight quantization (FP8, INT4, AWQ, GPTQ) | Fewer bits per weight, less to move | No | |
| Speculative decoding (EAGLE etc.) | A small model guesses, the big one checks in one pass | No | |
| Constrained decoding | Mask invalid tokens each step (JSON, regex) | No | |
| Too big for one GPU | Tensor parallelism (TP) | Split each layer, all-reduce at the end | Yes |
| Pipeline parallelism (PP) | Different layers on different GPUs | No | |
| Data parallelism / DP attention | Several replicas, each taking its own requests | No | |
| Expert parallelism (EP) | MoE experts spread across GPUs | No |
The serving layer adds more: scheduling policies (for example lpm, ordering by prefix-hit length), a router that sends requests with the same prefix to the same machine, and serving many LoRAs at once.
A few takeaways
- Decode is slow because each round moves the whole set of weights out of GPU memory once → computing a few more rows is almost free → batching and speculative decoding are both built on this
- The Radix tree is only an index; the real data is the KV in the pool
- Paging lets memory be handed out in small pieces and shared at any time; Radix finds which pages can be shared, and on a hit it just copies the page numbers into the new request's
page_table - A lot of an inference engine is old CS: paging, tries, LRU, reference counting, pipelining, process scheduling