Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON speculative

Speculative decoding: draft, verify and correct

Trace accepted prefixes, derive a corrected sampling example, and test when drafting pays off.

Preparation: Autoregressive generation; probability; weighted fractions.

Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.

Section 01 / 07

Use a cheap proposal without surrendering the answer

College path. Trace accepted prefixes, derive a corrected sampling example, and test when drafting pays off. Preparation: Autoregressive generation; probability; weighted fractions. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.

An autoregressive model normally produces one token, then uses that token to produce the next. A smaller draft model can propose several tokens quickly. The target model checks those proposals together, potentially accepting several in one iteration. The target remains responsible for the final distribution under the exact sampling algorithm. The draft is a proposal mechanism, not an authority. Speed comes from arranging work differently, not from making the target’s prediction problem disappear. Poor proposals, expensive drafts or large verification costs can remove the benefit.

Distinguish greedy verification from distribution-preserving speculative sampling. Greedy verification accepts agreement with the target argmax and stops at the first mismatch. Sampling needs acceptance probabilities and a correction distribution; simply accepting likely-looking words is not sufficient. Distributional equivalence means the same probability law under assumptions, not necessarily the identical sequence for the same random seed.

Worked example. A draft proposes three tokens. If the target accepts the first two and rejects the third, the first two form a reusable prefix. A corrected next token replaces the rejected proposal. Later draft tokens conditioned on the rejected token cannot automatically be retained. The following iteration starts from the verified sequence.

Draft prefix → target verification → accepted prefix + corrected token

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why is checking only that a proposed sentence looks plausible insufficient?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Plausibility does not preserve the target model’s probabilities or greedy decisions. Verification must follow a defined algorithm at each conditional position.

Section 02 / 07

Parallel checks still respect causal order

The target can score a short proposed continuation in a single forward pass using a causal mask. Each proposed position sees only the prefix before it, just as it would in sequential processing. These computations can run together because the draft has supplied the candidate tokens. But correctness still depends on acceptance in order. Once a proposal is rejected, the later conditional context is wrong. Parallel scoring therefore does not mean that output positions become independent or that the target reads the true future.

For candidate tokens x_1 through x_gamma, target distributions p_i are conditioned on the original prefix and preceding draft tokens. They are valid for output only while that preceding draft prefix is accepted. The target pass can also provide a next-position distribution after an entirely accepted draft block. Cache implementations must trim rejected speculative states and retain only the verified prefix.

Worked example. Suppose the target’s greedy choices agree with draft tokens one and two, but differ at three. Accept positions one and two, emit the target choice at three, and discard any later candidates. A score for position four based on the rejected third token belongs to a different history, even if its highest-scoring token happens to look reasonable.

p_i = P_target(x_i | prefix, x_1, …, x_(i−1))

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Can a fourth draft token be accepted independently after the third token fails?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Not in the simple sequential-prefix procedure. Its distribution was conditioned on a history that was not accepted. More elaborate tree methods require their own valid verification logic.

Section 03 / 07

Accept proposals in the right proportion

For sampling, call the target probability p and the draft probability q for a proposed token. Accept that proposal with probability the smaller of one and p divided by q. A token proposed too often by the draft is accepted only some of the time. A token proposed less often than the target would use it can be accepted whenever it appears. This local rule is only one part of the algorithm: rejected mass must also be corrected. The probabilities must refer to the same prefix and compatible token choices.

The unconditional accepted mass for token x is q(x) min(1,p(x)/q(x)) = min(p(x),q(x)). This identity explains why correction is needed. A sampled proposal has q(x)>0; avoid evaluating an undefined ratio for unsampled zero-probability entries. Temperature and other sampling transformations must be included consistently in the distributions whose law is being preserved.

Worked example. Let the target assign A and B probabilities 0.6 and 0.4, while the draft assigns 0.8 and 0.2. A is accepted with probability three quarters; B is always accepted. Accepted mass is therefore 0.6 for A and 0.2 for B. The total acceptance probability is 0.8, leaving 0.2 rejection mass.

a(x) = min(1, p(x)/q(x)); accepted mass = min(p(x),q(x))

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. If the draft proposes A and a uniform random number is 0.9, do you accept it?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. The acceptance threshold is 0.75. A uniform draw below that threshold would accept it; 0.9 triggers correction.

Section 04 / 07

Correct rejected mass instead of quietly biasing output

After a rejection, the correction distribution gives probability to tokens that the draft under-proposes relative to the target. Compute the positive part of target probability minus draft probability, then normalize it. In our two-token example, the only deficit is for B. The correction therefore chooses B. Adding accepted mass and corrected rejection mass recovers the target probabilities. This is the key reason the method can preserve quality in a precise probabilistic sense. It does not mean every approximate drafting scheme is exact.

Define r(x) = max(p(x)−q(x),0)/Z, with Z the sum of positive differences. Since both p and q sum to one, Z equals one minus the total accepted mass. Then min(p,q) + Z r = p componentwise. If p=q, Z=0 and rejection has zero probability; the correction distribution is not needed. Numerical rounding and implementation details require care in practice.

Worked example. For p=(0.6,0.4) and q=(0.8,0.2), positive differences are zero and 0.2. Normalization gives correction probabilities zero and one. Add rejection mass 0.2 to B’s accepted mass 0.2, obtaining 0.4. A remains at 0.6. Always resampling from p after rejection would instead produce 0.72 for A and 0.28 for B in this example.

r(x) = max(p(x) − q(x), 0) / sum_y max(p(y) − q(y), 0)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why not simply sample from the original target distribution after a rejection?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Because the accepted proposals already contributed part of the target mass. Resampling from the full target would double-count some probability and bias the result; the residual correction accounts for what is missing.

Section 05 / 07

Estimate useful tokens per verification round

A draft block only helps when enough of its prefix survives verification. For a simple thought experiment, assume every candidate is accepted independently with the same probability alpha. With a block of gamma candidates and one extra target token after full acceptance, expected output per round is one plus alpha plus alpha squared, continuing through alpha to the power gamma. The one accounts for a corrected token or the extra target token. This model is useful for predictions, but real acceptance varies by position, task and prefix.

The expected token count is the sum of survival probabilities. Under the constant independent-acceptance assumption, E = sum from i=0 to gamma of alpha^i. For alpha not equal to one, this is (1−alpha^(gamma+1))/(1−alpha); at alpha=1 it is gamma+1. This is a model of rounds before end-of-sequence truncation. Independence is a teaching assumption, not a theorem about model outputs.

Worked example. For alpha 0.8 and three candidates, expected output is one plus 0.8 plus 0.64 plus 0.512, or 2.952 tokens. At zero acceptance it is one token. At perfect acceptance it is four. Workbench lets you change alpha and block length, but it does not estimate alpha from a real model.

E[tokens/round] = sum(i=0..gamma) alpha^i

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. If acceptance rises, must the best draft block become arbitrarily long?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. Longer blocks also cost more to draft and verify, and distant proposals may be less likely to survive. Optimize useful output per total time, not accepted-token count alone.

Section 06 / 07

Count the draft and verification costs

To estimate speed, divide expected useful tokens by the cost of one speculative round, measured in units of an ordinary target decode step. The round includes draft work and verification, plus any overhead you have chosen to model. In our experiment each draft token costs a chosen fraction c and verification costs v. The ratio is expected tokens divided by v plus gamma times c. A value below one predicts a slowdown under these assumptions. Real verification cost depends on block size, batching, device utilization and implementation.

The toy speed ratio is S = E/(v+gamma c). It assumes constant per-draft-token cost and a user-specified verification cost, excluding communication and cache management. Compute-bound serving can behave differently from low-batch memory-bound decoding. Compare latency and throughput separately, and measure an actual acceptance-prefix distribution rather than substituting one global average without checking its adequacy.

Worked example. With alpha 0.8, gamma three, c 0.1 and v one, divide 2.952 by 1.3 to obtain about 2.27. This is a modeled ratio, not a benchmark result. If draft cost rises to one, the denominator is four and the ratio falls to 0.738: slower than the baseline despite the same acceptance.

S_model = E[tokens/round] / (v + gamma × c)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. What would invalidate a claim of a universal 2.27-fold speedup from this example?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

The inputs are hypothetical and costs vary with workload and hardware. The example establishes arithmetic under assumptions, not a universal measured performance result.

Section 07 / 07

Connect exact sampling to modern systems

Modern systems may use separate draft models, extra prediction heads, shared model components or branching proposals. Each needs a clear verification procedure. In the DeepSeek case study, DSpark combines drafting with confidence-guided scheduling. That model-specific design should not be confused with our simple constant-acceptance experiment. Evaluate the complete system using matched target sampling settings, tasks and hardware. Check both the distribution-preservation logic and the measured cost. A faster assistant is valuable only if its promised behavior survives the optimization.

For an implementation audit, check token compatibility, acceptance and residual calculations, end-of-sequence handling, numerical precision, cache rollback and bonus-token logic. For performance, record accepted-prefix lengths, draft and target timings, memory overhead and load-dependent throughput. Statistical tests can detect discrepancies but do not replace an algorithmic proof. Identical random seeds alone are not a distribution-equivalence test.

Worked example. First reproduce the two-token correction exactly in Workbench. Then change alpha and draft cost in the performance model, saving one predicted speedup and one slowdown. Explain why the correction example is a probability identity while the speed estimate depends on assumptions. Finally, state which measurements would be needed before choosing a draft strategy for a classroom assistant.

Correct distribution + measured cost + task quality = a defensible evaluation

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does preserving the target distribution prove that the target always gives correct factual answers?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. It preserves the target’s behavior under the algorithm’s assumptions, including its possible errors. Factual quality and decoding correctness are different questions.

Final checkpoint. For p=(0.6,0.4), q=(0.8,0.2), what is the rejection correction distribution? Option 1: (0.6,0.4). Option 2: (0.8,0.2). Option 3: (0,1).

Pause and choose an answer before continuing.

Reveal worked solution

Option 3 is correct. Normalize the positive part of p minus q. Accepted mass (0.6,0.2) plus rejection mass (0,0.2) recovers p.

Continue the learning path

Sources and scope

Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.