Pick the best draft length for speculative decoding

Why it matters Choosing the draft length is the main tuning knob when deploying speculative decoding, and the right k depends on the acceptance rate measured in production.

In speculative decoding a small draft model proposes k tokens and the big model verifies them in one pass. If each draft token is accepted with probability alpha independently, one verify step yields on average E(k) = (1 - alpha^(k+1)) / (1 - alpha) tokens (k + 1 when alpha is 1), counting the bonus token the target always produces.

Write spec_plan(alpha, c, k_max). c is the cost of one draft forward relative to one target forward. One step costs k * c + 1 target forwards, so the speedup over plain decoding is E(k) / (k * c + 1). Try k = 1 to k_max and return (best_k, expected_tokens, speedup) for the k with the highest speedup, ties going to the smaller k. Round nothing.

Signaturedef spec_plan(alpha, c, k_max)

Example

alpha 0.8, c 0.1, k_max 6 gives (6, 3.951424, 2.46964).

Understand the idea

Speculative decoding is like a junior writer drafting the next few words and a senior editor approving them in one glance. If the editor accepts each word with probability alpha, the run of accepted words stops at the first rejection, and the editor always adds one word of their own. Worked example: alpha 0.5, k 2. Expected tokens = 1 + 0.5 + 0.25 = 1.75. If a draft forward costs 0.1 of a target forward, a step costs 1.2, so speedup = 1.75 / 1.2 = 1.46. Rule: E(k) = (1 - alpha^(k+1)) / (1 - alpha), speedup = E(k) / (k c + 1). More draft tokens help less and less because later ones are rarely accepted. Teams measure alpha on real traffic and pick k from this curve.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplespec_plan(0.8, 0.1, 6)
  • Sample 2: costly draftspec_plan(0.6, 0.5, 8)
  • Test 3: perfect draftspec_plan(1.0, 0.05, 4)
  • Test 4: bad draftspec_plan(0.1, 0.3, 5)