Unit 5 of 12 · about 4 hours · explain, implement
Sampling and token-selection kernels and guided-decoding integration
A token-selection kernel is correct only for the distribution after the request's constraints. Faster selection that reads a stale grammar mask changes the output contract even when logits are unchanged.
You'll be able to
- Implement masked greedy and filtered stochastic selection with a declared filter order and tie policy.
- Preserve per-request grammar and random state through changing batch membership.
- Separate mask construction, transfer and token-selection costs at the serving boundary.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Fused filtered selectionFlashInfer Documentation
FlashInfer documentation: Parameters
filter_apply_order,deterministic,generator,seedandoffset, and the input-dtype Note (page read 2026-10-14, release 0.7.1)Use the parameter contract, not the sampled IDs printed in the example as a reproducibility target. Leave speculative sampling to the next section.
- Greedy and stochastic sampler branchesMini-SGLang - Kernel, Model Runner and Overlap Boundaries
Sampler.prepare,Sampler.sampleandsample_impl - Constraint configuration and sampler integrationvLLM structured outputs (v0.31.0)
Offline Inference,
StructuredOutputsParamsexample, and the opening deprecated-field warningFor the kernel boundary, also open https://docs.vllm.ai/en/v0.31.0/api/vllm/v1/worker/gpu_model_runner/ and locate
sample_tokens: grammar bitmask application precedes_sample. Skip online-server setup and reasoning-model examples.
Focus on
- Mask illegal vocabulary entries before selection; normalize only allowed mass. An all-disallowed state must terminate or error explicitly, never silently sample from an invalid row.
- Greedy selection needs no probability materialization. Use a separate greedy branch, not division by zero temperature; state the tie rule and non-finite policy.
- Top-k then top-p renormalizes before its nucleus threshold, while joint filtering uses a different contract. Pin the order, threshold crossing and tie handling before comparing distributions.
- Grammar state and random state belong to requests, not batch slots. A deterministic kernel or equal seed does not guarantee equal IDs across libraries with different random-number consumption.
Common mistakes · 3
- Treating grammar masking as ordinary token-ID filtering without advancing grammar state after the accepted token.
- Replaying captured sampling with an unchanged explicit random offset. Repeated random draws are not independent sampling.
- Calling schema-conforming output factually correct. Syntax constraints do not establish task quality.
Try it yourself
Closed-book, before checking anything
[0.6, 0.25, 0.15] with top-k 2 and top-p 0.7. Top-k-first filtering renormalizes to [12/17, 5/17, 0], so its nucleus retains only token 0; intersecting with the original nucleus, which is this card's CPU reference for joint and not a claim about FlashInfer's kernel output, retains tokens 0 and 1. Then forbid token 0 before filtering and show that no legal selection can emit it. Add an all-disallowed error case and a two-request state test that swaps batch slots after each selected token.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why can equal seeds still give different sampled IDs in two implementations?Answer
The algorithms can consume random draws differently. Test the filtered distribution, and require token identity only when the random mapping is also fixed.
2.Why not apply a grammar mask after top-k?Answer
Top-k may have discarded all legal alternatives. The engine must define and preserve ordering so selection operates on the legal distribution.
3.What should happen when a grammar row allows no token?Answer
Handle a declared terminal state or raise an explicit error. Normalizing zero mass or all negative-infinite logits is not a valid sampler.
You're done when
You explain the filter-order example, forbid illegal tokens under both selection modes, and preserve each request's constraint state across slot changes and cleanup.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 11 more in the section
- FlashInfer DocumentationFlashInfer Project · required
Use the current attention, PageAttention, sampling, JIT and CUDA Graph interfaces while implementing. Pin the version and supported GPU architecture, and validate dispatch and fallback over the real workload shape distribution.
- Mini-SGLang - Kernel, Model Runner and Overlap BoundariesSGLang Project · support
Trace how FlashAttention or FlashInfer, KV layouts, tensor parallel communication and overlap scheduling meet the model runner. Identify the fallback and state-reset boundary before attempting a change.
- vLLM structured outputs (v0.31.0)vLLM Project · required
Read Offline Inference and the API-field migration warning; trace grammar bitmask application before sampling in the versioned model-runner API.
Also in this section
- FlashInfer: Efficient and Customizable Attention Engine for LLM Inference ServingFlashInfer Project · primary
Read the storage heterogeneity, plan and run separation, load-balanced scheduling, customization, CUDA Graph compatibility and end-to-end evaluation. Use it to connect serving-shaped attention kernels to dynamic workloads and dispatch constraints.
- AI Systems Performance Engineering - Chapters 18 and 19, decode kernels and engine optimizationsChris Fregly (O'Reilly) · required
Read "Optimized Decode Kernels" in Chapter 18 (FlashMLA, ThunderMLA, FlexDecoding), then the Chapter 19 sections on kernel autotuning, occupancy-aware kernel selection, hot-swappable kernels and CUDA-graph prewarming. Choose one bounded critical path to verify.
- AI Systems Performance Engineering companion code - Chapter 18Chris Fregly · required
Start with paged_attn_common.py, the dense versus paged layout pair, CUDA graph bucketing and the vLLM integration pair. Run correctness tests first, then a hardware-compatible benchmark with newly captured artifacts.
- FlashAttention-2: Faster Attention with Better Parallelism and Work PartitioningTri Dao · required
Derive online-softmax state, memory traffic and work partitioning. Implement only a small oracle-backed version or use the CS336 assignment; production kernel tuning belongs to the GPU track.
- CS336 Assignment 2 - FlashAttention and Triton SectionsStanford University · required
Complete the relevant derivation, PyTorch reference and Triton sections using your own code. Follow assignment integrity: use external help for concepts, invariants, tests and profiling, not copied solutions or edited answer code.
- UCSD CSE 291A (Spring 2026) - Guest lecture: Engineering vLLMUC San Diego · support
Read the scribe notes, Sections 4 and 5: CPU overhead, the API server and renderer, synchronous and asynchronous engine-core scheduling, GPU-side input preparation, piecewise CUDA graphs and the hybrid kernel strategy.
- vLLM CUDA Graphs design (v0.31.0)vLLM Project · support
Use the capture modes, batch-size buckets and piecewise splitting around attention to explain what a graph replay can and cannot include.
- LLM Inference: From scratch, one token at a time - Module 07Tushar Amrit · support
Work the Attention Kernels module for the decode-attention memory traffic and the paged-attention gather before the matching units.
- AI Performance Engineering - Kernel Optimization, Profiling and AttentionWafer · reference
A curated index. Use Sections 2 and 3 only to find a kernel or profiler source the other entries lack.
- TensorRT-LLM Architecture OverviewNVIDIA · support
Use the runtime-optimization section to compare graph replay, overlap scheduling and backend dispatch with your selected engine. Record current version and hardware support before treating a path as available.
- PyTorch compiler troubleshooting guide (2.14)PyTorch · reference
Read Graph break, Guards, Recompilation and Dynamic Shapes; run
TORCH_LOGSset tograph_breaksandrecompileson a small serving-shaped function.