REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Preserve target mass with speculative accept and residual resampling

Implement one exact categorical speculative step for normalized finite nonnegative [vocab] probabilities. The proposed token must have positive draft mass. Accept it when accept_uniform < min(1,target[proposal]/draft[proposal]). On rejection, inverse-CDF sample from normalized clamp(target-draft,min=0), using residual_uniform and right-open CDF bins. Return (token, accepted). Uniforms are explicit finite values in [0,1), so the function owns no RNG. Reject invalid probabilities, token indices and uniforms. This single-position probability mechanism makes no wall-clock speed claim.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Preserve target mass with speculative accept and residual resampling →

Your task

Implement one exact categorical speculative step for normalized finite nonnegative [vocab] probabilities. The proposed token must have positive draft mass. Accept it when accept_uniform < min(1,target[proposal]/draft[proposal]). On rejection, inverse-CDF sample from normalized clamp(target-draft,min=0), using residual_uniform and right-open CDF bins. Return (token, accepted). Uniforms are explicit finite values in [0,1), so the function owns no RNG. Reject invalid probabilities, token indices and uniforms. This single-position probability mechanism makes no wall-clock speed claim.

Starter

import math
import torch

def speculative_token(target, draft, proposal, accept_uniform, residual_uniform):
    # TODO: implement speculative_token under the declared contract.
    return None
Inspect the worked answer
import math
import torch

def speculative_token(target, draft, proposal, accept_uniform, residual_uniform):
    if target.ndim!=1 or len(target)<2 or draft.shape!=target.shape:raise ValueError('Expected aligned categorical probability vectors.')
    for probability in (target,draft):
        if not probability.is_floating_point() or not torch.isfinite(probability).all() or (probability<0).any() or abs(probability.double().sum().item()-1)>1e-6:raise ValueError('Probabilities must be finite, nonnegative and normalized.')
    if type(proposal)!=int or not 0<=proposal<len(target) or draft[proposal]<=0:raise ValueError('Proposed token must have positive draft probability.')
    if any(not math.isfinite(u) or not 0<=u<1 for u in (accept_uniform,residual_uniform)):raise ValueError('Uniform draws must belong to [0, 1).')
    acceptance=min(1.,target[proposal].item()/draft[proposal].item())
    if accept_uniform<acceptance:return proposal,True
    residual=(target.detach().double()-draft.detach().double()).clamp_min(0)
    mass=residual.sum()
    if mass<=0:raise ValueError('A rejected proposal must leave positive residual mass.')
    cumulative=(residual/mass).cumsum(0)
    token=int(torch.searchsorted(cumulative,torch.tensor(residual_uniform,dtype=cumulative.dtype),right=True).item())
    return min(token,len(target)-1),False

About this algorithm

How Preserve target mass with speculative accept and residual resampling works

The idea

Speculative decoding speeds up a large target model by letting a small draft model guess tokens, which the target then checks. The check must be exact: the resulting token has to be distributed as if sampled from the target alone.

The rule does that in two parts. A proposed token is accepted with probability min(1, target / draft), so tokens the draft proposes too often are thinned down to the target's share. On a rejection, a new token is drawn from the residual, target - draft clamped at zero and renormalized, which holds exactly the mass the draft undersupplied. Accepted mass plus residual mass adds up to the target probability for every token. Both random numbers are passed in as arguments, so the function is deterministic.

How it works

  1. Validate that target and draft are normalized probability vectors, that proposal has positive draft mass, and that both uniforms lie in [0, 1).
  2. Compute acceptance = min(1, target[proposal] / draft[proposal]).
  3. Return (proposal, True) when accept_uniform < acceptance.
  4. Otherwise build residual = (target - draft).clamp_min(0) in float64 and divide it by its sum.
  5. Take the cumulative sum and use torch.searchsorted with right=True to find the bin that contains residual_uniform.
  6. Return that token with False, capped at the last index as a guard against rounding.

What it costs

Per token
O(vocab)
Accept rate
Σ min(target, draft)
Randomness
two uniforms, passed in

Validation and the residual each scan the vocabulary once; the chance of acceptance is the overlap of the two distributions, so a closer draft is accepted more often.

Where it is used

  • Leviathan, Kalman and Matias (2023) give this accept and resample rule in 'Fast Inference from Transformers via Speculative Decoding'.
  • Hugging Face Transformers offers it as assisted generation through the assistant_model argument of generate().
  • llama.cpp can run a small draft model alongside the main model for speculative decoding.

Watch out for

  • Resampling from the full target after a rejection: tokens the draft already supplied are counted twice and the output no longer follows the target.
  • Forgetting to clamp target - draft at zero, which leaves negative entries that cannot be normalized into a distribution.
  • Calling searchsorted without right=True: a uniform of exactly 0, or one on a bin edge, then selects the lower token, even one with zero residual mass.