Blockwise and Semi-Autoregressive Generation › Implementation
Language AI HandbookAll chapters 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.
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!