Blockwise and Semi-Autoregressive Generation › Implementation

Michael BrenndoerferNovember 17, 202614 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 137Blockwise and Semi-Autoregressive Generation › Implementation
Reading section 8 of 11 · Implementation · 14 minSection 8 of 11 · 14 min

Section 8 of 11 · 14 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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 p(yt∣y<t)=p(yt∣yt−1)p(y_t \mid y_{<t}) = p(y_t \mid y_{t-1}). It is enough to show how a draft mismatch changes the conditioning prefix.

PythonIn [7]
CollapseExpand
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]
CollapseExpand
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.00
ConsoleOut [9]
CollapseExpand
  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]
CollapseExpand
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 out
ConsoleOut [11]
CollapseExpand
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]
CollapseExpand
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 proposals

The 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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:], history
ConsoleOut [16]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Grouped bar chart comparing scored positions and committed tokens per decoding step.
The first round scores three candidate positions and emits one agreeing token plus the correction. In the second round, EOS agrees and ends the sequence after one candidate score.

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]
CollapseExpand
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_mass
ConsoleOut [21]
CollapseExpand
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 x1x_1 where the target assigns 0.5. Its excess 0.1 on x2x_2 is the probability of rejection, and the residual assigns that missing mass to x1x_1. 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]
CollapseExpand
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]
CollapseExpand
empirical frequencies after rejection sampling:
[0.5012 0.3008 0.198 ]
target distribution:
[0.5 0.3 0.2]
VisualizationOut [24]
CollapseExpand
Grouped bar chart comparing target probabilities with empirical sampler frequencies.
Target probabilities and empirical output frequencies from 200,000 trials of the one-position sampler. The frequencies vary around the target probabilities.

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]
CollapseExpand
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]
CollapseExpand
                          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.90

Look 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]
CollapseExpand
Line chart of simulated speculative decoding speedup against acceptance rate.
Simulated wall-clock speedup of speculative decoding versus draft acceptance rate for several draft lengths, assuming a target pass costs 10 cost units and a draft token costs 1. Values are simulated from the acceptance model in the text, not measured on hardware. The dashed line marks break-even.

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]
CollapseExpand
Bars for five simulated target pass counts, each below one pass per token.
Simulated target passes per output token for five configurations. The dashed line marks one target pass per token.
VisualizationOut [30]
CollapseExpand
Bars for five simulated speedups, with the last two below break-even.
Simulated wall-clock speedup for the same configurations. The last two scenarios fall below the break-even line despite scoring fewer target passes per output token.

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 VV for the measured verification time for the submitted block and HH for prefix updates and other serial overhead. Under the fixed-cost approximation, the speculative round costs γD+V+H\gamma D+V+H. 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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy