Module contents
Stage 6 of 9Research 110 min

Speculative decoding with a distribution guarantee

Implement speculative sampling with small draft and target models sharing a tokenizer, verify distribution preservation statistically, and compare measured speedup with acceptance-based predictions.

After this lesson you can

  • Implement drafting, parallel verification and rejection acceptance with residual sampling.
  • Use a chi-square test to check token distribution against the target.
  • Measure acceptance by position and speedup as a function of k.
  • Compare measured speedup with an analytical model.

Before you start

Propose without changing the distribution

A small draft model can propose several tokens autoregressively. The target model verifies all candidates in one causal pass, which can cost less than running it once per token. This depends on model, context, hardware and batch: verifying kk tokens does not necessarily cost the same as verifying one. The goal is faster sampling while preserving its distribution, not guaranteeing the same sequence from two runs with the same seed.

Speculative sampling implementation uses pp for the draft and qq for the target. The draft proposes x∼px\sim p and it is accepted with probability min⁡(1,q(x)/p(x))\min(1,q(x)/p(x)). If rejected, sample from r(x)∝max⁡(q(x)−p(x),0)r(x)\propto\max(q(x)-p(x),0). If all kk candidates are accepted, obtain an additional token from the target distribution after the last. Leviathan, Kalman and Matias and Chen and colleagues describe this correction.

InteractiveAccept or use the residual

Distribution comparison and residual conditioned on rejection:

A · draft 0.20 · target 0.45 · residual 1.00
B · draft 0.30 · target 0.30 · residual 0.00
C · draft 0.40 · target 0.15 · residual 0.00
D · draft 0.10 · target 0.10 · residual 0.00

Blue: draft; orange: target. After rejection the full residual is sampled; this figure shows its distribution without inventing a drawn token.

2
0.50
ProposalC
Acceptance probability0.375
Decision with uRejected
Residual mass0.250
Finite toy distributions; the control fixes the proposed token and uniform value. The residual shows a distribution, not an invented token.

For token xx, accepted proposal mass is p(x)min⁡(1,q(x)/p(x))=min⁡(p(x),q(x))p(x)\min(1,q(x)/p(x))=\min(p(x),q(x)). Total rejection probability is Z=∑y(q(y)−p(y))+Z=\sum_y(q(y)-p(y))_+, equal to ∑y(p(y)−q(y))+\sum_y(p(y)-q(y))_+ because both distributions sum to one. The residual contributes (q(x)−p(x))+(q(x)-p(x))_+ after its normalized distribution is multiplied by ZZ. Thus emitted mass is min⁡(p(x),q(x))+(q(x)−p(x))+=q(x)\min(p(x),q(x))+(q(x)-p(x))_+=q(x). If Z=0Z=0, rejection does not occur and division by zero is unnecessary.

The proof applies at each actually accepted prefix. After rejection, later candidates are discarded: their distributions were conditioned on a prefix that was not emitted. If temperature, top-k or top-p change, acceptance and residual must use the effective sampling distributions. Draft and target can differ, including their supports; a proposal with p(x)=0p(x)=0 cannot have been sampled from pp.

The residual distribution is not simply the target renormalized over tokens other than the rejected proposal. It is calculated over the entire vocabulary by subtracting draft mass and truncating negative values. A token can be in the target support and absent from the draft support: all its target mass belongs to the residual. If draft and target agree exactly, acceptance is one for every possible proposal and rejection is unreachable.

Two caches and one verification

The draft generates kk candidates while updating its cache. The target receives all kk at once and produces logits at each position; logits from the previous prefix evaluate the first candidate and output after each candidate evaluates the next. This alignment avoids shifting probabilities by one position. The local test uses the shared SmolLM2-135M and SmolLM2-360M tokenizer, temperature 0.8 and top-k 32 for both; EOS is deliberately excluded to fix the step count.

When candidate ii is rejected, both caches must retain only the prefix and earlier accepted candidates. Then process the residual token in both models to continue from the same prefix. If all are accepted, process the additional target token. In Transformers 5.23, crop(-n) removes the last nn tokens; other versions may use another contract. Checking length after every rollback avoids a silent error that appears only after several rounds.

Parallel verification needs a causal mask: prediction for candidate ii may depend on earlier candidates, not later ones. The target can calculate them in one call because the draft has already proposed the full block; this does not mean all candidates will be accepted. The additional-token distribution corresponds to the position after the last candidate and is used only when all earlier ones were accepted. With EOS, stop and truncate both output and caches at the stopping point; the experiment excludes EOS to avoid hiding that case.

Statistical test and its scope

The distribution-preservation test compares 100000 direct next-token samples with 100000 speculative outputs on a fixed prefix. To make expected counts interpretable, 16 likely-token categories and one remaining-token category are fixed before sampling. A chi-square homogeneity test compares the two tables and displays the minimum expected count. Grouping can hide differences within the remaining category.

A pp value above 0.05 means the test finds insufficient evidence against equality at the chosen level. It does not prove that all distributions, prefixes or implementations are identical. The algebraic proof establishes the ideal property; the statistical test seeks errors in one particular configuration and sample. A one-token test alone does not validate cache alignment in long generations. The lab also forces a rejection outside the benchmark and compares both recovered logits with full-prefix recomputation using explicit BF16 tolerance.

In the recorded run, the test gave χ2=15.6707\chi^2=15.6707, 16 degrees of freedom and p=0.476172p=0.476172, with minimum expected count 593.5. No evidence of a difference was found for that grouping and prefix. First-candidate acceptance was 0.7529 in the vectorized test. The sample uses both models’ real distributions at that prefix but does not run 100000 transformer passes: it reuses those logits for sampling.

Acceptance and cost

The speedup model counts tokens emitted per verification. With constant independent acceptance α\alpha, at least one token is always emitted and the probability of emitting more than ii tokens is αi\alpha^i. Thus E[N]=1+α+⋯+αkE[N]=1+\alpha+\cdots+\alpha^k. For α=0.8\alpha=0.8 and k=4k=4 the result is 3.3616 tokens per round. Independence and constant rate are simplifications; observed acceptances can depend on position and prefix.

InteractiveSpeedup model and measurement
  • Simplified assumption
  • Measured
  • Prediction with costs

The point k=2 has attempts 12, 8 and acceptances 8, 5 by position. A value below one means the speculative system was slower on that sample. Prediction and observation use the same short trace; they are not an independent validation.

0.75
0.30
1
Measured k2
Observed / predicted0.546 / 0.444 ×
Relative difference23.1 %
Observed rounds12
The hypothetical curve uses a constant rate and selected relative cost. Measured points and their prediction were recorded with the two models and lab scope described below.

A simple cost model divides E[N]E[N] by verification and draft cost in units of one target step. If verification grows with kk, the draft is not small enough or the batch already uses the GPU well, speedup can disappear. Resampling, rollback and Python work also count. A calculation omitting them can predict a gain that is not observed. EAGLE and Medusa study other candidate-generation methods; they are not implemented in this lab.

In the recorded sweep, the target alone produced 5.933 tokens/s. For k=1k=1, 2.857 tokens/s were observed, a ratio of 0.482 against prediction 0.424, a 13.6% relative difference. For k=2k=2 and k=4k=4 the differences were 23.1% and 33.9%, respectively. None of the three configurations sped up this run. Position rates come from few rounds and costs were measured under shared conditions; there is no evidence the model predicts all values within 20% or that this model pair improves a different workload.

The plotted prediction uses observed conditional acceptance at each position and multiplies survival probabilities to estimate tokens per round. The denominator sums one kk verification, one target step and k+1k+1 draft steps measured separately on a fixed prefix. The last two terms include the final-token update. Selection, resampling and some Python overhead are omitted; acceptance and cost are also estimated from few samples. This is an explanatory model fitted to this implementation, not an independent evaluation of its accuracy.

In the sweep, a position’s attempt counter includes only rounds that reached it. Dividing acceptances by all rounds would underestimate that conditional rate, because an earlier rejection prevents later positions from being attempted. Multiplying conditional rates recovers the fraction of rounds reaching each depth in that sample. If the last position was attempted once, its estimate has high uncertainty and does not justify extrapolation to another workload.

Local lab

PyTorch CUDA, NumPy, SciPy, Transformers and the pinned revisions of SmolLM2-135M and SmolLM2-360M are required. If absent from cache, they can be downloaded beforehand with a connection. The comparison uses BF16 on the local GPU, one prompt and short output; CUDA is synchronized to measure wall time. The sweep and predictions do not characterize every length or a concurrent server.

The default sample count is 100000 per group and sweep output is at least 24 tokens. For a quick flow check use P10_L06_TOKENS=8; P10_L06_SAMPLES may also be changed, but fewer samples weaken the test. P10_L06_OUT selects the result file; if unset, one is created in a temporary directory. The graph retains recorded results and does not change when the cell is rerun.

[ ]Two models and speculative samplingLocal GPU
import json, math, os, tempfile, time, numpy as np, torch
from scipy.stats import chi2_contingency
from transformers import AutoModelForCausalLM,AutoTokenizer
torch.set_num_threads(1);torch.manual_seed(823);rng=np.random.default_rng(823)
assert torch.cuda.is_available();device='cuda';draft_name='HuggingFaceTB/SmolLM2-135M';target_name='HuggingFaceTB/SmolLM2-360M'
draft_rev='93efa2f097d58c2a74874c7e644dbc9b0cee75a2';target_rev='f8027fd0eaeea54caa13c31d31b9fdc459c38b49'
tokenizer=AutoTokenizer.from_pretrained(target_name,revision=target_rev,local_files_only=True);draft_tokenizer=AutoTokenizer.from_pretrained(draft_name,revision=draft_rev,local_files_only=True)
assert tokenizer.get_vocab()==draft_tokenizer.get_vocab() and tokenizer.eos_token_id==draft_tokenizer.eos_token_id
draft=AutoModelForCausalLM.from_pretrained(draft_name,revision=draft_rev,local_files_only=True,dtype=torch.bfloat16).eval().cuda();target=AutoModelForCausalLM.from_pretrained(target_name,revision=target_rev,local_files_only=True,dtype=torch.bfloat16).eval().cuda()
prompt=tokenizer('A curious scientist opens a small wooden box and finds',return_tensors='pt').input_ids.to(device);TOPK=32;TEMPERATURE=.8;EOS=tokenizer.eos_token_id

def distribution(logits):
    logits=logits.float().clone()/TEMPERATURE;logits[EOS]=-torch.inf
    values,ids=torch.topk(logits,TOPK);probs=torch.softmax(values,dim=0);out=torch.zeros_like(logits);out.scatter_(0,ids,probs);return out
def draw(probs):return int(torch.multinomial(probs,1).item())
def init(model):
    out=model(input_ids=prompt,use_cache=True);return out.past_key_values,out.logits[0,-1]
def feed(model,cache,token):
    out=model(input_ids=torch.tensor([[token]],device=device),past_key_values=cache,use_cache=True);return out.past_key_values,out.logits[0,-1]
def statistical(target_logits,draft_logits):
    p=distribution(target_logits).cpu().numpy().astype(np.float64);q=distribution(draft_logits).cpu().numpy().astype(np.float64);p/=p.sum();q/=q.sum();n=int(os.environ.get('P10_L06_SAMPLES','100000'));assert n>=1000
    direct=rng.choice(len(p),size=n,p=p);proposed=rng.choice(len(q),size=n,p=q);accept=rng.random(n)<np.minimum(1,p[proposed]/q[proposed]);residual=np.maximum(p-q,0);residual/=residual.sum()
    speculative=proposed.copy();speculative[~accept]=rng.choice(len(p),size=(~accept).sum(),p=residual)
    # Agrupar 16 tokens probables y el resto antes de observar los resultados.
    top=np.argsort(p)[-16:];category=np.full(len(p),16);category[top]=np.arange(16)
    table=np.stack([np.bincount(category[direct],minlength=17),np.bincount(category[speculative],minlength=17)])
    chi,pvalue,dof,expected=chi2_contingency(table,correction=False);print('chi² homogeneidad',round(chi,4),'gl',dof,'p',round(pvalue,6),'mínimo esperado',round(expected.min(),1),'muestras por grupo',n,'aceptación',round(accept.mean(),4),flush=True)
    return {'chi2':chi,'df':dof,'pvalue':pvalue,'min_expected':float(expected.min()),'n':n,'p':p.tolist(),'q':q.tolist()}

def speculative(k,max_new=24,verify=False,force_reject=False):
    tc,tlog=init(target);dc,dlog=init(draft);prefix=prompt.shape[1];out=[];attempt=[0]*k;accepted=[0]*k;rounds=0
    torch.cuda.synchronize();start=time.perf_counter()
    while len(out)<max_new:
        rounds+=1;tokens=[];qs=[]
        for i in range(k):
            q=distribution(dlog);token=draw(q);tokens.append(token);qs.append(q);dc,dlog=feed(draft,dc,token)
        checked=target(input_ids=torch.tensor([tokens],device=device),past_key_values=tc,use_cache=True);tc=checked.past_key_values
        ps=[distribution(tlog)]+[distribution(checked.logits[0,i-1]) for i in range(1,k)];bonus=distribution(checked.logits[0,k-1]);chosen=None;accepted_count=0
        for i,token in enumerate(tokens):
            attempt[i]+=1;ratio=min(1.,float(ps[i][token]/qs[i][token]))
            if not(force_reject and rounds==1 and i==0) and rng.random()<ratio:out.append(token);accepted[i]+=1;accepted_count+=1
            else:
                residual=(ps[i]-qs[i]).clamp_min(0);residual=residual/residual.sum();chosen=draw(residual);break
        if chosen is None:chosen=draw(bonus)
        out.append(chosen)
        # Transformers 5.23: un entero negativo indica cuántos tokens se eliminan.
        remove=k-accepted_count
        if remove:tc.crop(-remove);dc.crop(-remove)
        assert tc.get_seq_length()==prefix+accepted_count and dc.get_seq_length()==prefix+accepted_count
        tc,tlog=feed(target,tc,chosen);dc,dlog=feed(draft,dc,chosen);prefix+=accepted_count+1
        assert tc.get_seq_length()==prefix and dc.get_seq_length()==prefix
        if verify:
            full=torch.cat([prompt,torch.tensor([out],device=device)],dim=1)
            target_full=target(input_ids=full,use_cache=False).logits[0,-1];draft_full=draft(input_ids=full,use_cache=False).logits[0,-1]
            target_error=float((tlog-target_full).abs().max());draft_error=float((dlog-draft_full).abs().max())
            assert torch.allclose(tlog,target_full,atol=.5,rtol=.05) and torch.allclose(dlog,draft_full,atol=.5,rtol=.05)
            print('rollback contra recomputación completa: longitud',prefix,'error objetivo',target_error,'borrador',draft_error,flush=True)
    torch.cuda.synchronize();elapsed=time.perf_counter()-start
    return {'k':k,'tokens':len(out),'rounds':rounds,'seconds':elapsed,'tokens_per_s':len(out)/elapsed,'attempt':attempt,'accepted':accepted,'text':tokenizer.decode(out[:max_new])}

def baseline(max_new=24):
    cache,logits=init(target);torch.cuda.synchronize();start=time.perf_counter();tokens=[]
    for _ in range(max_new):
        token=draw(distribution(logits));tokens.append(token);cache,logits=feed(target,cache,token)
    torch.cuda.synchronize();return len(tokens)/(time.perf_counter()-start)

def timed_calls(model,count):
    cache,_=init(model);ids=torch.full((1,count),42,device=device,dtype=torch.long);times=[]
    for _ in range(3):
        torch.cuda.synchronize();start=time.perf_counter();model(input_ids=ids,past_key_values=cache,use_cache=True);torch.cuda.synchronize();times.append(time.perf_counter()-start);cache.crop(-count)
    return sorted(times)[1]

@torch.inference_mode()
def main():
    print('GPU',torch.cuda.get_device_name(),'objetivo',target_name,'borrador',draft_name,'BF16 top-k',TOPK,'temperatura',TEMPERATURE,'EOS excluido',flush=True)
    tc,tlog=init(target);dc,dlog=init(draft);stats=statistical(tlog,dlog);del tc,dc
    max_new=int(os.environ.get('P10_L06_TOKENS','24'));assert max_new>=4
    base=baseline(max_new);draft_time=timed_calls(draft,1);target_time=timed_calls(target,1);results=[]
    print('baseline objetivo tokens/s',round(base,3),'paso borrador s',round(draft_time,4),'paso objetivo s',round(target_time,4),flush=True)
    for k in (1,2,4):
        verify_time=timed_calls(target,k);row=speculative(k,max_new);alpha=[a/n if n else 0 for a,n in zip(row['accepted'],row['attempt'])];survival=1.;expected=1.
        for x in alpha:survival*=x;expected+=survival
        predicted=expected*target_time/(verify_time+target_time+(k+1)*draft_time);observed=row['tokens_per_s']/base
        row.update({'alpha':alpha,'expected':expected,'verify_seconds':verify_time,'predicted':predicted,'observed':observed,'relative_error':abs(predicted-observed)/predicted if predicted else None});results.append(row)
        print('k',k,'intentados',row['attempt'],'aceptados',row['accepted'],'tokens/s',round(row['tokens_per_s'],3),'aceleración real',round(observed,3),'predicha',round(predicted,3),'error relativo',round(row['relative_error'],3),flush=True)
    # El rechazo forzado comprueba el rollback, no forma parte de la prueba de distribución ni del cronómetro de rendimiento.
    checked=speculative(2,4,verify=True,force_reject=True);print('rechazo forzado: intentos',checked['attempt'],'aceptaciones',checked['accepted'],flush=True)
    top=np.argsort(stats['p'])[-8:][::-1];summary={'target':target_name,'draft':draft_name,'gpu':torch.cuda.get_device_name(),'test':{k:stats[k] for k in ('chi2','df','pvalue','min_expected','n')},'tokens':[tokenizer.decode([int(i)]) for i in top],'p':[stats['p'][i] for i in top],'q':[stats['q'][i] for i in top],'results':results,'baseline':base}
    out=os.environ.get('P10_L06_OUT') or os.path.join(tempfile.mkdtemp(prefix='p10-l06-'),'evidence.json')
    with open(out,'w',encoding='utf8') as f:json.dump(summary,f,ensure_ascii=False)
    print('resultados guardados en',out)
if __name__=='__main__':main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
With independent acceptance 0.8 and k=4, how many tokens are emitted per round on average, including the final token?
Proof
Prove: Prove the emitted mass for a token x.
The proof will appear here as you work.

Step 1 of 2. What mass of x is accepted from the draft?

Code
Implement speculative_step(p_draft,q_target,draft_tokens,rng). p_draft contains one distribution per candidate, q_target one per candidate plus the additional distribution, and rng has random() and choice(n,p=...). Return a list: accept each candidate with min(1,q/p); on the first rejection sample normalized max(q−p,0) and stop; if all are accepted, sample from q_target[-1]. Distributions are normalized NumPy arrays and candidates have positive probability in p.
import numpy as np
def speculative_step(p_draft,q_target,draft_tokens,rng):
  ...
Shift+Enter to run
Quiz
Why can speculative speedup disappear with large batches?
Key idea
Rejection and residual correction preserve the target distribution under their assumptions. Acceptance helps model benefit, but only complete measurement reveals whether speculation speeds up the specific workload.