Speculative Decoding with Parallel Drafting for Long-Context Code Agents: A Practical Analysis

    This article examines how speculative decoding applies to code agents operating over long contexts, where inputs can reach tens of thousands of tokens. It covers the lossless rejection-sampling mechanism, a performance model built around acceptance length and per-round latency, and the trade-offs of parallel drafting when position-wise dependencies in code reduce acceptance rates. Includes a reference implementation of the accept/verify logic and comparative tables of drafting strategies.

    1. Why Code Agents Amplify Decoding Latency

    A typical code agent workflow involves reading multiple files from a repository, understanding the context, calling tools, generating patches, and iterating based on test output. Each interaction round can carry an input of tens of thousands to over a hundred thousand tokens, while the output typically ranges from a few hundred to a few thousand tokens. Long inputs create two kinds of pressure:

    • Prefill stage: computation grows with context length.
    • Decode stage: with every token generated, the attention computation must read a longer KV cache.

    In small-batch settings, decoding is usually memory-bandwidth bound. Each generated token requires reading the full model weights from GPU memory, while compute units remain underutilized. Speculative decoding exploits exactly this: it lets compute units do more useful work while they would otherwise be waiting on memory traffic.

    2. How Speculative Decoding Works

    The idea is to first use a smaller, faster draft model to propose candidate tokens, then have the target model verify the entire candidate sequence in a single forward pass. One full round looks like this:

    1. Draft stage: the draft model generates a candidate sequence of length k, x1 through xk, along with the probability distribution q at each position.
    2. Verify stage: the target model runs one forward pass over the confirmed prefix concatenated with the candidate sequence, producing probability distributions p at k+1 positions.
    3. Acceptance check: starting from the first position, each candidate token is checked for acceptance.
    4. Correction and extension: at the first rejected position, a replacement token is sampled from the corrected (residual) distribution, and all subsequent candidates are discarded. If all candidates are accepted, one extra token is sampled from the target model’s final position.

    Each round therefore advances at least one token and at most k+1 tokens. The payoff depends on the average number of tokens advanced per round, not on the candidate length itself.

    3. Losslessness: Why the Output Distribution Is Unchanged

    The standard approach is rejection sampling. For a candidate token x at position i, accept it with probability min(1, p(x)/q(x)). If it is rejected, sample a replacement from the normalized residual distribution max(0, p − q). It can be shown that the marginal distribution of the resulting token sequence is identical to sampling token-by-token directly from the target model.

    Under greedy decoding (temperature 0), the rule is simpler: a candidate token is accepted only if it matches the target model’s argmax at that position. The output is then identical to token-by-token decoding without speculative decoding, which makes it suitable for correctness regression tests.

    The following example shows the core acceptance logic:

    1. import random
    2. import numpy as np
    3. def sample(dist):
    4. return int(np.random.choice(len(dist), p=dist))
    5. def verify_and_accept(draft_tokens, draft_probs, target_probs):
    6. """
    7. draft_tokens: list of k candidate tokens
    8. draft_probs: shape (k, V), draft model distribution at each position
    9. target_probs: shape (k+1, V), target model distribution at each position
    10. Returns the list of tokens confirmed in this round
    11. """
    12. accepted = []
    13. for i, tok in enumerate(draft_tokens):
    14. p = target_probs[i][tok]
    15. q = draft_probs[i][tok]
    16. if random.random() < min(1.0, p / q):
    17. accepted.append(tok)
    18. else:
    19. residual = np.maximum(target_probs[i] - draft_probs[i], 0.0)
    20. residual /= residual.sum()
    21. accepted.append(sample(residual))
    22. return accepted
    23. # If all candidates are accepted, sample one extra token
    24. # from the target model's final position
    25. accepted.append(sample(target_probs[len(draft_tokens)]))
    26. return accepted

    4. A Performance Model: Acceptance Length and Per-Round Latency

    Let τ denote the average number of tokens advanced per round, including the extra token contributed by the target model. Per-round latency can be broken into three parts:

    T_round = T_draft + T_verify + T_other

    where T_draft is the drafting time, T_verify is the verification time, and T_other covers scheduling, sampling, and state maintenance overhead not listed separately. Decoding speed is approximately S ≈ τ / T_round, and the speedup over autoregressive decoding is S / S_AR, where S_AR is the tokens-per-second rate without speculative decoding.

    This formula makes two things clear. First, a high acceptance length τ is necessary but not sufficient. Second, drafting and verification must themselves be cheap enough. The illustrative numbers below show why:

    Metric Autoregressive decoding Speculative decoding (illustrative)
    Tokens advanced per round (τ) 1 3.2
    Draft time 0 3 ms
    Verify time 25 ms 28 ms
    Other overhead 0 2 ms
    Per-round latency 25 ms 33 ms
    Decoding speed 40 tok/s ~97 tok/s

    In this example, speculative decoding runs about 2.4x faster than autoregressive decoding. Note that verification time rises from 25 ms to 28 ms, because a single verification pass processes k+1 positions. Within the memory-bandwidth-bound regime this increment is usually small, but it grows quickly as batch size increases.

    One set of public measurements showed that, on an 8B-class open-source model, the verification stage accounted for roughly 72% to 76% of per-round latency, with similar proportions across different draft models. This means that shrinking the draft model alone yields limited gains. The alternatives are to raise τ or to reduce the per-unit cost of verification, for example through operator optimization, batching, or quantizing the target model.

    5. Parallel Drafting: From Token-by-Token to Block Prediction

    5.1 The Bottleneck of Autoregressive Drafting

    Traditional draft models are also autoregressive: generating k candidates requires k forward passes. The longer the draft, the more linearly drafting time grows, eventually offsetting the time saved during verification.

    5.2 The Cost of Parallel Drafting

    Parallel drafting lets the draft model predict all k positions in a single forward pass, making draft time essentially independent of k. The problem is that these k positions cannot see each other during computation. Position j cannot observe the prediction at position j−1, which amounts to assuming that the positions are conditionally independent given the context.

    This assumption has little impact on the first few tokens of natural language, but it matters more for code. Variable names and their later references, bracket matching, and indentation levels all exhibit strong dependencies. Once these dependencies are ignored, acceptance rates at later positions drop, and τ shrinks accordingly.

    5.3 Building Dependencies Across Network Depth

    One approach is to explicitly pass information between adjacent positions inside the network. Concretely, at each layer, the current intermediate representation at position i−1 is injected into position i, so that dependencies are established layer by layer while keeping the single-pass block computation intact. The benefits of such designs must be validated empirically; they cannot be inferred from architecture alone.

    The table below compares three drafting strategies:

    Dimension Autoregressive drafting Independent parallel drafting Dependency-aware parallel drafting
    Draft forward passes per round k 1 1
    Inter-position dependency modeling Full None Partial, built up layer by layer
    Acceptance rate at later positions High Markedly lower Between the two
    Draft time vs. k Grows linearly Roughly constant Roughly constant
    Implementation complexity Low Medium Higher

    6. What Makes Long-Context Code Tasks Different

    Long-context code tasks combine the challenges discussed above: verification cost grows with the KV cache length, code’s strong local dependencies make naive parallel drafting lose acceptance length at later positions, and agentic workflows issue many decode rounds per task. The practical takeaway is that speculative decoding in this setting is a systems problem, not just a modeling one. Gains depend on jointly optimizing the acceptance length τ, the drafting cost, and the verification cost—and on verifying any proposed architecture change with real measurements rather than structural intuition alone.