Accept or reject draft tokens in speculative sampling
Why it matters Speculative decoding speeds up serving of large models 2 to 3 times with identical outputs in distribution.
Speculative sampling lets a small draft model propose tokens and keeps the big model's distribution exact.
Write spec_accept(draft_tokens, q, p, u, u_extra). draft_tokens has length k. q is (k, V) draft probabilities, p is (k + 1, V) target probabilities. u is a list of k uniform numbers. For each i, accept token x = draft_tokens[i] if u[i] < min(1, p[i, x] / q[i, x]). On the first rejection, sample a replacement from the residual r = max(p[i] - q[i], 0) normalised, using inverse CDF with u_extra (first index where cumsum > u_extra), and stop. If all k are accepted, sample a bonus token from p[k] with u_extra the same way. Return the list of output tokens.
def spec_accept(draft_tokens, q, p, u, u_extra)Example
if p equals q at every step, every draft token is accepted (ratio 1) and one bonus token is added.
Understand the idea
Speculative sampling speeds up generation: a small draft model proposes k tokens, and the big model checks them all in one pass. Each draft token is accepted with probability min(1, p / q), where p is the big model's probability and q the draft's. On the first rejection, a replacement is drawn from the leftover distribution max(p - q, 0), normalised. This makes the output follow p exactly. Worked example: V = 3, draft [0, 2]. Step 0: q = [0.5, 0.3, 0.2], p = [0.4, 0.4, 0.2], ratio 0.4 / 0.5 = 0.8, u = 0.5 < 0.8, accept 0. Step 1: q = [0.1, 0.2, 0.7], p = [0.3, 0.5, 0.2], ratio 0.2 / 0.7 = 0.286, u = 0.6, reject. Residual [0.2, 0.3, 0] normalises to [0.4, 0.6, 0], cumulative [0.4, 1.0, 1.0]; with u_extra 0.5 the first index above it is 1. Output [0, 1]. Rule: accept while u[i] < min(1, p[i, x] / q[i, x]); on rejection, sample from the normalised residual by inverse CDF with u_extra and stop; if all k pass, sample a bonus token from p[k] the same way. Used in: fast inference servers.
Shapes and data flow
draft k tokens, q (k, V) target p (k+1, V) from one forward pass accept prefix -> residual sample on reject or bonus from p[k]