ELLMEngineering Large
Language Models
Download PDF

Chapter 22

Sampling, Structured Output, and Speculative Decoding

On this page

Decoding is part of the model's externally visible semantics. Acceleration may reorganize computation, but it must preserve the declared probability distribution, constraints, random-number mapping, and termination behavior unless approximation is explicitly allowed.

The running service's weight-only model gives a 4.7 ms floor per ordinary small-batch decode step. Speculative decoding tries to amortize one target-weight pass across several committed tokens. Whether it helps depends on proposal cost, acceptance, and verification work; first we need to define the distribution those tokens must follow.

The token-selection pipeline

A typical step transforms model logits through an ordered pipeline:

  1. apply vocabulary restrictions and bad-token masks;
  2. apply repetition, frequency, presence, or custom penalties;
  3. apply temperature or other score transformation;
  4. truncate with top-k, nucleus top-p, minimum probability, or a product policy;
  5. normalize and sample with a defined random stream;
  6. test stop tokens, stop strings, grammar acceptance, and length limits;
  7. commit token and KV state, detokenize incrementally, and stream.

Order matters because these operations generally do not commute. A fused implementation must match the reference order, tie rules, NaN behavior, and dtype policy. Tokenization creates additional edge cases: a stop string may span tokens, and a token byte sequence may be incomplete until later output arrives.

Greedy decoding is the special case that selects an argmax under deterministic tie policy. Sampling correctness means equality of the declared distribution, not equality of one token trace unless seeds, batching, and random-number mapping are also fixed.

Randomness and reproducibility

Counter-based random generators can derive values from a key such as request seed, logical output position, branch, and sampling substep. This makes randomness independent of physical thread scheduling and easier to preserve across dynamic batches.

Exact reproducibility across engine versions may still be impossible if floating reductions, truncation boundaries, or probability transforms change. Define a level:

  • distributional equivalence;
  • same result for fixed seed on one engine version;
  • same result across batch compositions;
  • bitwise identity across versions and hardware.

Do not promise the strongest level unless the whole logits pipeline, numeric path, and RNG mapping are controlled and regression-tested.

Structured and constrained decoding

Structured output restricts the next-token set according to a grammar, schema, regular expression, or application state. An engine compiles the constraint and maintains parser state per sequence. Regular constraints can use finite-state machinery; unbounded nesting generally requires a stack or an equivalent context-free parser. At each step the engine finds allowed tokens and masks the rest before sampling.

The hard parts are often outside the model:

  • tokenizer tokens may contain multiple characters or partial UTF-8 sequences;
  • a grammar state can have a large or tiny allowed set;
  • dynamic masks can break graph or batch compatibility;
  • state transitions and detokenization must agree;
  • fallback or repair changes semantics and latency.

Local grammar masking defines a constrained sampler; it generally does not sample the original model conditioned on the event that the complete sequence is valid. For a two-step example, let first-token probabilities for A and B both be 0.5, and let the probabilities of a valid continuation be 0.9 after A and 0.1 after B. Both prefixes remain locally legal, so first-step masking preserves 0.5/0.5. Conditioning the original full-sequence distribution on validity instead assigns 0.9/0.1. State which distribution the API implements.

An empty allowed set, an impossible schema, or exhaustion of the output budget before an accepting state needs an explicit failure result; token masking alone cannot guarantee completion. Precompute token-to-transition tables where possible, cache grammar artifacts by versioned identity, and batch sequences with compatible constraint work without starving rare grammars. Measure compile latency separately from per-token mask cost.

Beam search, best-of, and branch state

Beam search maintains multiple scored hypotheses and selects expansions under a declared sequence score, often with a length penalty or normalization. Best-of samples several candidates and returns a selected one. Both multiply KV state and scheduling work. Paged copy-on-write can share the common prefix, but diverged branches need private blocks.

Define whether non-returned candidates count against token quotas and billing, how stop rules apply, and whether streaming is possible before the winner is known. Prune and release branches promptly. A scheduler that counts one API request rather than its active branches can under-reserve memory badly.

Speculative decoding

Speculative decoding uses a cheaper proposal process to reduce sequential target-model steps. A draft proposes gamma tokens. The target evaluates the proposed positions in parallel and commits an accepted prefix plus, in common formulations, one token selected from target information at the stopping point.

A proposal is useful only when the target can verify several positions more cheaply than performing the same number of ordinary sequential decode steps.
Open full diagram ↗

A proposal is useful only when the target can verify several positions more cheaply than performing the same number of ordinary sequential decode steps.

Proposal sources include a smaller standalone model, a quantized or pruned target, early-exit layers, multiple-token prediction heads, retrieval or n-gram matches, or a tree of candidates. They differ in draft cost, acceptance, memory, training requirements, and how well they batch.

Exact stochastic verification

Let target probability be p(x) and proposal probability be q(x) for a proposed token x. Accept the proposed token with probability:

a(x) = min(1, p(x) / q(x))

If rejected, sample from the normalized positive residual:

r(x) proportional to max(0, p(x) - q(x))

This decomposition preserves the target distribution when probabilities are computed under matching histories and the correction is implemented exactly. Guard zero proposal probability, normalize stably, and apply identical target logits processors before constructing p. Vocabulary sharding may require distributed normalization or candidate exchange.

Example status: Illustrative Python excerpt; not standalone.

def verify_token(proposed, p, q, uniform):
    # Validates normalized distributions and rejects q[proposed] == 0.
    accept, residual = acceptance_and_residual(p, q, proposed)
    if uniform < accept:  # uniform is in [0, 1)
        return proposed, True
    assert residual is not None
    return sample(residual), False

acceptance_and_residual is the tested CPU helper in examples/inference_mechanisms.py; sample remains a caller-supplied categorical sampler. A proposed token with q=0 is inconsistent with the claimed proposal distribution and should be rejected as an input error, not silently repaired by clamping its probability. When p=q, acceptance is one and no residual distribution is needed.

Summing accepted mass gives sum_x min(p(x),q(x)) = 1 - TV(p,q), where TV(p,q) = 0.5*sum_x abs(p(x)-q(x)). Thus one-position acceptance measures overlap with the actual postprocessed target distribution. This identity does not predict a multi-token accepted prefix without the conditional distributions at later histories. It also explains why improving a draft's standalone accuracy need not improve acceptance.

For target [0.5,0.3,0.2] and proposal [0.2,0.7,0.1], accepted probability mass is the elementwise minimum [0.2,0.3,0.1], totaling 0.6. Rejection occurs with probability 0.4. The positive residual is [0.3,0,0.1], normalized to [0.75,0,0.25]. Adding the rejected branch's mass back gives exactly the target. The tests enumerate this mass directly, including disjoint support, rather than relying only on a noisy histogram.

Top-k, top-p, temperature, penalties, and constraints define the target distribution. Applying them differently in draft and verification can be legal if the exact acceptance/correction construction uses the resulting p and q, but it changes acceptance and implementation complexity. An approximation that skips correction must be declared and evaluated as a quality change.

Expected progress and break-even

If A is the number of accepted draft tokens, the tail-sum identity gives:

E[A] = sum from k=1 to gamma of Pr(A >= k)

The conditional acceptance probability changes with position and context, so estimate this from traces rather than assuming independent identical trials. Useful committed tokens per cycle may include an additional target token when all or part of the proposal is accepted, depending on algorithm details.

A simple break-even comparison is:

cycle_cost / expected_committed_tokens < ordinary_target_step_cost

Cycle cost includes draft, target verification, correction sampling, branch KV work, scheduler gaps, and any lost target batch capacity. Verification latency is shape-dependent and does not usually grow linearly with gamma, which is why speculation can win.

For the running service at small batch, an ordinary decode step is bounded near 4.7 ms by weight streaming. A 1B-class draft with about 2 GB of weights has a streaming floor near 0.7 ms per draft step, and target verification of several proposed positions still costs roughly one target-weight pass. Four draft steps plus one target verification therefore have an idealized floor near 4 * 0.7 + 4.7 = 7.5 ms. If the cycle commits three output tokens on average, ordinary decoding would spend about 3 * 4.7 = 14.1 ms on the same output work, so the ratio of these traffic-floor estimates is about 1.9x. A ratio of lower bounds is neither a measured speedup nor a bound on speedup: unmodeled work affects both paths. Measure complete baseline and speculative cycles, including arithmetic, correction sampling, scheduler gaps, extra KV, and changes in target batch capacity.

Choosing proposal length

Long proposals amortize a target call if acceptance remains high, but waste draft and verification work after early rejection and consume more temporary KV. Choose gamma from:

  • recent acceptance and draft confidence;
  • target/draft cycle-time curves by batch and context;
  • queue pressure and target batch opportunity cost;
  • memory reserve and graph variants;
  • domain, temperature, grammar, and request class.

Use a bounded policy or lookup table before a complex predictor. Optimize measured goodput and tail latency, not acceptance alone. The best length may be zero when the target is already efficiently batched.

Tree and multi-token proposals

A tree proposes alternatives at several future positions so target verification can recover useful progress even when the top draft path is wrong. Multiple-token prediction heads propose future tokens from a shared target representation. These approaches can reduce separate draft cost but require branch packing, attention masks, verification logic, and often model-specific training.

The scheduler sees a variable number of verification tokens per request. Grouping incompatible trees can waste padding, while separating every shape fragments batches and graph caches. Restrict to a small family of supported tree shapes unless telemetry justifies more variants.

Feature drafts and parallel block drafts

The draft need not be a separate small autoregressive model trained only on text. EAGLE-3 uses target-model features and training-time simulation of the draft's own execution. The useful intuition is distribution matching: a drafter should learn under the states and self-generated inputs it will actually encounter, not only under ideal teacher-forced prefixes.

DFlash uses a lightweight block-diffusion drafter to propose multiple positions in parallel from target context features. This removes some serial draft steps; the target still verifies the proposal. It is different from replacing the target with a standalone diffusion language model. Its published acceleration results are measurements for the reported models, workloads, and decoding setup, not a prediction for every batched service.

Proposal mechanism Main cost removed New dependency
Standalone autoregressive draft Several expensive target steps Separate weights, serial draft steps, tokenizer compatibility
Feature-conditioned draft Recomputing information already available in the target Feature taps, model-specific training, feature/KV lifetime
Multi-token prediction heads Repeated full draft forwards Head accuracy, correlated proposals, verification packing
Parallel block/diffusion draft Serial dependence inside the draft block Block shape, masks, proposal semantics, target verification
N-gram/prompt lookup Learned draft computation Repeated text and a safe fallback when matches disappear

For an original scheduling example, suppose a target step takes 6 ms. A serial four-token draft costs 4 ms and verification plus bookkeeping costs 7 ms. At three committed tokens per cycle, cost is 11/3=3.67 ms per token. A parallel draft costing 1 ms with the same verification and progress yields 8/3=2.67 ms. If its lower-quality proposals commit only 1.5 tokens, cost becomes 8/1.5=5.33 ms. Faster drafting and better acceptance must be evaluated together.

Greedy equality, stochastic distribution preservation, and same-seed output equality remain different contracts. A parallel proposal must expose whatever joint or conditional probabilities its verifier requires, or use another proven target-preserving construction. Independent per-position logits are not automatically the conditional distribution of an arbitrary tree or iterative sampler. Validate the exact deployed verification algorithm, including grammar masks and temperature, before calling it lossless.

Feature extraction can extend activation lifetimes and add cross-device traffic. A method that works well on a colocated target/draft pair may become unattractive if features cross a slow boundary. Measure the full cycle with the production batch, not only an unloaded single-stream demonstration.

Interaction with batching and KV

Different sequences accept different prefix lengths, so they advance unevenly. Commit accepted KV, discard or recycle rejected branch state, update logical positions, and ensure random streams follow logical output rather than physical verification slots.

Hybrid models add recurrent and short-convolution state to this transaction. A draft block can mutate that state beyond the accepted prefix even if attention KV is truncated correctly. Save a boundary snapshot or use a verified replay/rollback path. Test accepting zero, one, and all proposal tokens, and compare continuation logits with ordinary decode after each case. A cache-length assertion alone will miss recurrent-state corruption.

At high target batch, ordinary decode may already reuse weights well. Draft compute can contend with the target or reduce its resident batch because of extra weights and KV. At low-latency batch, eliminating target synchronization steps is often more valuable. Benchmark the joint scheduler with real arrival pressure.

Design Exercises

  1. Why must the order of logits processors be part of the API contract?
  2. Design deterministic RNG mapping for continuous batching and cancellation.
  3. How does constrained decoding affect the serving system beyond token masking?
  4. Derive speculative acceptance and the rejection correction at a high level.
  5. How would you choose proposal length online and decide when to disable speculation?
  6. Compare standalone drafts, multi-token heads, and tree proposals.

Worked Solutions

1. Processor order

Penalties, masks, temperature, and truncation generally do not commute, so reordering changes probabilities and possibly the chosen token. The contract must fix the pipeline, numeric and tie behavior, stop handling, and constraint application. A fused or distributed path is correct only if it matches that reference or the product explicitly accepts a new distribution.

2. RNG mapping

Use a counter-based generator keyed by request seed and logical output position, plus branch or subdraw indices for rejection and best-of. Do not key randomness to batch slot, CUDA thread, or scheduling iteration because regrouping would change results. Commit counters only with logical tokens, discard uncommitted branch draws by identity, and define whether retries reproduce or intentionally resample. Test across batch reshuffles, cancellation neighbors, and speculative accept/reject paths.

3. Constraints

Constraints require compilation and caching of grammar state, per-request state transitions, tokenizer-aware allowed-token computation, dynamic masks, and defined invalid-state behavior. They change CPU work, batch compatibility, graph shapes, sampling cost, and sometimes token-length distribution. The scheduler must account for compile latency and per-step cost, while semantic tests cover UTF-8 boundaries, stop sequences, schema completion, and cancellation.

4. Exact speculation

For a proposed token with target probability p(x) and draft probability q(x), accept with min(1, p(x)/q(x)). Accepted mass is the overlap between the two distributions. If rejected, sampling from the normalized positive residual max(0, p-q) supplies exactly the target mass not covered by accepted proposals. Apply the construction conditionally at each matching history, handle zero and normalization stably, and use the exact target postprocessed distribution.

5. Proposal control

Estimate expected committed tokens and full cycle cost for a small supported set of proposal lengths by batch, context, domain, temperature, and recent acceptance. Select the length with best predicted SLO-constrained goodput subject to memory reserve. Disable when draft plus verification per committed token exceeds ordinary target decode, when target batches are already efficient, acceptance collapses, memory is tight, or unsupported sampling/grammar semantics would require approximation.

6. Proposal designs

A standalone draft is flexible and needs no target modification, but carries separate weights/KV and consumes scheduling capacity. Multi-token heads share target computation and can draft cheaply, but require architecture-specific training and may have correlated errors. Trees provide alternative future paths and recover from top-path errors, but increase verification tokens, branch state, masks, and shape complexity. Compare end-to-end cycle cost, acceptance/progress, memory, training and deployment burden, batching, and exactness.