@YichiZ03: 3-min explain AI Infra, Day 6 Today we will talk about KV Cache. As the essential of LLM inferencing, understanding the…
Summary
3-min explain AI Infra Day 6 介绍 KV Cache 机制,作为 LLM 推理的核心与后续优化策略的基础,并附带 Datawhale 与 RadixArk 联合推出的 zero-to-sglang 从零构建推理引擎教程。
View Cached Full Text
Cached at: 11/19/26, 03:53 AM
3-min explain AI Infra, Day 6 🫵 Today we will talk about KV Cache. As the essential of LLM inferencing, understanding the mechanism of KV Cache is the key to understand all further optimization strategies. Full course blog please read Zero-to-SGLang: https://t.co/MfAlAutEEw https://t.co/tDPMxIhfMj
datawhalechina/zero-to-sglang
Source: https://github.com/datawhalechina/zero-to-sglang
zero-to-sglang
📚 Build SGLang from Scratch
A hands-on tutorial on LLM inference: build a mini-sglang from scratch, then read the real SGLang source.
Start from what inference really is, build a mini-sglang by hand, then read the real SGLang source
Datawhale × RadixArk
Course status: All chapters, from Part 0 through Part IV, are complete in both English and Chinese. The full companion video series is expected to be completed by the end of November 2026, with videos published on YouTube and Bilibili. Links will be added to the Syllabus below as videos are published. You can switch to 简体中文 at any time. Want to help? See Contributing.
🎯 About
Large models have moved on from the training race to the inference race. Once applications took off, inference cost and latency became the real bottleneck: on the same GPU, a good inference engine can serve several times more requests. Yet there are few tutorials on inference engines. They either stay at the concept level without touching code, or drop you straight into the SGLang source with no idea where to start.
This course fills that gap. The first half starts from the core questions of inference: why KV Cache exists, how prefill differs from decode, what compute-bound and memory-bound actually mean. The middle part walks you through building a mini-sglang from scratch: forward pass, generation, KV Cache, HTTP serving, Continuous Batching, Paged KV Cache, RadixAttention, added one at a time. The last part returns to the real SGLang, explains how its cutting-edge optimizations are actually implemented, and finally shows you how to land your first solid PR in SGLang.
The project is jointly launched by Datawhale and RadixArk (the company founded by the SGLang team). SGLang is technically solid and actively iterated in the inference framework space. If you like this project, please give the official SGLang repository a ⭐.
✨ What you will learn
- 📖 Understand inference: KV Cache, prefill/decode, compute-bound vs. memory-bound, and what these concepts actually mean
- 🏗️ Build the engine: write a mini-sglang from 0 to 1, with every step landing in code
- 🛠️ Read the real engine: how RadixAttention, Paged KV Cache and Continuous Batching are implemented inside SGLang
- ⚙️ Touch the frontier: quantization, hierarchical caching, DP Attention / EP / PP, Prefill-Decode disaggregation
- 🚀 Join open source: learn profiling and trace analysis, and walk through the full SGLang PR workflow
📋 Prerequisites
- Python: fluent in Python, with basic software engineering habits
- Deep learning basics: familiar with PyTorch and the fundamentals of neural networks
- Math: linear algebra and probability; knowing roughly how matrix multiplication and attention are computed is enough
- GPU programming (optional): knowing CUDA basics helps, but is not required. Part I fills in the gaps from scratch
- Hardware (optional): Part I needs no GPU; most of Part II can be debugged on CPU, but the full implementation and performance tests are best done on a GPU (cloud is fine)
🔗 Links
- Repository: https://zero-to-sglang.datawhale.cc/
- PDF download: English · 中文版 (all releases)
- SGLang: https://github.com/sgl-project/sglang
- mini-sglang reference implementation: https://github.com/sgl-project/mini-sglang
📖 Syllabus
Status legend: ✅ Done 🔄 In progress 📝 Needs polish 🚧 Planned ⏸️ Paused
Chapters in bold are written by SGLang core members.
| Chapter | Key content | Status |
|---|---|---|
| Part 0 — Before you learn | ||
| 0.1 Coding Ethics and Open-Source Spirit | Own your code, communicate like a human, profile first, the open-source spirit | ✅ |
| 0.2 Deploy Your First SGLang Server | Environment setup; run Qwen3-0.6B with SGLang on your own GPU | ✅ |
| Part I — Foundations (concepts only, no code, no GPU) | ||
| 1. Introduction to LLM | What an LLM is and how it evolved, the Transformer architecture, autoregressive generation, key concepts | ✅ |
| 2. Introduction to Inference | Training vs. inference, prefill/decode, compute-bound vs. memory-bound, the Roofline model | ✅ |
| 3. Introduction to GPU | GPU architecture basics, how LLM inference executes on a GPU, understanding inference bottlenecks from the hardware | ✅ |
| 4. KV Cache: The Core Data Structure of Inference | Deriving KV Cache from attention, cache lifecycle, quantitative memory analysis | ✅ |
| 5. Introduction to Benchmark | Core metrics such as TTFT / TPOT / ITL / Goodput, percentiles and tail latency, how to design, run and read a benchmark | ✅ |
| Part II — Build Your Own Mini SGL | ||
| 1. mini-sglang: What an Inference Engine Looks Like | Overall architecture of an inference engine, module breakdown, roadmap for this part | ✅ |
| 2. Inside SGLang: The Path of a Request (Concepts) · Code Walkthrough | The full lifecycle of a request from arrival to response | ✅ |
| 3. Your First 200 Lines: Forward Pass and Generation (Concepts) · Code Walkthrough | A source walkthrough of embeddings, attention, the LM head, and generation | ✅ |
| 4. KV Cache: From O(n²) to O(n) (Concepts) · Code Walkthrough | Implementing the cache and optimizing attention computation | ✅ |
| 5. HTTP and Concurrent Requests (Concepts) · Code Walkthrough | HTTP basics and request flow; implementing isolation, streaming, and cancellation | ✅ |
| 6. Continuous Batching and the Scheduler (Concepts) · Code Walkthrough | Continuous batching, scheduler state, resource limits, and latency/throughput tradeoffs | ✅ |
| 7. Paged KV Cache and Memory Management (Concepts) | Paged KV Cache and GPU memory management | ✅ |
| 8. RadixAttention and Prefix Caching (Concepts) · Code Walkthrough | RadixAttention and prefix caching | ✅ |
| 9. Multi-process & Tensor Parallelism(Concepts) · Code Walkthrough | Multi-process execution and tensor parallelism | ✅ |
| 10. Speculative Decoding (Concepts) · Code Walkthrough | Drafting and verification, greedy and sampling-based acceptance, rejection correction, and performance tradeoffs | ✅ |
| Part III — Advanced Inference Technique (deep into the real SGLang) | ||
| 1. Attention Backends (FlashInfer / Triton / FA3 / FlashMLA) | Backend responsibilities, tiled Attention, implementation tradeoffs, and selection | ✅ |
| 2. Quantization and Low-Precision Inference | Numeric formats and scales, Decode speedup and KV Cache capacity, accuracy tradeoffs, quantization labels and loading | ✅ |
| 3. Hierarchical Caching | L1/L2/L3 cache tiers, prefix matching, backup and restoration, prefetching and performance tradeoffs | ✅ |
| 4. Scaling Out: DP Attention, EP, PP | TP scaling limits, DP Attention, EP, PP, and combined parallelism | ✅ |
| 5. Prefill-Decode Disaggregation | Prefill interference, request handoff, KV transfer costs, resource allocation, and workload evaluation | ✅ |
| Part IV — How to Make Contribution to SGLang (optional) | ||
| 1. Deploying SGLang with the Cookbook | Recipe selection, launch configuration, service validation, and a small benchmark | ✅ |
| 2. Measuring It All: Profiling and Trace Analysis | Profiling fundamentals and a merged PR case study: traces, code changes, and validation | ✅ |
| 3. SGLang PR Workflow | Open-source collaboration, PR lifecycle, CI and review, and first contributions | ✅ |
🗓️ Writing schedule
Writing began on August 24, 2026. All chapters are complete in both English and Chinese as of November 10, 2026.
| Part | Schedule | Status |
|---|---|---|
| Part 0 — Before you learn | Done | ✅ |
| Part I — Foundations | Done | ✅ |
| Part II — Build Your Own Mini SGL | Done | ✅ |
| Part III — Advanced Inference Technique | Done | ✅ |
| Part IV — How to Make Contribution to SGLang | Done | ✅ |
| Full zero-to-sglang companion video series | Expected completion: end of November 2026. YouTube / Bilibili links will be added to the Syllabus as videos are published. | 🔄 |
🚀 Quick start
# Clone the repository
git clone https://github.com/datawhalechina/zero-to-sglang.git
cd zero-to-sglang
# Install dependencies as each chapter requires
Learning path
1️⃣ Read Part I to build an overall picture of inference (no GPU needed)
2️⃣ Follow Part II to build a mini-sglang from 0 to 1
3️⃣ Move to Part III and understand the frontier optimizations against the real SGLang source
4️⃣ Finish Part IV: profiling, trace analysis, and the full PR workflow
Project structure
zero-to-sglang/
├── course-material/ # Course text
│ ├── ch/ # Chinese edition (read online at /ch/)
│ │ ├── part0/ # Part 0: Before you learn
│ │ ├── part1/ # Part I: Foundations (complete)
│ │ ├── part2/ # Part II: Build Your Own Mini SGL (complete)
│ │ ├── part3/ # Part III: Advanced Inference Technique (complete)
│ │ ├── part4/ # Part IV: How to Make Contribution to SGLang (complete)
│ │ └── WRITING_TEMPLATE.md
│ └── eng/ # English edition (read online at /eng/, complete)
│ ├── part0/
│ └── WRITING_TEMPLATE.md
├── community/ # Community corner: build logs, pitfalls, study notes
│ ├── ch/
│ └── eng/
├── docs/.vitepress/ # VitePress site config
├── README.md # Project overview (English, default)
├── README_zh.md # Project overview (Chinese)
├── README_en.md # Legacy English entry (links to README.md)
└── .gitignore # Git ignore rules
🤝 Contributing
We are an open community and welcome contributions of every kind. Before you start, please read Part 0 to understand the coding ethics and open-source spirit we expect.
1. Improve the course text
- 🐛 Found an error in the content, a formula, or code: open an issue, or fix it and open a PR
- 📝 Add to a chapter or improve the wording: open a PR. Chapter division and numbering follow the outline in the writing template; do not add, remove, or merge chapters on your own
- 🌐 Translate: help translate chapters into English following the English writing template, and put them under
course-material/eng/ - 💡 Have ideas about the course: open an issue to discuss
2. Share your practice
- 🔧 Built mini-sglang yourself following Part II? Write down the bugs you hit and how you fixed them
- ⚠️ Pitfalls from deploying SGLang or setting up the environment, or places where the docs were unclear and others deserve a warning
- 📒 Study notes written in your own words after finishing a chapter, or extra derivations and experiments
Community content goes under the matching directory in community/eng/ (English) or community/ch/ (Chinese).
How to open a PR
- Fork the repository and create a branch from
main - PR requirements are in community/eng/PR_requirement.md; check every item before submitting
❓ FAQ
Q: Can I follow the course without a GPU?
Yes. Part I involves no GPU at all. Most of the code in Part II can be debugged on CPU, but full performance verification and the deeper content of Part III are best done on a GPU (cloud is fine).
Q: Do I need to master CUDA first?
No. The course starts from inference concepts. Low-level topics such as attention backends only come in Part III, and you can catch up on CUDA as needed at that point.
💬 Reader Community
Join the zero-to-sglang reader community to learn together, ask questions, and share ideas: Join our Discord community
👥 Contributors
We thank every developer who has contributed to this project!
Special thanks
- Thanks to Datawhale and the SGLang team for supporting the project
- Datawhale: @1iyouzhen, @xuhu0115, @kangkang-Adam
- SGLang: @Ccyest, @fcranzhou, @Hayden727
- Thanks to @Sm1les for the help and support
- Thanks to every developer who has contributed to this project ❤️
🎓 Citation
If zero-to-sglang helps your research or work, please cite it:
@misc{zero_to_sglang2026,
title = {zero-to-sglang: Building an LLM Inference Engine from Scratch},
author = {TODO},
year = {2026},
url = {https://github.com/datawhalechina/zero-to-sglang},
note = {GitHub repository}
}
⭐ Star History
If this project helps you, please give it a Star ⭐️!
📄 License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Helping more people learn to build LLM inference engines, systematically
Made with ❤️ by Datawhale & RadixArk
Similar Articles
@ZeroZ_JQ: https://x.com/ZeroZ_JQ/status/2066380476970103028
The article redefines KV Cache from an engineering perspective, pointing out that it is not just an inference optimization technique, but becomes a runtime infrastructure for reusing already computed results in the Agent era, helping AI avoid redundant reasoning.
@akshay_pachaar: 12 KV caching techniques I’d learn to optimize LLM inference. An LLM generates one token at a time, but each new token …
该推文总结了优化 LLM 推理的 12 种 KV 缓存技术,包括滑动窗口、跨层共享、MLA、量化、前缀复用、分页、驱逐和 GQA/MQA 等,帮助开发者根据具体瓶颈选择合适的组合。
@MaxForAI: http://Z.ai and this ZCube paper from Tsinghua—worth a read for anyone in Infra. Many people's first reaction when talking about AI infra is still GPU, memory, quantization, and inference frameworks. But once you get into long context and Prefill-Decode separation, the network is no longer just a 'supporting role' in the data center. Every...
ZCube is a new network architecture that flattens the topology and mixes single/multi-rail access to optimize KV Cache transmission in long-context and PD separation scenarios. In the GLM-5.1 production cluster, it achieved a 33% reduction in switch/optical module costs, a 15% increase in GPU inference throughput, and a 40.6% decrease in TTFT P99.
@polydao: This Stanford lecture on AI inference will teach you more about how LLMs work in production than most ML courses > Clau…
A Stanford lecture on AI inference emphasizes practical bottlenecks like KV-cache and techniques like speculative decoding and continuous batching, offering more real-world insight than typical ML courses.
@shao__meng: 9 episodes, 230 minutes — @jbhuang0604's video series "AI Training and Inference" explains the fundamentals of foundation model training and inference, covering the entire training/inference stack: single-GPU memory → thousand-GPU parallelism → cheap fine-tuning → inference acceleration → small-model distillation → inference RL…
A blogger shares Jia-Bin Huang's 9-episode, 230-minute video series "AI Training and Inference", which systematically covers the training and inference architecture of foundation models: from ZeRO/FSDP memory optimization, five-dimensional parallelism, LoRA variants, speculative decoding, on-policy distillation, GRPO reinforcement learning, to AdamW/Muon optimizers and LLM serving.