Phase 06/Reading production engines/SGLang source and TensorRT-LLM internals
PHASE 06 · Reading production engines

SGLang source and TensorRT-LLM internals

0%
12 h6 subtopics2 lessons · 2 required
In plain English

Once you know one engine well, the fastest way to understand the field is to read two more and notice what they do differently. It is like a chef who has mastered one restaurant's kitchen visiting two others: the stations are familiar, so the differences jump out. SGLang is built around a cache that remembers shared prompt prefixes in a tree, so repeated conversation histories are not recomputed. TensorRT-LLM instead compiles the model ahead of time into a fixed, highly tuned program, trading flexibility for speed. You will trace a request through each and write a comparison with vLLM.

Why it matters

Production teams pick engines based on workload, and engineers who can explain the structural differences (tree cache versus block hashing, ahead-of-time compilation versus eager Python) make better choices and debug faster. Reading three engines also shows you which ideas are universal and which are implementation accidents.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Trace a request through SGLang's tokenizer manager, scheduler and TP worker.
  • Explain RadixAttention and how the radix tree stores and evicts KV cache.
  • Describe the TensorRT-LLM flow from model definition to compiled engine to runtime executor.
  • Locate the in-flight batching and KV cache manager implementations in TensorRT-LLM.
  • Write a structured comparison of the three engines' scheduling and caching designs.

Key concepts

RadixAttention
SGLang's prefix cache that stores KV blocks in a radix tree keyed by token sequences and evicts by LRU on tree leaves.
Tokenizer manager
SGLang's front process that tokenizes, routes to the scheduler process and detokenizes streaming output.
Scheduler (SGLang)
Builds batches with prefix-aware ordering so requests sharing cache run together.
Frontend language
SGLang's Python DSL for multi-call programs (fork, select, regex constraints) that the runtime can exploit.
TensorRT engine
A serialized, hardware-specific compiled graph produced from a model definition with fixed max shapes.
Executor API
TensorRT-LLM's C++/Python runtime interface that handles in-flight batching and KV cache management.
Plugin
A hand-written TensorRT layer (GEMM, attention) that replaces the compiler's generic implementation.

Subtopics

  1. 1. SGLang repository layout

    python/sglang/srt is the runtime; map managers (tokenizer, scheduler, detokenizer), mem_cache, model_executor and layers/attention.

  2. 2. RadixAttention and the radix cache

    Read mem_cache/radix_cache.py; understand match_prefix, insert, evict and how a request's KV indices are built from the tree.

  3. 3. SGLang scheduler and batch formation

    Read managers/scheduler.py and schedule_policy.py; see how longest-prefix-match ordering and chunked prefill are implemented.

  4. 4. TensorRT-LLM build pipeline

    Model definition in tensorrt_llm/models, network building, plugin insertion, and trtllm-build producing an engine directory with config.json.

  5. 5. TensorRT-LLM runtime and batch manager

    The Executor API, in-flight batching, paged KV cache manager and the cpp/tensorrt_llm/batch_manager directory.

  6. 6. Three-engine comparison

    Scheduling policy, prefix caching data structure, kernel source, compilation model and extensibility compared side by side.

Resources

Hands-on lessons

L1

Trace a request through SGLang and annotate the radix cache

CPU · your Macreading-code240 minrequired

Goal · Produce a call graph of one SGLang generate request and a worked example of radix cache insert, match and evict for three overlapping prompts.

  1. 1git clone https://github.com/sgl-project/sglang and check out the latest release tag; record the commit hash.
  2. 2Start at python/sglang/srt/entrypoints and find the HTTP generate handler; follow into managers/tokenizer_manager.py.
  3. 3Follow the ZMQ hop to managers/scheduler.py; annotate the main event loop, get_new_batch_prefill and the decode batch path.
  4. 4Open mem_cache/radix_cache.py; read match_prefix, insert and evict and draw the tree after inserting prompts A, AB and AC token by token.
  5. 5Find where the scheduler calls the radix cache to compute prefix lengths and how that influences batch ordering.
  6. 6Locate the attention backend selection and the layer that calls it; record the kernel used for prefill and decode.
  7. 7Write the call graph with path:line references and the radix tree diagrams in one markdown file.
Deliverable
sglang-request-trace.md with the call graph, commit hash and three radix tree diagrams showing node sharing.
Check
Your diagram shows prompts AB and AC sharing the node for A, and your eviction walkthrough frees a leaf before an interior node.
L2

Map the TensorRT-LLM build and runtime path

CPU · your Macreading-code180 minrequired

Goal · Document how a Llama model goes from Python definition to compiled engine to a served request in TensorRT-LLM, and write a three-engine comparison table.

  1. 1git clone https://github.com/NVIDIA/TensorRT-LLM; record the release tag.
  2. 2Read tensorrt_llm/models/llama/model.py and note how layers are expressed as network-building calls rather than eager PyTorch.
  3. 3Read tensorrt_llm/commands/build.py (trtllm-build) and list the build-time decisions (max batch, max input length, plugins, quantization).
  4. 4Read tensorrt_llm/executor and the headers under cpp/include/tensorrt_llm/executor; identify the request, response and KV cache config types.
  5. 5Skim cpp/tensorrt_llm/batch_manager to find the in-flight batching scheduler and the KV cache manager classes.
  6. 6Fill in a comparison table for vLLM, SGLang and TensorRT-LLM with rows for scheduling, prefix cache structure, attention kernel source, compilation model, and how to add a new model.
  7. 7Write a 300-word conclusion on which engine you would choose for a chat workload with heavy shared system prompts and why.
Deliverable
trtllm-internals.md with the build/runtime map and the comparison table.
Check
Every row of the comparison table has a path reference in each engine's repository, and your conclusion names a concrete mechanism rather than a benchmark number.

Build your own

Build your own engine comparison matrix generator

PythonCPU · your Mac~8 h

A tool that parses the argument and config definitions of vLLM, SGLang and TensorRT-LLM straight from their source trees and emits a feature-by-feature comparison table with path:line evidence for every cell.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/engine/arg_utils.py ↗

How you know a stage passes

Write tests/test_matrix.py first. A fixture clones the three repositories at pinned commits (tests/PINS.json). Each stage adds an assertion on the extracted data (a known flag with its default, a cell in the matrix, a path:line that must exist) and a CLI call that must exit 0 and produce a file. Run `pytest -q`; a stage passes when its test and all earlier tests are green, and `python -m matrix build` regenerates matrix.md without manual edits.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01extract vLLM engine arguments
    Parse vllm/engine/arg_utils.py and the dataclasses it references with ast and collect every flag name, type, default and help string into a normalized JSON record.
    test · The record for max_num_seqs has the default taken from the SchedulerConfig dataclass, enable_prefix_caching is present with its help text, and the extractor finds at least 100 arguments.
  2. 02extract SGLang server arguments
    Parse python/sglang/srt/server_args.py (the ServerArgs dataclass and add_cli_args) into the same JSON shape, including flags that exist only in the argparse section.
    test · chunked_prefill_size, schedule_policy and disable_radix_cache appear with defaults and path:line; the two extractors share one schema validated by a JSON Schema file.
  3. 03extract TensorRT-LLM build and runtime options
    Parse the trtllm-build argparse definitions and the LLM API args (tensorrt_llm/llmapi/llm_args.py or the pydantic models of the pinned version) into the same schema, tagging each as build-time or runtime.
    test · max_batch_size and max_num_tokens appear tagged build-time, kv_cache_free_gpu_mem_fraction appears tagged runtime, and at least 60 options are extracted.
  4. 04concept mapping table
    A hand-written concepts.yaml maps each of 20 concepts (prefix caching, chunked prefill, scheduling policy, speculative decoding, quantization formats, CUDA graphs, TP degree, max concurrency, KV memory fraction, and so on) to zero or more flags per engine; the tool joins it with the extracted records.
    test · `python -m matrix build` writes matrix.md with 20 rows and 3 engine columns; every non-empty cell contains a flag name, its default and a path:line; a test asserts no concept row is empty for all three engines.
  5. 05evidence checker
    Every path:line in matrix.md is verified against the pinned checkouts, and defaults are re-read from source so a stale table fails loudly.
    test · `python -m matrix check` exits 0 on the pinned commits and exits 1 with a named cell when you deliberately edit one default in matrix.md.
  6. 06drift report across releases
    `python -m matrix drift --engine vllm --from <tag> --to <tag>` reports flags added, removed, renamed and defaults changed between two releases.
    test · Running drift across two consecutive vLLM minor releases lists at least one default change with both values, and the report regenerates matrix.md for the newer tag with no check failures.

Knowledge check

QHow does SGLang's radix cache differ from vLLM's block-hash prefix cache?

SGLang stores shared prefixes as nodes in a radix tree and matches token by token, so arbitrary-length prefixes are shared; vLLM hashes fixed-size blocks, so sharing happens only at block granularity.

QWhy does SGLang order requests by longest prefix match before batching?

Requests that share cached prefixes run together, so their shared KV nodes stay resident and the hit rate is higher than FIFO ordering would give.

QWhat does TensorRT-LLM fix at build time that vLLM decides at runtime?

Maximum batch size, sequence lengths, plugin choices and quantization format are baked into the engine; vLLM picks kernels and shapes per request.

QWhat is the cost of TensorRT-LLM's compilation approach?

A new engine must be built for each model, GPU type and shape configuration, which takes minutes to hours and limits flexibility.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • Both lesson deliverables written with commit hashes and path references.
  • Comparison table complete for all three engines.
  • All subtopics marked completed.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →