Skip to content
King Jin

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

mini-sglang's 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_map work as its mailbox
    • Sends a TokenizeMsg to the tokenizer, then waits for the reply in wait_for_ack
    • stream=True goes through StreamingResponse; otherwise it collects everything and returns once
  • 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; takes DetokenizeMsg → decodes incrementally → sends UserReply back 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.py starts the scheduler, detokenizer and tokenizer subprocesses, and waits on an ack_queue until all of them are ready

One Scheduler round

One Scheduler round

  • The main loop is overlap_loop (or normal_loop). Each round:
    1. receive_msg: only blocks when there is nothing to do
    2. _process_one_msg: a UserMsg goes into PrefillManager.pending_list; a max_tokens beyond the model's length gets cut down
    3. _schedule_next_batch: prefill first, decode only when there is no prefill (there's a TODO in the code about supporting decode first)
    4. _prepare_batch: pads the batch for CUDA Graph, pages with allocate_paged, computes positions, reads where to write KV from page_table, prepares attention metadata and sampling parameters
    5. _forward: takes input_ids from token_pool → Engine.forward_batch → writes the new tokens back to token_pool
    6. _process_last_data: checks who is finished (hit max_tokens or EOS), frees their resources, stores them into the Radix cache with cache_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)
  • 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_pool on 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_done event) 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 Graph replay when it can, otherwise model.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 pool
  • page_size defaults 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_req to 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_count keeps 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-size sets 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:

QuestionTechniqueHowmini-sglang
Don't waste memoryPaged KVPages + a page table, allocate on demandYes
Prefix caching (RadixAttention)Look up a tree by content, reuse KV for shared beginningsYes
KV quantization (FP8)Store K/V in 8 bitsNo
Tiered cache (HiCache)Move evicted prefixes to CPU memory / SSDNo
Preemption and recomputeAdmit optimistically, evict when short (retract)No, reserves for the worst case
Keep the GPU busyContinuous batchingRegroup every roundYes
Chunked prefillRead a long prompt over several roundsYes
Mixed prefill / decode batchesBoth kinds in the same roundNo
Overlap schedulingGPU runs this round while the CPU prepares the nextYes
CUDA GraphRecord once, replay every roundYes
PD disaggregationPrefill and decode on different machines, ship the KVNo
Faster, better-behaved outputFlashAttention / FlashInferCompute attention tile by tile on chipCalls existing kernels
Weight quantization (FP8, INT4, AWQ, GPTQ)Fewer bits per weight, less to moveNo
Speculative decoding (EAGLE etc.)A small model guesses, the big one checks in one passNo
Constrained decodingMask invalid tokens each step (JSON, regex)No
Too big for one GPUTensor parallelism (TP)Split each layer, all-reduce at the endYes
Pipeline parallelism (PP)Different layers on different GPUsNo
Data parallelism / DP attentionSeveral replicas, each taking its own requestsNo
Expert parallelism (EP)MoE experts spread across GPUsNo

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