Pidoku

Sampling and Structured Output

Module 18 Lesson 18.e 50 min Difficulty 3/5

Prerequisites 12.o, 18.b


Before you start: words you need#

WordPlain meaning
LogitsOne raw score per vocabulary token. Softmax turns them into probabilities.
GreedyAlways take the highest-scoring token. Requested with temperature = 0.
Argmax-invariantA change to the scores that can never change which token is on top (temperature, top-k, top-p, min-p).
Logits processorA step that edits the scores before sampling: penalties, bias, a grammar mask, your own code.
Constrained decodingForbidding every token a grammar does not allow next, so the output is guaranteed to match it.
BitmaskOne bit per vocabulary token saying “allowed” or “forbidden”, packed into 32-bit integers.
Gumbel-max trickAdding a particular kind of random noise to each logit and taking the argmax; the result is a sample from the softmax distribution.

1. What is it?#

The forward pass ends with one row of scores per request: a number for every vocabulary token. Choosing a token from that row is sampling, and it is where every request’s own settings (temperature, top-p, penalties, seed) are applied. vLLM does it for the whole batch at once, on the GPU, in a fixed order that decides how the settings interact.

Structured output adds one step at the front. A grammar, running on the CPU in the engine core, computes which tokens are legal next and forbids the rest. That guarantees valid JSON (or a regex, or a choice from a list), and it is the one feature whose cost is paid in engine-core CPU time rather than GPU time.

The sampling strategies themselves are 12.o. This lesson is how vLLM v0.32.0 runs them. Facts checked on 12 November 2026.


2. Why does it matter?#

  • The order changes results. Whether a penalty runs before or after the greedy choice decides whether temperature = 0 respects it. Knowing the order answers most “why did my setting do nothing?” questions.
  • Mixed batches are the norm. One step holds requests with different temperatures, seeds and grammars. Doing that without a per-request Python loop is what keeps sampling cheap.
  • JSON mode is everywhere. Tool calling (18.i) and structured extraction depend on it, and heavy structured-output traffic can make the engine core’s CPU the bottleneck.

3. Simple analogy#

A hiring panel scores every candidate (the logits). First a rule-book strikes out the ineligible (the grammar mask and allowed lists). Then adjustments that can change the ranking are applied (penalties for people already hired). If the panel must take the top scorer (greedy), it stops there. Otherwise it narrows to a shortlist (top-k, top-p, min-p) and draws one name at random from it. Shortlisting never changes who is first, so a greedy panel skips it.


4. Tiny example: what temperature = 0 ignores#

SettingWith temperature = 0
top_p, top_k, min_pNo effect. They cannot change the argmax.
repetition_penalty, frequency_penalty, presence_penaltyApplied. They can change the argmax.
logit_bias, min_tokens, allowed and bad token lists, grammarApplied.
seedNo effect; nothing random happens.

5. Technical explanation#

The order, as documented#

The older runner’s Sampler (vllm/v1/sample/sampler.py) states its pipeline in its docstring:

1. If logprobs are requested: keep the raw logprobs (or raw logits) to return.
2. Convert logits to float32.
3. Apply allowed token ids whitelist.
4. Apply bad words exclusion.
5. Apply logit processors which are not argmax-invariant, i.e. that can impact
   greedy sampling.
     a) Min tokens processor
     b) Logit bias processor
6. Apply penalties
     a) Repetition penalty   b) Frequency penalty   c) Presence penalty
7. Sample the next tokens:
     a) If not all_random, perform greedy sampling. If all_greedy, return.
     b) Apply temperature.
     c) Apply logit processors which are argmax-invariant, by default the min_p processor.
     d) Apply top_k and/or top_p.
     e) Sample the next tokens with the probability distribution.
     f) Return random samples where temperature >= epsilon (1e-5), greedy otherwise.
8. Gather the logprobs of the top max_num_logprobs and sampled token (if requested).
9. Return the final SamplerOutput.

The key idea is argmax-invariance. Everything that can change the winner runs before the greedy choice, so greedy decoding respects it. Everything that cannot is skipped for greedy requests.

The same pipeline in Model Runner V2#

Model Runner V2, the default runner (18.a), reimplements this in Triton under vllm/v1/worker/gpu/sample/. Its Sampler.apply_sampling_params runs, in order:

  1. Copy logits to float32 (only if some request in the batch needs processing).
  2. Logit bias (LogitBiasState), which also handles allowed token IDs and min_tokens.
  3. Penalties (PenaltiesState). The source notes the order matters: “bias adds, penalties scale, so the two do not commute.”
  4. Bad words, then any custom logits processors.
  5. Thinking budget (ThinkingBudgetState): forces the end-of-reasoning marker when a reasoning model exceeds its thinking_token_budget (18.i). It runs last so nothing can undo it.
  6. Temperature, then min-p, then top-k / top-p.
  7. Gumbel sampling: add noise generated in the kernel from the request’s seed and position, take the argmax. At temperature 0 it is a plain argmax.

The grammar bitmask is applied before all of this, in vllm/v1/worker/gpu/structured_outputs.py (a Triton kernel adapted from xgrammar’s). The observable behaviour, including the table in section 4, is the same in both runners.

Two MRV2 details matter for performance. A fused sampler (FlashInfer’s top-k/top-p sampling kernel, or an XPU one) is used when no request in the batch is greedy or has an explicit seed and no processed logprobs are requested. And per-request state is reached through an index (idx_mapping) instead of being expanded per logit row, which makes speculative decoding’s many rows per request simple (18.f).

One batch, many settings#

Per-request values are rows of tensors in the persistent batch, written once when a request joins. Each stage is one vectorised operation over the batch. In the older runner a mixed batch computes both a greedy and a random result for every row and picks per row:

Python
sampled = torch.where(
    sampling_metadata.temperature < _SAMPLING_EPS,
    greedy_sampled,
    random_sampled,
    out=greedy_sampled,  # Reuse tensor
)

Flags short-circuit the common cases: all_greedy skips the random path, all_random skips the argmax, and a batch where no request uses penalties skips that stage entirely.

Seeds and reproducibility#

A request with a seed gets its own random stream, advanced only by that request (in MRV2 the noise is a pure function of seed and position, so no generator state is kept). Two caveats:

  • The logits can differ in their last bits between runs, because batch composition changes the order of floating-point operations and which kernel variant runs. A different last bit can flip a near-tie.
  • Reproducibility across vLLM versions, GPUs or batch shapes is not promised.

Batch invariance (VLLM_BATCH_INVARIANT=1, in beta) constrains kernel choices so a request’s output does not depend on its batch-mates, at some cost in speed.

Logprobs and prompt logprobs#

logprobs: 5 needs the top five log-probabilities per row per step. The older runner computes a full-vocabulary log-softmax first; MRV2 finds the top-k from the logits and computes log-probabilities only for those, which lowers peak memory. prompt_logprobs needs a distribution at every prompt position, so the last-row trick of 18.b no longer applies; MRV2 chunks this, even inside one prompt, to avoid memory spikes.

Custom logits processors#

A logits processor is a class that receives the batch’s logits and may edit them. It declares whether it is argmax-invariant so the sampler can place it. Processors are loaded at startup (--logits-processors) and work on the whole batch, with a hook telling them when requests join and leave. Per-request Python callbacks are gone: a function called once per request per token cannot be part of a vectorised pipeline.

Structured output: where the grammar lives#

JSON
{
  "messages": [{"role": "user", "content": "Give me a user record."}],
  "structured_outputs": {"json": {"type": "object", "properties": {"name": {"type": "string"}}}}
}

StructuredOutputsParams accepts exactly one of json (a JSON schema), json_object, regex, choice, grammar (a context-free grammar) and structural_tag. The OpenAI response_format field maps onto the same machinery.

StepWhereCode
Compile the schema into a grammarEngine core, on a thread pool, when the request arrivesStructuredOutputManager.grammar_init
Compute the allowed-token bitmask for the next stepEngine core, on the CPU, while the GPU runs the forward passStructuredOutputManager.grammar_bitmask
Apply the bitmask to the logitsWorker, on the GPUInside sample_tokens
Advance the grammar with the sampled tokenEngine core, in update_from_outputaccept_tokens

Compilation is asynchronous. A complex schema can take tens or hundreds of milliseconds. The request gets the status WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR; the scheduler skips it without blocking those behind it (17.a) until its grammar is ready.

The bitmask is one bit per vocabulary token per request: about 12.5 kB per request for a 100,000-token vocabulary. It is computed during the forward pass (16.g) and sent with sample_tokens. When more than 128 requests in a batch are constrained, masks are filled in parallel on a thread pool, 16 requests per task.

The grammar is the authority. If it rejects a sampled token, which should be impossible, the request is ended with an error rather than left inconsistent.


6. Under the hood#

Backends#

BackendNotes
xgrammarCompiled grammars; the first choice for most JSON schemas
guidance (llguidance)Broad JSON-schema coverage; lazy evaluation; needs a fast tokenizer
outlinesRegex and schema support through finite-state machines
lm-format-enforcerA character-level enforcer; uses Python regex syntax

--structured-outputs-config.backend selects one; the default is auto, which “will make opinionated choices based on request contents and what the backend libraries currently support, so the behavior is subject to change in each release.” In v0.32.0, auto tries xgrammar first; if xgrammar rejects the request it falls back to guidance, or to outlines when guidance cannot handle the schema or the tokenizer (non-Tekken Mistral). Lark grammars for Mistral’s Tekken tokenizer go straight to guidance. Pin a backend if you need identical behaviour across upgrades.

The pipeline in code#

The sampling order for three requests: free text with every knob turned, and two steps of a JSON-constrained request.

Go
package main

import (
	"fmt"
	"math"
	"math/rand"
	"sort"
)

var vocab = []string{"{", "}", `"name"`, ":", `"Ada"`, ",", "hello", "the", "42", "\n"}

type params struct {
	temperature       float64
	topK              int     // 0 = off
	topP              float64 // 1 = off
	minP              float64 // 0 = off
	repetitionPenalty float64 // 1 = off
}

func softmax(logits []float64) []float64 {
	m := math.Inf(-1)
	for _, l := range logits {
		m = math.Max(m, l)
	}
	sum := 0.0
	p := make([]float64, len(logits))
	for i, l := range logits {
		p[i] = math.Exp(l - m)
		sum += p[i]
	}
	for i := range p {
		p[i] /= sum
	}
	return p
}

func show(stage string, logits []float64) {
	p := softmax(logits)
	fmt.Printf("%-28s", stage)
	for i := range vocab {
		if math.IsInf(logits[i], -1) {
			fmt.Printf("%7s", "-")
		} else {
			fmt.Printf("%7.3f", p[i])
		}
	}
	fmt.Println()
}

// sample follows the order documented in vLLM's Sampler class.
func sample(raw []float64, allowed []bool, history []int, p params, rng *rand.Rand) int {
	logits := append([]float64(nil), raw...)
	show("raw", logits)

	// Structured output: the grammar's bitmask removes tokens before anything else.
	if allowed != nil {
		for i := range logits {
			if !allowed[i] {
				logits[i] = math.Inf(-1)
			}
		}
		show("grammar bitmask", logits)
	}

	// Step 6: penalties. These can change the argmax, so they come before greedy.
	if p.repetitionPenalty != 1 {
		for _, t := range history {
			if logits[t] > 0 {
				logits[t] /= p.repetitionPenalty
			} else {
				logits[t] *= p.repetitionPenalty
			}
		}
		show("repetition penalty", logits)
	}

	// Step 7a: greedy. temperature == 0 stops here.
	if p.temperature < 1e-5 {
		best := 0
		for i := range logits {
			if logits[i] > logits[best] {
				best = i
			}
		}
		return best
	}

	// Step 7b: temperature.
	for i := range logits {
		logits[i] /= p.temperature
	}
	show(fmt.Sprintf("temperature %.1f", p.temperature), logits)

	// Step 7c: min_p. Drop tokens whose probability is below minP x the top probability.
	if p.minP > 0 {
		probs := softmax(logits)
		top := 0.0
		for _, v := range probs {
			top = math.Max(top, v)
		}
		for i := range logits {
			if probs[i] < p.minP*top {
				logits[i] = math.Inf(-1)
			}
		}
		show(fmt.Sprintf("min_p %.2f", p.minP), logits)
	}

	// Step 7d: top_k, then top_p, over the tokens sorted by probability.
	order := make([]int, len(logits))
	for i := range order {
		order[i] = i
	}
	sort.SliceStable(order, func(a, b int) bool { return logits[order[a]] > logits[order[b]] })
	if p.topK > 0 {
		for _, i := range order[min(p.topK, len(order)):] {
			logits[i] = math.Inf(-1)
		}
		show(fmt.Sprintf("top_k %d", p.topK), logits)
	}
	if p.topP < 1 {
		probs := softmax(logits)
		cum := 0.0
		for _, i := range order {
			if cum >= p.topP {
				logits[i] = math.Inf(-1)
			}
			cum += probs[i]
		}
		show(fmt.Sprintf("top_p %.2f", p.topP), logits)
	}

	// Step 7e: draw one token from what is left.
	probs := softmax(logits)
	r, cum := rng.Float64(), 0.0
	for i, v := range probs {
		cum += v
		if r < cum {
			return i
		}
	}
	return len(probs) - 1
}

func main() {
	fmt.Printf("%-28s", "")
	for _, v := range vocab {
		fmt.Printf("%7q", v)
	}
	fmt.Println()
	raw := []float64{1.2, 0.3, 2.0, 0.1, 1.5, 0.2, 3.1, 2.8, 0.9, -1.0}
	rng := rand.New(rand.NewSource(3))

	fmt.Println("\nA. free text: temperature 0.8, repetition penalty 1.3, min_p 0.05, top_k 5, top_p 0.9")
	history := []int{6} // "hello" was already generated
	tok := sample(raw, nil, history, params{0.8, 5, 0.9, 0.05, 1.3}, rng)
	fmt.Printf("sampled: %q\n", vocab[tok])

	fmt.Println("\nB. JSON mode at the start of an object: the grammar allows only \"{\"")
	allowed := make([]bool, len(vocab))
	allowed[0] = true
	tok = sample(raw, allowed, nil, params{temperature: 0.8, topP: 1, repetitionPenalty: 1}, rng)
	fmt.Printf("sampled: %q   (the model preferred %q; the mask overruled it)\n", vocab[tok], vocab[6])

	fmt.Println("\nC. JSON mode after {\"name\": — the grammar allows a string or a number")
	allowed = make([]bool, len(vocab))
	allowed[4], allowed[8] = true, true
	tok = sample(raw, allowed, nil, params{temperature: 0, topP: 1, repetitionPenalty: 1}, rng)
	fmt.Printf("sampled (greedy): %q\n", vocab[tok])
}

Output (the header row runs the quoted token names together):

                                "{"    "}""\"name\""    ":""\"Ada\""    ",""hello"  "the"   "42"   "\n"

A. free text: temperature 0.8, repetition penalty 1.3, min_p 0.05, top_k 5, top_p 0.9
raw                           0.055  0.022  0.122  0.018  0.074  0.020  0.368  0.273  0.041  0.006
repetition penalty            0.068  0.028  0.151  0.023  0.091  0.025  0.222  0.336  0.050  0.008
temperature 0.8               0.054  0.017  0.146  0.014  0.078  0.015  0.237  0.398  0.037  0.003
min_p 0.05                    0.057      -  0.154      -  0.082      -  0.249  0.419  0.039      -
top_k 5                       0.059      -  0.160      -  0.086      -  0.259  0.436      -      -
top_p 0.90                        -      -  0.170      -  0.091      -  0.275  0.463      -      -
sampled: "the"

B. JSON mode at the start of an object: the grammar allows only "{"
raw                           0.055  0.022  0.122  0.018  0.074  0.020  0.368  0.273  0.041  0.006
grammar bitmask               1.000      -      -      -      -      -      -      -      -      -
temperature 0.8               1.000      -      -      -      -      -      -      -      -      -
sampled: "{"   (the model preferred "hello"; the mask overruled it)

C. JSON mode after {"name": — the grammar allows a string or a number
raw                           0.055  0.022  0.122  0.018  0.074  0.020  0.368  0.273  0.041  0.006
grammar bitmask                   -      -      -      -  0.646      -      -      -  0.354      -
sampled (greedy): "\"Ada\""

In run A, "hello" loses first place to "the" at the repetition-penalty row: that could not happen if penalties ran after the greedy choice. In run B one token is legal, so the model’s preference is irrelevant. In run C the temperature is zero, the mask leaves two candidates, and the higher of those two wins although neither was the model’s overall favourite.


7. Performance implications#

  • Sampling is cheap when uniform. All-greedy or all-random batches skip half the work; no penalties skips the history tensors; MRV2’s fused sampler handles top-k/top-p in one kernel.
  • Greedy or seeded requests in a batch disable MRV2’s fused sampler for that step.
  • Logprobs cost per step, in GPU work and in bytes sent to the API server. Prompt logprobs cost far more and bypass the last-row optimisation.
  • Structured output costs engine-core CPU every step, in proportion to the number of constrained requests. The engine core is single-threaded at its heart; heavy JSON traffic can make it the bottleneck while the GPU has room.
  • The mask is on the async critical path. The mask for step N+1 needs step N’s token (17.d), so slow mask filling stretches every step.

8. Production implications#

  • Pin the structured-output backend for reproducibility. auto may change its choice between releases.
  • Describe the schema in the prompt as well. A guarantee of valid output is not a guarantee of good output. A model forced into a schema it was not trying to follow fills it with poor content.
  • Reasoning models: the constraint must start after the reasoning section ends. That is why StructuredOutputsConfig carries reasoning_parser and enable_in_reasoning (18.i).
  • Speculative decoding: drafts must satisfy the grammar too; validate_tokens trims invalid drafts before verification (18.f).
  • Watch engine-core CPU with top or the process metrics when JSON traffic grows. Scaling out replicas helps; a bigger GPU does not.

9. Common mistakes#

  1. Setting top_p with temperature = 0 and expecting a difference. There is none.
  2. Expecting a seed to give bit-identical output across batch sizes, GPUs or versions.
  3. Requesting prompt_logprobs by default in a client library and paying for it on every call.
  4. Writing a per-request logits processor. Processors operate on the whole batch.
  5. Assuming regex syntax is portable between backends. lm-format-enforcer uses Python regex; the others use a Rust-style dialect.

10. Hands-on exercise#

  1. In run A, set the repetition penalty to 1.0. Which token is sampled now? Then set temperature to 0 with the penalty at 1.3 and confirm the penalty still decides.
  2. In run C, change the temperature to 1.5. Over many seeds, how often is "42" chosen? Is the output always valid?
  3. Against a real server, send the same request with a JSON schema 50 times concurrently and 50 times without one. Compare tokens per second and watch the engine core’s CPU in top.
  4. Read Sampler.sample in vllm/v1/worker/gpu/sample/sampler.py. List the conditions under which the fused sampler is not used.

11. Interview questions#

  1. What does “argmax-invariant” mean, and why does it decide where a processor runs?
  2. A request sets temperature: 0 and top_p: 0.5. What effect does top_p have?
  3. Where is the grammar bitmask computed, where is it applied, and why are those different places?
  4. Why does a structured-output-heavy workload sometimes saturate CPU before GPU?
  5. How does the Gumbel-max trick let MRV2 sample without materialising probabilities?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in