Blockwise and Semi-Autoregressive Generation
Explore semi-autoregressive block generation, blockwise parallel decoding, and exact speculative sampling with acceptance and residual repair rules.
Language AI HandbookAll chapters Blockwise and Semi-Autoregressive Generation
A target decoder would greedily emit a, c, <eos>. The draft proposes a, b, <eos>, and the target scores all three positions in one pass. It accepts a and uses its second score to replace b with c. The third score was computed after b. The decoder needs a score after the corrected prefix to choose its next token.
There are two design choices to keep distinct in this chapter:
- Train a model to generate blocks. In the semi-autoregressive translation system we will study, the model predicts positions inside a group independently given the earlier groups and source text. Other block-autoregressive models allow dependence within a group through an iterative sampler.
- Verify blocks against an existing target model. A fast proposal process supplies potential future tokens, and the target checks their prefixes together. A greedy verifier can reproduce the target's baseline sequence. An exact stochastic verifier can preserve the target's sampling distribution.
The sequence probability factorizes over ordered blocks. What happens inside a block is a separate modeling choice. A one-shot block predictor can use independent token distributions, and a block diffusion model can refine the same block across multiple rounds.
Stern, Shazeer, and Uszkoreit (2018) predict several positions in parallel. They use the original model to check the longest contiguous prefix that matches its greedy choices. A related greedy draft-and-verify algorithm can also emit a target correction at the first disagreement.
Leviathan, Kalman, and Matias (2023) draw a block of proposals from a draft distribution and score it with the target. An acceptance rule and a residual distribution recover the intended target distribution at each output position.
A trained block model specifies how its tokens depend on each other. In draft verification, an existing target model uses each hypothetical prefix to evaluate the corresponding proposal.
Part XXVIII, Inference Optimization, introduces Speculative Decoding for deployment. Speculative Decoding Math develops the acceptance and speedup formulas further.
Why One Token at a Time Is Expensive
Recall from Decoder Architecture that the attention layer for a newly processed position can use keys and values cached for its prefix. With dense attention and a fixed model width , scoring that position against keys takes attention work per layer. The feed-forward cost for a fixed width is independent of . The cache avoids computing prefix keys and values again. The sampled token still needs to be chosen before it can serve as input for the next decision.
A model with parameters stored in bfloat16 uses about bytes for weights alone. A 70-billion-parameter example takes about 140 GB of weight storage in decimal units before sharding or compression. This measures storage. Traffic on an actual device depends on how weights and cached activations are laid out, what fits in faster memory, and what the runtime reuses. In the bandwidth-limited setting discussed by Leviathan et al., processing multiple positions together can make greater use of the hardware while reusing the weight read.
A decoder's critical path counts steps whose inputs depend on earlier outputs. How that translates into elapsed time depends on the cost of each step. Time to first token includes prompt processing and the work before the first output. Inter-token latency measures the spacing between emitted tokens, so several tokens arriving together followed by a pause can have the same mean spacing as a smooth stream. Throughput measures aggregate output over time, usually across requests. Operation count and accelerator time are separate ways to track cost. Batching can improve aggregate throughput through reuse without shortening the logical dependency chain of an individual sequence.
What "Semi-Autoregressive" Actually Relaxes
Here is the standard autoregressive factorization. For an output sequence conditioned on some input ,
where . Each next-token conditional can use all preceding output tokens. An ordinary left-to-right sampler forms the prefix before sampling at the next position.
Now partition a fixed-length output into contiguous groups of at most tokens, with only the last group allowed to be shorter. There are groups. A semi-autoregressive model with independent intragroup predictions defines its joint probability by
where denotes all tokens in groups . Read this carefully, because the two products mean very different things:
- The outer product generates groups in order. Each group can condition on all the earlier groups.
- The inner product over conditions each token on the group prefix and the common input . Tokens inside a group are conditionally independent given what came before.
The independent predictions let the model generate a group in parallel. This choice limits the conditional dependence the model can express within one group.
Group size controls the number of sequential groups and the information available to each prediction.
| Behavior | Dependencies within each group | |
|---|---|---|
| Token-autoregressive | No within-group pairs | |
| Group-autoregressive | Independent given the earlier groups and input | |
| One-shot prediction | Independent given the input |
Table: Dependency pattern at three group sizes.
Changing the width moves group boundaries and changes which preceding tokens are visible to each prediction. In the fourth position, groups of width two expose the first two tokens, and groups of width three expose the first three. Increasing group width reduces or preserves the number of group decisions at a fixed output length. These settings control which tokens the model can condition on. An empirical quality or latency comparison still depends on how each model is trained and decoded.
Training a Semi-Autoregressive Model
Wang, Zhang, and Chen start from a Transformer encoder-decoder. They shift decoder inputs by a group and relax causal masking across the known inputs in the shifted group. The information carried by the decoder inputs matters alongside their positions. A mask over unshifted gold target tokens could leak the answers through the diagonal.
The following diagram uses explicit prediction queries to show which information each position can use. Query reads token content supplied for earlier groups and a target-free key at its own position. The target-free key can encode the position and other information available during inference. For , the binary mask has entries
A marks visibility from query to key . With groups of width three, the query at position four can read token content from positions one through three and its own target-free key. The token at position four can supply content to queries in later groups. The two roles at position four use distinct representations. During teacher forcing, token content comes from the reference. During generation, it comes from completed groups. The diagram leaves source attention and the start symbol implicit.
The mask is easier to read as a picture than as a piece of pseudocode. In the heatmap below, rows are query positions and columns are key positions, so a filled cell means the query is allowed to attend to that key. The diagonal shows each query's access to its own target-free representation.
VisualizationOut [3]Expand

Under the independent within-group product, the negative log-likelihood sums the per-position cross-entropies. A single teacher-forced pass can compute all of them using the group-shifted inputs of Wang et al. or an explicit query construction with separately supplied earlier-group token content. Using unshifted gold embeddings on the diagonal would give queries their own labels. A token-autoregressive Transformer can also parallelize teacher-forced training. The group model reduces sequential decisions during generation, when each group waits for completed earlier groups.
What the Relaxation Costs
Consider a name with two plausible two-token forms. Predicting both tokens independently in one group can combine halves from different forms. If the boundary falls between the halves, the next group can use the first sampled token when choosing the second.
Wang, Zhang, and Chen (2018) studied this trade-off on English–German and Chinese–English translation. Table 3 compares the WMT 2014 English–German baseline of 27.11 BLEU at 346 ms per sentence to the model at 26.90 BLEU and 229 ms, with beam size four for both rows. The model at beam size four reached 24.83 BLEU and 116 ms. These comparisons use the paper's data, fitted models, hardware and decoding settings. They show that larger groups helped latency and hurt BLEU across those settings. The magnitude of either change is workload-specific.
A small probability table makes the restriction visible. Suppose the reference distribution gives probability to “North Court” and to “South Park” at one prefix. The words stand for two token positions in this example. The first position's distribution gives probability each to “North” and “South”. The second position gives probability each to “Court” and “Park”. Multiplying those marginals gives to each of four names. Two of them had probability zero under the reference. The combined mass on those two cross-pairs is .
| Pair | Reference probability | Independent prediction probability |
|---|---|---|
| North Court | ||
| North Park | ||
| South Court | ||
| South Park |
Table: Two within-group token decisions at a fixed prefix.
The per-position marginals in the table are correct. The error arises when the model samples the two positions independently. If the group boundary comes between these positions, the second prediction can instead put all its mass on “Court” after “North” and on “Park” after “South”. That particular dependency then fits the factorization, at the cost of waiting for the first group. In a translation example, a clearer source sentence might determine the whole name and remove this uncertainty even for independent predictions. The dependence that matters here is what remains after conditioning on the source and preceding groups.
Auxiliary heads that predict several future positions can supply a draft to another decoder. Their training objective alone does not determine which distribution the final decoder follows. For example, when an exact greedy verifier still checks their proposals, it can use their predictions to save steps while preserving the baseline's sequence.
Blockwise Parallel Decoding
Stern, Shazeer, and Uszkoreit (2018) train proposal predictors for offsets two through . The first proposal is the original autoregressive model's greedy next token. The other predictors use the same committed prefix. The verifier then runs the original model on the proposed continuations, allowing position to condition on earlier proposals. The first proposal already matches by construction. The algorithm appends the longest agreeing contiguous prefix.
The worked example uses a related greedy draft-and-verify procedure. It allows an independent draft, then uses the target to ensure progress even when no draft token agrees. Begin from a committed prefix . The target's greedy choice at the next position is the token with largest conditional probability. Choose a fixed tie-breaking rule and use it in the baseline and verifier.
- Draft. Propose up to tentative tokens . In the example a small autoregressive table proposes them sequentially. A parallel proposal head is also possible.
- Verify. Supply all the proposed tokens together as a known extension. The target evaluates for proposal position . A causal attention mask prevents position from seeing later proposals. In a Transformer implementation the conditionals can be evaluated in one batched pass, with the first-position distribution possibly available from the cached prefix.
- Accept the longest agreeing prefix. Let be the number of consecutive matches from the start. Append those tokens.
- Continue with the target. At the first disagreement, use the target's greedy choice at position . If the whole proposal agrees, the algorithm can use the extra target score after the final proposal when the pass also produced that score. EOS and output-budget limits take precedence.
The greedy guarantee follows from the prefixes. Before the first proposal, the target verifier and the baseline are conditioned on the same committed text. If the verifier accepts that proposal, it appends the same token as the baseline. Inductively, the prefixes continue to match throughout the agreeing part. At the first disagreement, the verifier's target choice is the baseline's next token under that still-matching prefix. After appending it, the next iteration starts from the new verified prefix. With no EOS or length stop before the iteration, the verification and correction step commits at least one token.
Scores After the First Rejected Proposal
The first disagreement occurs at proposal position . Its target score uses a prefix consisting entirely of committed tokens and agreeing proposals, so the score can supply the correction. At positions , the verifier's scored prefixes already contain the rejected proposal. Scoring the same continuation after replacing that token requires the corrected prefix. A tree-based verifier may already have scored this other prefix if the tree contained it.
Verifying with a KV Cache
A target runtime can score an extension while filling provisional entries in the KV cache. It then retains the entries for the accepted prefix and invalidates later entries. Depending on the cache layout this might mean changing its valid length or releasing pages. The correction or extra token needs an entry of its own before its keys and values become part of a subsequent prefix. The draft model also needs its state to match the new sequence before it drafts again. These cache operations affect latency even when the greedy output is identical.
One practical alignment check is to write the candidate predictions beside the inputs used to produce them. With prefix of length and a draft of length three, the logits from the prefix's last position supply the prediction at . The logits from the first draft position supply the prediction at . The logits from the second draft position supply the prediction at . The logits from the last draft position can supply an extra token at . This follows the usual next-token convention where the output at an input position predicts the following position. It is easy to be off by one here if the scoring API returns only logits for the newly submitted positions.
If the second proposal fails verification, its cache entry and the third proposal's entry must be invalidated. The first proposal's entry can remain because earlier inputs at that location agreed and the target is causal. Replacing the second proposal with the target's correction changes the required state from that position onward. Leaving the rejected entries physically allocated is fine if the runtime keeps them outside the valid prefix.
Relaxed Verification
Stern and colleagues also test verification that accepts a proposal when it ranks among the target's top choices. This can increase the length of accepted blocks. It drops the greedy equality guarantee when it permits a choice below the target's top rank. Section 5 and the reported experiments in the paper explain how this relaxation changes the quality and latency trade-off.
End of Sequence and Output Budget
A committed EOS ends generation. The draft stops proposing after a tentative EOS. The verifier can reject that proposal and continue from its replacement when the replacement is nonterminal and the budget allows. The decoder counts committed EOS against the output budget and excludes the supplied BOS. An exhausted budget suppresses any extra token.
Speculative Decoding: Exact Stochastic Verification
The greedy verifier has one reference output for a given prompt and tie-breaking rule. For a sampling decoder, there is a reference distribution over outputs. Leviathan, Kalman, and Matias (2023) give an algorithm that preserves that distribution while still using multiple proposals per target pass.
Exactness means matching the output probability assigned by the baseline sampling policy to every sequence. Two implementations can consume random numbers in different orders. Their outputs with the same seed may differ even when the distributions agree.
The algorithm has four steps.
- Draft. Sample up to tokens autoregressively from the draft distribution within the remaining budget, stopping the draft on a proposed EOS. A latency gain depends on the draft's cost relative to target verification and on how many of its proposals pass.
- Score. Evaluate on the hypothetical prefixes using a batched target pass. For a block of proposals, the last committed position supplies and the logits at draft input supply . The last draft input can supply the distribution for an extra token if the entire block survives and generation can continue.
- Verify with rejection sampling. At each reached proposal , draw an independent . Accept the proposed token if . Both probabilities refer to the same reached prefix.
- Residual repair. If the first rejection happens at position , resample the output token from the residual distribution
Emit the replacement and discard the remaining draft. If every proposal is accepted and generation can continue, sample one extra token from . Apply the baseline's EOS and output-budget rules to the committed tokens.
The acceptance probability uses the actual probability of drawing the proposal from . For a token the draft overweights, the ratio accepts only enough proposals to match the smaller target mass. For a token the draft underweights, the residual supplies the missing probability. A draft with always passes at that position.
Why the Rule Is Exact
Consider a single position with target distribution and draft distribution . The sampler produces by accepting a proposal of or by drawing from the residual after a rejection. The first product below is zero whenever .
The first term simplifies to , because when , and when the term is .
For a concrete example, take target probabilities and proposal probabilities . The first and third proposals always pass. The second passes with probability . It carries proposal mass , so three quarters of that mass, , is already the required target mass. The remaining goes to the rejection branch. A replacement draw assigns it to the first token, the only token whose target mass exceeds its proposal mass.
The rejection probability in general is
Since both and sum to 1, , and that common value is the normalizer of the residual. When , the rejection branch has probability zero and every drawn proposal is accepted. For the two paths give
Rejection mass is also half the sum of the absolute differences . The positive differences and the negative differences have equal total magnitude because both distributions sum to one. This half-sum is total variation distance on the vocabulary. It gives a precise sense in which a better draft can pass more often at a fixed prefix. It also explains why keeping one phrase's top token unchanged can leave a sizable rejection probability when the rest of the distribution shifts.
This identity holds at each reached prefix . Reaching the next check depends on earlier draft tokens and their independent acceptance draws. Conditional on their prefix, the next token still comes from the actual proposal . After rejection, sample the replacement and restore both models to the committed prefix. Applying the resulting target conditional at every position gives the baseline sequence distribution. To compare to an exact top- baseline, must include the baseline's truncation and renormalization at the relevant prefix. The draft can use a different sampling rule. The verifier must use the distribution that actually generated the proposal, expressed over the same token events as .
Expected Tokens per Iteration
Take one speculative iteration that proposes tokens and can emit the extra target token after accepting all of them. Ignore EOS and length stops for this cost calculation. To emit at least tokens, the first proposals have to pass. With independent acceptance events of common probability , the probability for that event is . The expected committed count is the sum of these probabilities:
The first term counts the token guaranteed whenever an iteration can emit. In real decoding, acceptance probabilities can depend on the text and position. You can still sum the probabilities of reaching each accepted prefix length. Raising a single observed average acceptance rate to powers generally fails to estimate those probabilities exactly. For example, take two kinds of request that occur equally often. The first kind would pass both checks and the second kind would fail both checks if scored separately under their respective hypothetical draft prefixes. The chance of getting past both proposals is one half. Multiplying two unconditional per-position probabilities of one half would give one quarter under an independence assumption. The second check is reached only on the first kind of request, so its conditional acceptance rate is one. Pooling the first and reached second checks gives two successes for three checks per pair of requests. The exact expectation uses the probability of each whole accepted prefix, which is one half for lengths one and two in this example.
Each curve corresponds to a draft length. The horizontal axis is the assumed per-proposal acceptance probability. The vertical axis is the expected number of committed tokens from one target pass. At low acceptance, extra draft positions add small higher-power terms.
VisualizationOut [5]Expand

Let be the baseline time for one target token and the time for one draft token. The simulation uses the same cost for full-block verification and for the baseline single-token step, with the draft and verify stages run serially. With fixed costs and long outputs, its predicted speedup is
The numerator is the time the baseline would spend on the expected number of tokens committed by one speculative iteration. The denominator is the cost of that iteration in this simplified model. Real verification time can differ from , and cache rollback, scheduling and synchronization can add costs. Batch-level throughput and the latency seen by each request therefore need separate measurement.
Block Diffusion
Arriola et al. (2025) also generate an ordered sequence of blocks. Their model uses a diffusion conditional within each block. As in the preceding chapter on diffusion language models, a noisy or masked state is updated across a sequence of reverse steps. Each step receives the current state of the block, which can contain tokens revealed at earlier steps.
For blocks , let denote all blocks already completed. The block-level chain rule is
This factorization leaves the distribution inside unspecified. The block-diffusion model samples it through denoising conditioned on . Its attention mask allows positions to attend to earlier blocks and to the current noisy block. A masked step can score several positions together. Subsequent steps can use a different state, which can couple decisions at nearby positions even when individual transition predictions are computed in parallel.
The number of reverse steps and the block length are separate controls. With a one-token block, the outer factorization has token-level granularity. With a multi-token block, even a sampler with one refinement per position in its budget may make its decisions in a different order or update several positions per refinement. The denoising schedule and transition rule determine when decisions are made and whether they depend on positions to their right.
The sampler in Algorithm 2 of the paper freezes completed blocks, reuses their KV entries, and computes a cache for the newly sampled clean block before the next iteration. Those cache operations and all denoising passes enter a latency comparison. A single pass can prepare candidates for several positions, and the refinement rounds contribute to the serial cost. The next chapter, Comparing Architecture Families Fairly, covers the measurements needed for such comparisons.
Worked Example With an Early Disagreement
We'll build a minimal deterministic trace of blockwise decoding before touching the code, so the logic is clear.
Suppose we have a target model and a draft model , both bigram distributions over the tiny vocabulary [<bos>, a, b, c, <eos>]. The draft approximates the target and prefers a different continuation after the token a. Greedy decoding under from <bos> gives a, c, <eos>. Greedy decoding under gives a, b, <eos>.
Start with the verified prefix <bos>, block size , and let the draft propose next tokens one at a time:
- Draft from
<bos>:a. - Draft from
a:b(here the draft disagrees with the target, which would have saidc). - Draft from
b:<eos>.
So the draft proposes [a, b, <eos>]. Now run the target in one teacher-forced pass over the prefix plus this draft:
| Position | Conditioning context | Target argmax |
|---|---|---|
| 1 | <bos> | a |
| 2 | <bos>, a | c |
| 3 | <bos>, a, b | <eos> |
Compare with the draft:
- Position 1:
avsa. Agree. - Position 2:
bvsc. Disagree.
Longest agreeing prefix has length . The first drafted token is accepted. The second is rejected. The third was scored, but its conditioning context included b, which is about to be rejected. It is a score for the discarded branch. It cannot be used to justify committing <eos> at position 3, because the prefix to position 3 will not contain b. If the model wanted to claim that <eos> is the right continuation, it would have to be re-run under the correct prefix <bos>, a, c. It hasn't been.
Now read the correction. The target's argmax after the accepted prefix <bos>, a is position 2's score, which is c. That prediction was computed inside the same pass, and it is guaranteed to match the greedy target sequence. Commit it. The verified prefix becomes <bos>, a, c. One step produced two tokens.
Second iteration. Prefix <bos>, a, c. Draft from c gives <eos>. Target from c gives <eos>. Full agreement, . Commit <eos>. Sequence complete. The runtime committed three new tokens including <eos> in two verification rounds. The greedy baseline makes three serial decisions. The supplied <bos> counts in neither output length nor decision count.
Two things are worth extracting from the trace.
- The score/commit gap. The first iteration checked three candidate positions and committed two tokens. Position 2's target score was useful, even though the draft token at position 2 was rejected. Position 3's score belonged to the discarded branch.
- The next iteration. The target gives EOS probability 0.40 after
band 0.70 afterc. EOS is the greedy choice in both contexts. The verifier uses the distribution afterconce it commits the correction.
We now encode the same trace in two small bigram tables. Then we use different tables to show why stochastic verification needs its probability correction, even on a single position.
Implementation
We'll proceed in four stages. First, the toy AR model as a bigram table. Second, blockwise decoding on the table. Third, exact speculative sampling with modified rejection. Fourth, a simulated cost model with a variant that fails.
A Tiny Table-Driven Autoregressive Model
A bigram table gives us a small autoregressive language model with . It is enough to show how a draft mismatch changes the conditioning prefix.
PythonIn [7]Expand
import numpy as np
VOCAB = ["<bos>", "a", "b", "c", "<eos>"]
IDX = {t: i for i, t in enumerate(VOCAB)}
# Rows index the previous token, columns index the next token.
P = np.array(
[
[0.00, 0.50, 0.20, 0.20, 0.10], # after <bos>
[0.00, 0.10, 0.20, 0.50, 0.20], # after a
[0.00, 0.20, 0.10, 0.30, 0.40], # after b
[0.00, 0.10, 0.10, 0.10, 0.70], # after c
[1.00, 0.00, 0.00, 0.00, 0.00], # after <eos>
]
)
Q = np.array(
[
[0.00, 0.60, 0.20, 0.10, 0.10], # after <bos>
[0.00, 0.10, 0.50, 0.20, 0.20], # after a
[0.00, 0.10, 0.10, 0.30, 0.50], # after b
[0.00, 0.10, 0.10, 0.10, 0.70], # after c
[1.00, 0.00, 0.00, 0.00, 0.00], # after <eos>
]
)
P = P / P.sum(axis=1, keepdims=True)
Q = Q / Q.sum(axis=1, keepdims=True)After a, the target prefers c and the draft prefers b. Both tables also have a placeholder row after EOS to keep their rows normalized. Generation ends when it commits EOS.
ConsoleOut [8]Expand
Target model P(next | prev)
prev | <bos> | a | b | c | <eos>
<bos> | 0.00 | 0.50 | 0.20 | 0.20 | 0.10
a | 0.00 | 0.10 | 0.20 | 0.50 | 0.20
b | 0.00 | 0.20 | 0.10 | 0.30 | 0.40
c | 0.00 | 0.10 | 0.10 | 0.10 | 0.70
<eos> | 1.00 | 0.00 | 0.00 | 0.00 | 0.00ConsoleOut [9]Expand
prev target argmax draft argmax
<bos> a a
a c b
b <eos> <eos>
c <eos> <eos>
<eos> <bos> <bos>Under the target, the first two argmax picks are a and then c. Under the draft, the picks are a and then b. That's exactly the disagreement pattern we need.
Now we define the greedy decoder and the blockwise step.
PythonIn [10]Expand
def greedy_next(table, prev):
"""Greedy next-token index under a single bigram table."""
return int(table[IDX[prev]].argmax())
def greedy_ar(table, start="<bos>", max_len=8):
"""Pure autoregressive greedy decoding under one table."""
out, prev = [], start
for _ in range(max_len):
nxt = VOCAB[greedy_next(table, prev)]
out.append(nxt)
if nxt == "<eos>":
break
prev = nxt
return outConsoleOut [11]Expand
target greedy sequence: ['a', 'c', '<eos>'] draft greedy sequence: ['a', 'b', '<eos>']
The two decoders agree on the first token and disagree on the second, which is what the verifier needs to be tested on.
Blockwise Parallel Decoding
First draft within the remaining output budget. We stop drafting at EOS. This table uses the most recent token as its whole conditional context. A Transformer would need all the earlier tokens or their cached keys and values.
PythonIn [12]Expand
def draft_block(draft, previous, length):
proposals = []
for _ in range(length):
next_token = VOCAB[greedy_next(draft, previous)]
proposals.append(next_token)
if next_token == "<eos>":
break
previous = next_token
return proposalsThe target can look up the candidate positions together because their presumed predecessors are already known. The row for the first candidate follows the last committed token. Later rows follow the earlier proposals. NumPy indexing represents one batch of conditional queries in this example.
PythonIn [13]Expand
def score_block(target, previous, proposals):
if not proposals:
return []
predecessor_ids = [IDX[token] for token in [previous] + proposals[:-1]]
return [VOCAB[index] for index in target[predecessor_ids].argmax(axis=1)]At the first disagreement, the target choice supplies the correction because all earlier proposals agreed. If the whole draft agrees, an extra token is available only when there is budget left and the accepted draft ends in a nonterminal token. The table looks up a fresh row for that extra choice. A Transformer can obtain its logits from the final draft input in the verification pass. The trace counts candidate-position scores and records corrections and extra tokens separately.
PythonIn [14]Expand
def blockwise_step(target, draft, previous, gamma, budget):
if gamma < 1 or budget < 1:
raise ValueError("Draft length and step budget must be positive")
if previous == "<eos>":
raise ValueError("Verification requires a nonterminal prefix")
proposals = draft_block(draft, previous, min(gamma, budget))
scores = score_block(target, previous, proposals)
accepted = next(
(
i
for i, pair in enumerate(zip(proposals, scores))
if pair[0] != pair[1]
),
len(proposals),
)
committed = proposals[:accepted]
correction = bonus = None
if accepted < len(proposals):
correction = scores[accepted]
committed.append(correction)
elif len(committed) < budget and committed[-1] != "<eos>":
bonus = VOCAB[greedy_next(target, committed[-1])]
committed.append(bonus)
return committed, {
"drafts": proposals,
"scores": scores,
"accepted": accepted,
"correction": correction,
"bonus": bonus,
"n_scored": len(scores),
"n_committed": len(committed),
"committed": committed,
}The driver starts with BOS and calls the step only with a positive remaining budget and a nonterminal prefix. A zero output budget returns empty tokens and history. Each completed step appends the new tokens and its trace.
PythonIn [15]Expand
def blockwise_generate(target, draft, gamma=3, max_new=12):
if gamma < 1 or max_new < 0:
raise ValueError(
"Draft length must be positive and output budget nonnegative"
)
prefix, history = ["<bos>"], []
while len(prefix) - 1 < max_new and prefix[-1] != "<eos>":
budget = max_new - (len(prefix) - 1)
committed, step = blockwise_step(
target, draft, prefix[-1], gamma, budget
)
prefix.extend(committed)
history.append(step)
return prefix[1:], historyConsoleOut [16]Expand
step 1 drafted : ['a', 'b', '<eos>'] target choices: ['a', 'c', '<eos>'] accepted : 1 correction : c extra token : None committed : ['a', 'c'] step 2 drafted : ['<eos>'] target choices: ['<eos>'] accepted : 1 correction : None extra token : None committed : ['<eos>'] generated tokens: ['a', 'c', '<eos>']
The first round scores three candidate positions and commits the agreeing a and the correction c. The second round commits EOS and stops. The checks below cover empty and one-token budgets, and exercise the extra-token path with an agreeing one-token draft and room to continue.
PythonIn [17]Expand
assert emitted == greedy_ar(P, max_len=12)
assert blockwise_generate(P, Q, max_new=0) == ([], [])
assert blockwise_generate(P, Q, max_new=1)[0] == ["a"]
assert log[0]["correction"] == "c" and log[0]["bonus"] is None
assert log[-1]["bonus"] is None
extra_tokens, extra_step = blockwise_step(P, P, "<bos>", gamma=1, budget=2)
assert extra_tokens == ["a", "c"] and extra_step["bonus"] == "c"The bars count scored candidate positions and committed tokens in the original two-round trace. A separate extra-token lookup, if used, is outside the candidate-score count. The cost of a Transformer pass depends on the verification workload and hardware.
VisualizationOut [19]Expand

Exact Speculative Sampling
The next example computes the output probabilities for a single categorical position. The calculation uses a three-token alphabet so we can inspect all the probability mass.
PythonIn [20]Expand
target_probs = np.array([0.5, 0.3, 0.2])
draft_probs = np.array([0.4, 0.4, 0.2])
tiny_vocab = ["x1", "x2", "x3"]
accept_at = np.zeros_like(target_probs)
np.divide(target_probs, draft_probs, out=accept_at, where=draft_probs > 0)
accept_at = np.minimum(1.0, accept_at)
accepted_mass = np.minimum(draft_probs, target_probs)
p_accept = float(accepted_mass.sum())
missing_mass = np.maximum(0.0, target_probs - draft_probs)
p_reject = float(missing_mass.sum())
residual = missing_mass / p_reject if p_reject > 0 else None
output_probs = accepted_mass + missing_massConsoleOut [21]Expand
token target p draft q accept prob x1 0.500 0.400 1.000 x2 0.300 0.400 0.750 x3 0.200 0.200 1.000 P(accept a draft token) = 0.900 P(reject) = 0.100 residual distribution = [1. 0. 0.] repaired output probs = [0.5 0.3 0.2] target probabilities = [0.5 0.3 0.2]
The algebra gives the target probabilities, and the NumPy results agree to floating-point precision. The acceptance array uses zero for symbols outside the draft's support, which the draft never draws. Here the draft assigns 0.4 to where the target assigns 0.5. Its excess 0.1 on is the probability of rejection, and the residual assigns that missing mass to . With identical distributions, every proposal passes and the residual is unused.
To check the implementation empirically, repeat the one-position experiment over independent draws. Sample replacement tokens only for rejected proposals.
PythonIn [22]Expand
rng = np.random.default_rng(0)
N = 200_000
drawn = rng.choice(len(tiny_vocab), size=N, p=draft_probs)
u = rng.random(N)
accepted = u < accept_at[drawn]
outputs = drawn.copy()
rejected = ~accepted
n_rejected = np.count_nonzero(rejected)
if n_rejected:
outputs[rejected] = rng.choice(len(tiny_vocab), size=n_rejected, p=residual)
empirical = np.bincount(outputs, minlength=len(tiny_vocab)) / N
x = np.arange(len(tiny_vocab))ConsoleOut [23]Expand
empirical frequencies after rejection sampling: [0.5012 0.3008 0.198 ] target distribution: [0.5 0.3 0.2]
VisualizationOut [24]Expand

The sampled frequencies are near the target probabilities. They are a finite-sample check on the implementation. The probability derivation establishes exactness for the specified one-position sampler.
Simulated Cost Accounting
The cost model combines the acceptance rate with the relative cost of a draft step and a target pass. The simulation assigns 10 cost units to a target pass and varies the cost of each draft token.
PythonIn [25]Expand
def expected_tokens(alpha, gamma):
"""Expected committed tokens per target pass, under the geometric model."""
if not 0.0 <= alpha <= 1.0 or gamma < 0:
raise ValueError(
"Acceptance must be in [0, 1] and draft length nonnegative"
)
if alpha == 1.0:
return float(gamma + 1)
return (1.0 - alpha ** (gamma + 1)) / (1.0 - alpha)
def wall_clock_speedup(alpha, gamma, target_cost=10.0, draft_cost=1.0):
"""Simulated wall-clock speedup using the cost model in the text."""
n = expected_tokens(alpha, gamma)
return (n * target_cost) / (gamma * draft_cost + target_cost)
def target_passes_per_token(alpha, gamma):
return 1.0 / expected_tokens(alpha, gamma)ConsoleOut [26]Expand
scenario alpha gamma tok/pass passes/tok speedup
many drafts, slow draft 0.90 8 6.13 0.163 1.46
cheap draft, good agreement 0.85 4 3.71 0.270 2.65
cheap draft, poor agreement 0.40 4 1.65 0.606 1.18
cheap draft, very poor agreement 0.20 4 1.25 0.800 0.89
costly draft, many drafts 0.90 6 5.22 0.192 0.90Look at the last two scenarios. Both show target-passes-per-token well below 1 (0.800 and 0.192), meaning the speculator really does spend far fewer target calls than autoregressive decoding. Both show wall-clock speedups below 1 (0.89 and 0.90). The number of target passes went down while total wall-clock went up. In the cheap-draft case at 20% agreement, a round accepts about 0.25 draft tokens on average. The draft work costs more time than the savings in target calls. The costly-draft case is more interesting: at 90% acceptance with a big draft, the draft is so expensive relative to the target that even good acceptance doesn't pay back.
The simulated speedup curves below make this break-even structure legible. Each curve corresponds to a draft length and varies the acceptance rate. The horizontal line at 1 marks the boundary between useful and counterproductive speculation.
VisualizationOut [28]Expand

For each draft length the predicted speedup rises with acceptance. Near the left edge, long drafts spend substantial work on proposals that will rarely be reached. Near the right edge, several additional tokens can pass and spread verification cost over more outputs. The curves cross at several acceptance rates. The best draft length among those shown depends on the acceptance regime.
The final two charts use the same five scenarios. The first shows target passes per token and the second shows elapsed speedup in the toy model. Below one pass per token is favorable on the first chart. Above one is favorable on the speedup chart.
VisualizationOut [29]Expand

VisualizationOut [30]Expand

The final two configurations illustrate two failure modes. The first wastes enough draft work through rejection to miss break-even even with a cheap draft model. The second has high acceptance and misses break-even because each draft step is expensive. Both use fewer target passes than the baseline in this accounting. At acceptance 0.20 with a four-token draft, the expected output per round is about 1.25 tokens. The baseline spends about 12.50 cost units to emit that many tokens and the speculative iteration costs 14. The predicted ratio is about 0.89. In the expensive-draft example, a six-token draft at acceptance 0.90 gives about 5.22 tokens per round. The baseline cost for those tokens is about 52.17, against 58 for the speculative round. More than five emitted tokens per target pass can still cost more when the proposal step is expensive.
For profiling, write for the measured verification time for the submitted block and for prefix updates and other serial overhead. Under the fixed-cost approximation, the speculative round costs . Compare it with the baseline cost of producing the expected number of committed tokens. Record draft, verification and rollback times along with committed output per round. If these costs vary with context or acceptance, report the regimes separately. For an aggregate throughput comparison, divide total output tokens by elapsed time for each system on the same workload. A mean of per-regime speedup ratios can give a different result.
Limitations and Impact
An independent within-group model can express dependencies from earlier groups and from the input. If it needs a direct coupling between two uncertain decisions inside the same group, it has no sampled within-group token to condition on. Group size and block boundaries then influence the kinds of errors you see. A block-diffusion sampler can introduce local dependence by revisiting its own partially filled state. Each refinement adds a serial round before the next block can start, and any cache preparation adds work.
Greedy and stochastic verification keep the baseline model and change the execution schedule. Greedy agreement depends on using the same score and tie-breaking rule. Stochastic exactness depends on computing probabilities for the actual target and proposal policies at the relevant prefix, and using the specified residual after rejection. A different policy, an early stop triggered by a tentative proposal, or a rounding-sensitive tie can invalidate comparisons. On a particular backend, test whether the verifier sees the same target conditional as the baseline under the same prefix. Accepted EOS and remaining output budget belong in that test.
In practice, speculative work can consume additional memory for the proposal model, provisional cache entries, or both. This can change how many requests a device can serve together. An implementation that speeds up an isolated request might lose part of the advantage at higher concurrency. The opposite can happen if verification creates better accelerator utilization without displacing too many requests. Keep model weights, precision, prompt distribution, output limit and stopping policy fixed when isolating the change. Report the run's batch size, hardware and measured stage costs.
For streaming, inspect the actual times between emitted spans. A backend that drafts before its first verification may increase time to first token. When a pass commits a run of tokens, consecutive outputs may arrive in a burst. A lower mean time per token can still hide occasional long waits while a proposal is verified or rejected. Measure the first-token latency and later spacing separately, and state how the client receives tokens. Tail latency can also reflect contention and scheduling delays rather than the acceptance rule alone.
Smaller active blocks can make the sequencing of inference choices clearer, which is useful for drawing a fair comparison. For a trained group model, compare output quality under the new factorization. For an exact speculative sampler, first verify policy equivalence and then compare timing. For block diffusion, report the block width and the refinement schedule together. The same number of calls can represent different work in all three cases.
Summary
- Semi-autoregressive translation. The model generates groups in order. In the one-shot product, tokens within each group are conditionally independent given the input and earlier groups.
- Greedy block verification. The target scores the hypothetical prefix for each candidate. The longest agreeing prefix can be committed. The first mismatch can use the target's own score as a correction. Scores after that point refer to the discarded prefix.
- Stochastic speculative decoding. Acceptance retains overlapping probability mass from the proposal. Drawing from the residual after rejection restores the target's missing mass and preserves the intended sampling distribution.
- Block diffusion. Blocks are generated in order. Refinement within a block can condition on the current state of other positions in that block. The step schedule and block length are separate.
- Serving cost. Target passes, work and elapsed time per emitted token measure different quantities. Track the draft, verification, cache, and scheduling costs that intervene before output.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about blockwise and semi-autoregressive generation.
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!