13.7 Rejection sampling and residual distributions
A language model’s sampler emits one token per forward pass, and each forward pass reads every weight once. The fastest way to decode more quickly without changing what the model says is to let something cheap guess ahead: a draft (an n-gram table, a prompt lookup, a small model) proposes several tokens, and the target model checks all of them in a single forward pass. For greedy decoding the check is easy, since you only ask whether the draft guessed the argmax. For sampled decoding it is subtle. The accepted text must be distributed exactly as if the target had sampled it alone, or the speedup silently changes the model’s output distribution, and no evaluation would ever attribute that drift to the decoding trick.
Concepts from other sections (11)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Prompt lookup: drafting by copying what followed the most recent earlier occurrence of the context’s suffix. Read more: 21.6 Speculative decoding: n-gram, prompt-lookup, and model drafts in AI Engineering
- greedy decoding: taking the single most likely token at every step; a beam of size 1. Read more: 10.4 Beam search, generic over a step function in AI Engineering
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics
- Trie: a rooted tree whose edges carry characters so that each node spells the string on its path. Read more: 12.2 Trees and tries, longest-prefix match
- Accept-or-resample: accept a drafted when , else sample from the residual; the emitted token’s law is exactly . Read more: 23.9 Speculative decoding in the engine in AI Engineering
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- speculative decoding: drafting several tokens cheaply and verifying them in one target-model pass, preserving the output distribution. Read more: Chapter 20: Inference Engines and GPU Deployment in AI Engineering
- Acceptance rate: accepted draft tokens over proposed draft tokens; per token, . Read more: 21.6 Speculative decoding: n-gram, prompt-lookup, and model drafts in AI Engineering
- Standard error: , the estimated standard deviation of the sample mean. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- Random variable: a number assigned to each outcome of a random experiment; a discrete one is a table of values and probabilities. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
This section supplies the piece of probability that makes the check exact: an acceptance test and a residual distribution. You will derive von Neumann’s classic rejection sampler, adapt it to the setting where there is no time to retry, and prove (first algebraically, then by enumerating a small example by hand) that the result samples the target distribution for every draft. The code lives in course/solutions/python/tinyllm/prob/rejection.py, with the signatures and error rules in the contract course/contracts/py/tinyllm/prob/rejection.pyi and the draw order in spec/sampling.md (draw accounting).
This section builds on Categorical sampling: inverse CDF, Gumbel-max, alias method, whose sample_categorical, inverse CDF, and UniformSource it reuses (see sampling.py). It also assumes the language of Random variables, expectation, variance, and normal draws by Box-Muller and the uniforms produced by Modular arithmetic, hashing, and PCG32 in Python.
Learning objectives
- Derive von Neumann’s rejection sampler and show that the number of tries is geometric with mean .
- Explain why the acceptance test must be the strict comparison for floating-point uniforms.
- Derive the residual distribution and prove that accept-or-resample outputs exactly .
- Show that the acceptance probability equals .
- Implement the five functions so that their sums and draw order match a Rust port bit for bit.
Notation
Section titled “Notation”The section uses the following symbols throughout.
| Symbol | Meaning | Type / shape |
|---|---|---|
| number of ids (the vocabulary) | integer | |
| the target distribution (the big model’s sampler output) | float64[n], sums to 1 | |
| the proposal distribution (the draft) | float64[n], sums to 1 | |
| a draft token, drawn from | integer in | |
| independent uniforms on | float | |
| the acceptance ratio of | float | |
| the acceptance probability | float in | |
| total variation distance | float in | |
| the residual distribution, | float64[n] | |
| an envelope: for every | float |
Von Neumann’s rejection sampler
Section titled “Von Neumann’s rejection sampler”Start with the classic problem. Suppose is cheap to sample but you want samples of . If for every , repeat the following: draw , draw , and accept when . On one try,
Conditioned on acceptance, has probability : exactly the target. Each try is an independent coin with success probability , so the number of tries is geometric, with mean and variance . A loose envelope costs time, never correctness. An envelope that is too small ( for some ) is a different matter: it caps the acceptance of at 1 and under-samples it, which is why the contract checks the envelope before drawing anything.
The acceptance test, exactly
Section titled “The acceptance test, exactly”Every acceptance in this section is a comparison of a uniform against a ratio, so it pays to get that comparison exactly right. For uniform on and any , . The comparison must be strict. For a continuous , would be the same, but floating-point uniforms are discrete (PCG32 gives multiples of ), and the point combined with would accept a token the target never produces. Notice also what happens at the other end: with , every is below it, so an under-proposed token is always kept.
Accept, or draw from the residual
Section titled “Accept, or draw from the residual”Speculative decoding cannot use von Neumann’s retry loop as it stands. The target’s forward pass has already happened, and a rejected position must produce a token right away; another try would mean another forward pass. So change the procedure: keep with probability , and on rejection draw from a carefully chosen fallback. To find that fallback, look at what acceptance keeps. The kept mass of token is
and the total kept mass is . Since and both distributions sum to 1, : the closer the draft is to the target, the more of it is accepted. What is missing from after acceptance is , which sums to . Normalizing that missing mass gives the residual distribution.
The theorem
Section titled “The theorem”You now have both halves of the procedure, and they fit together exactly. Draw , accept with probability , and otherwise draw . Then
Nothing was assumed about beyond its being a distribution: a bad draft makes the method slow, never wrong. When , and the residual is undefined, but then and the residual is never sampled; the contract returns in that case so that the function stays total.
Determinism
Section titled “Determinism”Correct in distribution is not quite enough. The same request, with the same seed, should accept and reject the same drafts in the Python reference and in the Rust engine of Speculative decoding in the engine in AI Engineering. The sums in and are therefore left-to-right loops over ascending ids in float64, and , come from the request’s generator in the order fixed by Speculative decoding: n-gram, prompt-lookup, and model drafts. The Rust engine repeats the same arithmetic. numpy’s np.sum sums pairwise and can differ in the last bit, which would move a boundary of the residual’s CDF and change a draw.
Working it by hand
Section titled “Working it by hand”The theorem is short enough that it is worth checking on numbers. Take four ids, with target and draft . The table lays out each token’s ratio, its chance of being kept when proposed, the mass it keeps, and the mass left missing.
| id | kept mass | |||||
|---|---|---|---|---|---|---|
| 0 | 1/2 | 1/4 | 2 | 1 | 1/4 | 1/4 |
| 1 | 1/4 | 1/2 | 1/2 | 1/2 | 1/4 | 0 |
| 2 | 1/4 | 0 | (never proposed) | 0 | 1/4 | |
| 3 | 0 | 1/4 | 0 | 0 | 0 | 0 |
The acceptance probability is ; the residual mass is , and the residual is . Now add up the output distribution token by token. Id 0 is kept with mass , plus the rejected mass times its residual probability , for a total of . Id 1 is kept with mass and has residual 0, so it gets . Id 2 is never proposed but comes back through the residual: . Id 3 is proposed a quarter of the time and always rejected, so it gets 0. That is exactly .
Follow one concrete draw too. The draft proposes ; rejects it, and walks the residual’s CDF to id 2. With instead, id 1 is kept and is never looked at. These are the first cases the tests check.
Designing the interface
Section titled “Designing the interface”The module exposes five functions: the single acceptance test, the acceptance probability, the residual, one speculative step, and a full von Neumann sampler.
def rejection_accept(p_x: float, q_x: float, u: float) -> bool # u < p_x / q_xdef acceptance_probability(p: ArrayLike, q: ArrayLike) -> float # sum min(p, q)def residual_distribution(p: ArrayLike, q: ArrayLike) -> NDArray # normalize(max(0, p - q)); p if p == qdef speculative_step(p, q, x: int, u_accept: float, u_resample: float) -> tuple[int, bool]def rejection_sample(p, q, m: float, rng: UniformSource, max_tries: int = 10000) -> tuple[int, int]speculative_step resamples with sample_categorical from Categorical sampling. rejection_sample draws exactly two uniforms per try, proposal first. The contract has every error rule.
Building it step by step
Section titled “Building it step by step”The implementation follows the derivation closely, and each choice traces back to one of the principles above.
First, both inputs are distributions over one vocabulary. Every function starts by checking and with the rules from Categorical sampling (1-D, finite, non-negative, summing to 1) and that their shapes match. A draft over a different vocabulary is a bug, not a case to handle.
Second, acceptance is one strict comparison. As shown above, u < p_x / q_x has probability exactly for on the discrete grid in . No explicit min is needed, because already accepts. If , the draft proposed a token it gave probability 0, so the function raises rather than divides.
Third, the acceptance probability and the residual’s normalizer are left-to-right sums: a plain loop over ascending ids, so the Rust port gets the same last bit and the residual’s CDF has the same boundaries.
Fourth, the residual is , or when . happens exactly when everywhere, which for two distributions means ; then nothing is ever rejected, and returning a copy of keeps the function total without aliasing the caller’s array.
Fifth, one speculative step is accept, or one draw from the residual. If the acceptance test passes, return without reading ; otherwise call sample_categorical(residual, u'). That draw order is part of the parity contract with the Python and Rust speculative decoders.
Sixth, von Neumann needs a checked envelope and two uniforms per try. Check and everywhere first, then loop: propose with one uniform, accept with another when , and return the token and the number of tries. A bounded loop turns a pathological envelope into an error rather than a hang.
The first two functions are the acceptance test and its probability.
def rejection_accept(p_x: float, q_x: float, u: float) -> bool: _check_u(u, "u") # u in [0, 1) if not q_x > 0.0: raise ValueError(f"q_x must be > 0 (q proposed this token), got {q_x!r}") if not p_x >= 0.0: raise ValueError(f"p_x must be >= 0, got {p_x!r}") # P(u < r) = min(1, r) for u uniform on [0, 1): strict, so p_x = 0 (r = 0) # never accepts and r >= 1 always does. return u < p_x / q_x
def acceptance_probability(p: ArrayLike, q: ArrayLike) -> float: a, b = _pair(p, q) # two checked distributions, same shape s = 0.0 for pi, qi in zip(a.tolist(), b.tolist()): # ascending ids, left to right s += min(pi, qi) # the kept mass of token i return s # = 1 - TV(p, q)On the hand example, the per-token kept masses are , so . The residual and the speculative step come next.
def residual_distribution(p: ArrayLike, q: ArrayLike) -> NDArray: a, b = _pair(p, q) r = np.maximum(a - b, 0.0) # what acceptance left missing from p z = 0.0 for v in r.tolist(): # not np.sum: pairwise summation differs in the last bit z += v if z <= 0.0: # p == q: nothing is ever rejected, but the result must stay a distribution. return a.copy() return r / z
def speculative_step(p, q, x: int, u_accept: float, u_resample: float) -> tuple[int, bool]: a, b = _pair(p, q) if not 0 <= x < a.size: raise ValueError(f"draft token {x} outside [0, {a.size})") _check_u(u_resample, "u_resample") # validated even when not used if rejection_accept(float(a[x]), float(b[x]), u_accept): return int(x), True # accepted: u_resample is not read return sample_categorical(residual_distribution(a, b), u_resample), FalseTrace the hand example’s draw through this code: , and rejects; the residual is with running sums , and first falls below at id 2. With the function returns (1, True). In the disjoint-support case , and , so the residual is itself: a useless draft is always rejected and the output is still a draw of .
Finally, the von Neumann sampler checks its envelope and loops.
def rejection_sample(p, q, m: float, rng, max_tries: int = 10000) -> tuple[int, int]: a, b = _pair(p, q) if not m >= 1.0: # an envelope below 1 cannot cover p raise ValueError(f"the envelope m must be >= 1, got {m!r}") if (a > m * b).any(): # p_x > m q_x: x would be under-sampled i = int(np.flatnonzero(a > m * b)[0]) raise ValueError(f"m = {m} is not an envelope: p[{i}] = {a[i]} > m q[{i}] = {m * b[i]}") for tries in range(1, max_tries + 1): x = sample_categorical(b, rng.uniform()) # proposal uniform first if rng.uniform() < a[x] / (m * b[x]): # then the acceptance uniform; b[x] > 0 here return x, tries raise RuntimeError(f"no acceptance in {max_tries} tries")sample_categorical never returns an id with (its comparison is strict), so the division is safe; and the envelope check guarantees that any id with has . The full solution is rejection.py.
Why this design
Section titled “Why this design”Consider the cost first. rejection_accept is ; acceptance_probability and residual_distribution are ; speculative_step is (validation, the residual, and an inverse-CDF draw) and is only computed in full on rejection. rejection_sample costs checks plus a geometric number of tries with mean , each for the inverse CDF.
The residual beats a retry loop for speculative decoding. A von Neumann retry would also be exact, but each retry would need another target forward pass; the residual produces a token from the pass already done, so every verified position yields exactly one token.
Explicit loops are chosen over np.sum deliberately. numpy’s pairwise sum is more accurate for long arrays, but it is not what the Rust port computes. The sums here are of at most a vocabulary of non-negative terms, where left-to-right error is tiny, and bit parity matters more.
One tradeoff is accepted knowingly: validating and on every call costs per step. For a 50 000-token vocabulary that is small next to a forward pass, and it turns a draft/target vocabulary mismatch into an immediate error.
What can go wrong
Section titled “What can go wrong”A correct implementation has to survive a specific set of checks. The hand example anchors the definitions: its ratios, , and the residual must come out exactly, and its output distribution, enumerated exactly, must equal . Strict acceptance is a boundary check: rejects and never accepts, because discrete uniforms make wrong. When the target dominates, must accept every , so under-proposed tokens are always kept. Bad acceptance arguments (, , ) must raise, since a silent answer biases the output.
The statistical checks cover the theorem itself. The enumerated acceptance rate must equal , because the speculative decoder reports it as its acceptance rate. The residual must be a distribution (non-negative, summing to 1, with ), since sample_categorical demands one. For random and in eighths, the speculative output distribution must equal exactly by enumeration, and 20000 seeded draws on arbitrary distributions must match under a chi-square test. For von Neumann, one try must accept with probability exactly , and the mean number of tries must equal within 4 standard errors.
The remaining boundary and unit checks protect parity and the edges. must give a copy of : no 0/0, and no aliasing of the caller’s array. Disjoint supports give and residual , so a useless draft is slow, not wrong. The normalizer must be a left-to-right loop over ascending ids for bit parity with the Rust port. Mismatched shapes and non-distributions must raise, because draft and target vocabularies must match. An accepted draft must not look at , because the draw order is part of the parity contract, and a draft outside the vocabulary or with must raise, because draft and proposal disagreeing is a bug. Von Neumann must draw the proposal uniform first and then the acceptance uniform, two per try, to be reproducible across languages, and it must raise for , for , and when nothing is accepted within max_tries, since a wrong envelope silently biases.
The classic mistakes are worth naming one by one, with the line of the solution that avoids each.
Warning: Accepting on accepts a token with whenever . The solution returns
u < p_x / q_x.
Warning: Writing the ratio upside down, or “capping” it by inverting it when it exceeds 1, keeps over-proposed tokens and drops under-proposed ones. The ratio is
p_x / q_x, and does the capping for free.
The residual has its own traps. Using or resamples the tokens the draft over-proposed; the solution computes np.maximum(a - b, 0.0). Forgetting to normalize makes sample_categorical reject the residual, or leaves its CDF ending below 1; the solution divides r / z. Handling as 0/0 produces NaN, and returning the caller’s array lets a later in-place edit corrupt the target; the solution returns a.copy() when z <= 0.0.
On rejection, resampling from , from , or simply returning the draft means the output is no longer , because accepted tokens are effectively counted twice; the solution samples residual_distribution(a, b). Running von Neumann without , or without checking it, makes accepted tokens follow -ish weights rather than ; the solution accepts on a[x] / (m * b[x]) after checking m >= 1 and a <= m * b. And summing with numpy’s pairwise np.sum produces last-bit differences against the Rust port, which the explicit left-to-right loops avoid.
Where this leads
Section titled “Where this leads”The residual draw uses sample_categorical and the UniformSource generator type from Categorical sampling, and every probability above rests on the uniform random variables and independence of Random variables, expectation, variance, and normal draws by Box-Muller. Looking forward, Speculative decoding: n-gram, prompt-lookup, and model drafts in AI Engineering calls one speculative_step per draft position and reports acceptance_probability as its acceptance rate, building on the token sampler of Sampling and logit processors. Speculative decoding in the engine ports the same logic to Rust and is held to the same accept and reject decisions.
Production systems use the same ideas at larger scale. vLLM’s RejectionSampler (vllm/v1/sample/rejection_sampler.py) performs batched acceptance over a whole draft tree on the GPU, recovering tokens from the residual. Hugging Face assisted generation uses the same residual for model drafts in _speculative_sampling (transformers/generation/utils.py). NumPy’s Gamma and binomial samplers (numpy/random/src/distributions/distributions.c) use rejection with tight squeeze functions to avoid evaluating the target.
Further reading
Section titled “Further reading”- Devroye, Non-Uniform Random Variate Generation (1986), ch. 2.3.
- Leviathan, Kalman, and Matias, “Fast Inference from Transformers via Speculative Decoding” (2023), appendix A.1.
- Chen et al., “Accelerating Large Language Model Decoding with Speculative Sampling” (2023).
Key terms
Section titled “Key terms”- Rejection sampling: drawing from a proposal and accepting each draw with a probability chosen so that accepted draws follow the target .
- Envelope: a constant with for all ; von Neumann’s sampler needs one, and its mean cost is tries.
- Acceptance ratio: ; the draft token is kept with probability .
- Acceptance probability: , the chance a draft token is kept.
- Total variation distance: ; it satisfies .
- Residual distribution: , the normalized mass that acceptance leaves missing from .
Summary
Section titled “Summary”- Keeping a draft with probability keeps exactly of every token’s mass; the total kept is .
- What rejection removes is exactly the residual , so resampling from its normalized form restores token for token: the output of
speculative_stepis distributed as for every . - “Accept when ” with uniform on has probability exactly ; "" counts one extra point and accepts tokens never produces.
- Von Neumann’s sampler accepts a proposal with probability ; each try succeeds with probability , so the cost is a geometric number of tries with mean .
- Left-to-right sums and a fixed draw order make the Python and Rust implementations agree on every decision for the same seed.
Review questions
Section titled “Review questions”-
Why is the residual and not or ?
Answer
After acceptance each token has of its target mass; what is missing is , the tokens the draft under-proposed. would resample the tokens the draft over-proposed, which already have more than enough, and mixes both; neither adds up to .
-
Why does
rejection_acceptneed nomin(1, ...)?Answer
is always below 1, so when the test
u < ris always true: the acceptance probability is already . Writing an explicit cap is harmless, but “capping” by inverting the ratio when it exceeds 1 would turn the always-accept case into a partial one and drop under-proposed tokens. -
On acceptance, why must
speculative_stepreturn without using ?Answer
Correctness: the theorem’s accept branch outputs itself, contributing ; letting change the result there would replace accepted tokens with residual draws and break that term. Parity: the contract says matters only on rejection, so the Python speculative decoder and the Rust engine agree on every decision for the same uniforms.
-
Why does
residual_distributionreturna.copy()when and nota?Answer
means , so the residual is never sampled, but the function must still return a valid distribution and is the natural choice. Returning the caller’s array would let a later in-place edit of the result (a mask, a temperature) silently change the target distribution itself.
-
In von Neumann’s sampler, what does a loose envelope (large ) cost, and what does a too-small one break?
Answer
A loose envelope only costs time: each try accepts with probability , so the mean number of tries is . A too-small one breaks correctness: for an with the acceptance ratio exceeds 1 and is effectively capped, so is drawn with probability below and the others are over-sampled. That is why the function checks the envelope before drawing.
-
In the hand example, but the output still produces id 2 a quarter of the time. Where does that probability come from?
Answer
Entirely from the residual. Id 2 is never proposed, so its kept mass is 0, but its missing mass makes up half of , so its residual probability is . The rejection probability is , giving .