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

Sampling and token-selection kernelsStructured and guided decoding integration
1

Read

In this order, only the parts listed

0 of 3 done

  1. Fused filtered selectionFlashInfer Documentation

    FlashInfer documentation: Parameters filter_apply_order, deterministic, generator, seed and offset, 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.

  2. Greedy and stochastic sampler branchesMini-SGLang - Kernel, Model Runner and Overlap Boundaries

    Sampler.prepare, Sampler.sample and sample_impl

  3. Constraint configuration and sampler integrationvLLM structured outputs (v0.31.0)

    Offline Inference, StructuredOutputsParams example, and the opening deprecated-field warning

    For 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.

2

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.
3

Try it yourself

Closed-book, before checking anything

Write a CPU reference for probability vector [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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 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. 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