Unit 8 of 11 · about 5 hours · implement
Integrating a custom operator with vLLM, SGLang and FlashInfer
Engines keep the scheduler and memory; kernels win only behind a stable interface with registration, workspace and fallback contracts.
You'll be able to
- Build and register one custom operator with stream, lifetime and fallback contracts.
- Meet a workspace, metadata, layout and capture-safe kernel interface for one paged operation.
- Compare vLLM, SGLang and FlashInfer component boundaries for that operation.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Serving-kernel wrapper contractFlashInfer
FlashInfer 0.7.1 documentation,
BatchDecodeWithPagedKVCacheWrapper: constructor withfloat_workspace_bufferandkv_layout,planwithindptr,indicesandlast_page_len,runwithqandpaged_kv_cache,workspace_sizeandreset_workspace_buffer;use_cuda_graphbuffer rules - Plan-run and custom-op registration pathFlashInfer
BatchDecodeWithPagedKVCacheWrapper.planandruninflashinfer/decode.py;get_batch_decode_modulewithregister_custom_opandregister_fake_opin the same file - Alternative runtime architectureSGLang
Section 2, programming model with
genandfork; Section 3, RadixAttention reuse with cache-aware scheduling as the alternative component boundary
Focus on
- Caller-owned workspace comes first: allocate the 128 MB float buffer aligned to 16 bytes, call
planwithindptr,indicesandlast_page_len, then reuse the plan across layers withrun.plannever runs inside a graph ortorch.compile. - A graph-safe wrapper (
use_cuda_graph=True) fixes the batch size and keeps metadata in caller-providedindptr,indicesandlast_page_lenbuffers sized for the largest page count. Re-plan outside capture to update their contents; a different batch size needs a new wrapper. - Register the custom op with a fake implementation for shape inference, keep execution on the current PyTorch stream, and keep an eager fallback that passes the same differential tests.
Common mistakes · 3
- Calling
planinside a captured graph. Planning copies metadata on the host; onlyrunwith stable bindings captures. - Forgetting workspace alignment or zero-initialization on first use. Split-KV scratch then reads garbage.
- Shipping the fast path without a fallback. Unsupported dtypes, layouts or shapes must route to a tested eager path.
Try it yourself
Closed-book, before checking anything
plan a batch of 7 requests in NHD layout with page_size = 16, and run one layer. State which buffers must stay stable for graph capture and which eager fallback runs on an unsupported dtype.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does a custom op need a fake implementation?Answer
Shape inference, compilation and autotuning need output metadata without launching kernels. The fake implementation supplies it; without it capture and compilation fail.
2.What is fixed once a graph-safe decode wrapper is created?Answer
The batch size and the caller-provided
indptr,indicesandlast_page_lenbuffers, plus the workspace binding. A plan with another batch size raises; re-planning rewrites those buffers in place, so capturedruncalls keep reading stable addresses.3.Where does a custom kernel sit relative to vLLM, SGLang and FlashInfer?Answer
vLLM owns scheduling plus paged blocks, SGLang owns radix reuse plus program-level caching, FlashInfer owns the attention and sampling kernels. Your op replaces one kernel behind a stable plan-run boundary, not a scheduler.
Practice
- LeetGPU 83 Fused Residual Add RMS Norm, integrated locally
Challenge 83 in
challenges/medium/83_fused_residual_add_rms_norm/challenge.py: implementsolve, pass the hosted tests, then wrap it as atorch.library.custom_opwith a fake implementation and an eager fallback and integrate it into one small endpoint step with differential testsRun it on LeetGPU or locally against
reference_implfromchallenge.pyas in the CUDA primitives section. Do not stop at the hosted score: the local integration with fallback is the deliverable.
You're done when
Your op passes differential tests through both the custom path and the eager fallback, with a pinned plan-run interface and a stated unsupported-shape policy.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 12 more in the section
- SGLangSGLang Authors · support
Read the runtime and RadixAttention design, then inspect the repository path for one kernel or prefix-reuse interaction. Use it as an alternative architecture in the integration defense.
- FlashInferFlashInfer Project · support
Use the repository as the serving-kernel baseline and interface reference. Reconstruct workspace planning, layouts, dispatch and stream behavior for one selected operation before comparing your path.
Also in this section
- AI Systems Performance Engineering - Chapters 13, 15 and 16Chris Fregly · primary
Read Chapter 13 on profiling and tuning PyTorch, Chapter 15 on inference parallelism, decoding and routing, and Chapter 16 on profiling and debugging inference. Keep Chapters 17 to 19 for GPU-9 and depth.
- AI Systems Performance Engineering companion code - Chapters 12 to 16Chris Fregly · required
Use compatible examples from
code/ch12throughcode/ch16. Trace whether each optimized path changes a kernel, graph, compiler choice, scheduler or library dispatch, then integrate one bounded custom path into a realistic operator or small endpoint. - AI Performance Engineering - Inference EnginesWafer · reference
A curated index. Use Section 4 only to find the introducing paper and implementation for the mechanism your measurement points to.
- PagedAttention and vLLMvLLM Authors · required
Study block-based key-value allocation, sharing and scheduling interaction. Trace logical token positions to physical blocks in one engine run and quantify fragmentation and memory-capacity effects.
- LeetGPU - Inference Kernel SetAlphaGPU · required
Choose three bottleneck-matched challenges from 74 GPT-2 Block, 83 Fused Residual Add RMS Norm, 84 SwiGLU MLP Block, 87 Speculative Decoding Verification, 93 Llama Transformer Block and 96 INT8 KV Cache Attention. Integrate one result locally rather than stopping at the hosted submission.
- GPU Microbenchmark and Kernel Suite - IntegrationRoadmap-Final · support
Complete the real tensor or model-operation integration, dispatch and fallback requirements. Report compilation and invocation overhead, workload frequency, correctness or quality and the end-to-end no-benefit regime.
- PyTorch 2.14 ProfilerPyTorch · reference
Read the Overview example plus the API reference for
torch.profiler.profile(activities,schedule,on_trace_ready,record_shapes,with_stack),torch.profiler.record_functionandexport_chrome_trace. Use it for exact profiler and NVTX-range call contracts missing from the book. - Orca (OSDI 2022)USENIX · support
Read Sections 3 to 4 for iteration-level scheduling and selective batching, and Section 6 for the engine microbenchmark and end-to-end latency-throughput method. Use it as the continuous-batching mechanism behind the book summary.
- Sarathi-ServearXiv · support
Read Sections 3 to 4 for chunked-prefill stall-free batching and token-budget selection, and Section 5 for capacity and overhead method. Use it as the chunked-prefill mechanism behind the book summary.
- Fast Inference from Transformers via Speculative DecodingPMLR · support
Read Sections 2 to 3 for the draft-verify-accept loop, the acceptance rule and the walltime-versus-operations analysis. Use it for the verification cost model behind the engine guides.
- vLLM Documentation - Automatic Prefix CachingvLLM Project · reference
Read Automatic Prefix Caching (vLLM v0.31.0) for hash-based block reuse, full-block caching, reverse-order freeing and the multimodal hashing example. Use it for engine behavior the papers do not version.
- Transformer Inference ArithmeticKipply · reference
Read kv cache, capacity, latency calculations, batch sizes and flops counting for per-token KV bytes, weight-capacity arithmetic and memory-bound versus compute-bound latency floors. Use it to derive endpoint bounds before measuring.