# Speculative decoding

> Speculative decoding chhote draft model se tokens guess karwata hai, bada model ek forward pass se verify karta hai; accept aur correction sampling rules output distribution same rakhte hain. Yeh page expected speedup derive karta hai aur interactive widget deta hai।

- URL: https://dmxsf.com/hi/wiki/inference/speculative-decoding/
- [DMXSF](https://dmxsf.com/hi/about/)
- मध्यम
- अपडेट किया गया: 2026-11-18
- Tags: Speculative decoding, Inference, Decoding & sampling

## यह पृष्ठ पूरा करने पर आप

- Samjhayein decoding dheemi kyun hai, aur "guess, verify, correct" se speed kaise badhti hai।
- Spasht karein accept aur correction sampling rules output distribution kyun nahi badalte, aur code se verify karein।
- Expected output aur speedup derive karein, aur interactive experiment se dekhein acceptance rate aur draft length speedup kaise badalte hain।
- Draft ke kai srot batayein, aur speculative decoding kab faaydemand nahi, bhi।

Speculative decoding ek **chhota, fast draft model** se agle $\gamma$ tokens guess karwata hai, phir **bada model ek forward pass se parallel** candidates verify karta hai; "probability ke hisaab se accept, reject par correction distribution se resample" rule se output distribution sirf bade model wale se exactly same rehta hai. Yeh lossless speedup hai: har round kam se kam 1 token, kismat ho to ek round mein $\gamma+1$; actual speedup do quantities se aata hai - draft accept hone ki probability $\alpha$, aur draft model ka target ke relative time ratio $c$।

## Decoding itni dheemi kyun, aur tez kaise

Autoregressive decoding ek baar mein ek token; agla step pichhle ka khatam hone ka intezaar karta hai. Batch chhota ho to bottleneck compute nahi - saare weights memory se compute units mein le jaana hai: har token ke liye poora model padhna padta hai।

Misaal: 7B BF16 model, A100 80GB SXM par decode (batch 1; attention, KV cache reads aur kernel overhead ignore):

| Quantity | Value | Kaise mila |
| --- | --- | --- |
| BF16 weight size | 14 GB | $7\times10^{9}$ params x 2 bytes |
| Memory bandwidth | 2,039 GB/s | NVIDIA A100 datasheet (80GB SXM) |
| BF16 dense compute | 312 TFLOPS | NVIDIA A100 datasheet |
| Weights ek baar padhne ka time | 6.87 ms; ceiling lagbhag 146 token/s | 14 GB ÷ 2,039 GB/s |
| Ek token ka compute time | 0.045 ms | $2\times7\times10^{9}$ FLOP ÷ 312 TFLOPS |
| 5 positions ek saath | 0.22 ms | 5 x 0.045 ms |

Weights padhne mein 6.87 ms, ek token ka compute 0.045 ms - lagbhag 153 guna farq (compute-to-bandwidth ratio $312\times10^{12}/2039\times10^{9}\approx153$ FLOP/byte). Weights waise bhi padhne hain - **bada model isi read par $\gamma+1$ positions process kar de to lagbhag free hai**. Speculative decoding yahi karta hai: layak positions dhoondhta hai - sasta draft model candidates guess karta hai, bada model ek saath verify karta hai. Yahan ka "compute-to-bandwidth ratio" roofline model ka turning point hai; derivation [GPU aur roofline model](https://dmxsf.com/hi/wiki/systems/gpu-and-roofline/) mein।

## Core method: guess, verify, correct

Ek round ke steps:

1. **Guess**: draft model autoregressively $\gamma$ candidate tokens $x_1,\dots,x_\gamma$ propose karta hai, aur har candidate ki probability $q_i$ bhi record karta hai।
2. **Verify**: bada model prefix + $\gamma$ candidates ka ek forward karta hai, $\gamma+1$ positions par distributions $p_1,\dots,p_{\gamma+1}$ milte hain।
3. **Accept ya reject**: baen se dahine check; candidate $x_i$ probability $\min(1,\,p_i(x_i)/q_i(x_i))$ se accept hota hai; pehla reject aate hi ruk jaao, baaki candidates cancel।
4. **Correct**: rejected position par correction distribution se naya token sample (agle section mein); agar saare $\gamma$ accept ho gaye to $\gamma+1$-th position ki distribution $p_{\gamma+1}$ se ek "free" token aur sample।

*Figure: Speculative decoding ka ek round: draft serially 4 guess karta hai, target model ek forward par 5 positions check karta hai; pehle do accept, teesri par correct - is round ke 3 tokens।*

## Output distribution kyun nahi badalta

Sirf ek position dekhein. Target model ki distribution $p$, draft ki $q$. Draft token $x\sim q$ probability $\min(1,p(x)/q(x))$ se accept hota hai; reject par correction distribution se sample:

$$
p'(x)=\frac{\max\big(0,\;p(x)-q(x)\big)}{\sum_{y}\max\big(0,\;p(y)-q(y)\big)}
$$

$\beta=\sum_x\min\big(p(x),q(x)\big)$ likhein - yeh draft accept hone ki total probability bhi hai aur $1-\mathrm{TV}(p,q)$ ke barabar bhi ($\mathrm{TV}$ total variation distance). Denominator exactly $1-\beta$ hai. To output $x$ ki probability:

$$
\Pr[x]=\underbrace{q(x)\min\!\Big(1,\frac{p(x)}{q(x)}\Big)}_{\text{propose + accept}}+\underbrace{(1-\beta)\,p'(x)}_{\text{reject ke baad correction}}
=\min\big(p(x),q(x)\big)+\big(p(x)-\min(p(x),q(x))\big)=p(x)
$$

Accept hue hisse ne $\min(p,q)$ diya; gap $p-\min(p,q)$ correction distribution ne poora kiya - total exactly $p$. Reject par seedha $p$ se sample karte to high-probability tokens double count hote, distribution kharaab hoti. Baaki positions sirf tab use hote hain jab saare pichhle accept hon, isliye per-position result poore sequence par extend hota hai (Leviathan adi, 2023, Appendix A.1)।

## Kitna tez: expected output aur speedup

Har draft token ki accept probability $\alpha$ (positions i.i.d. assume). Ek round ke tokens $K$ = "lagatar accepts (max $\gamma$) + 1":

$$
\Pr[K=k]=\alpha^{k-1}(1-\alpha)\quad(k\le\gamma),\qquad \Pr[K=\gamma+1]=\alpha^{\gamma}
$$

$$
\mathbb E[K]=\frac{1-\alpha^{\gamma+1}}{1-\alpha}
$$

Ek round ka time $\gamma$ draft steps + 1 target verification. Draft step target step ka $c$ guna (draft cost ratio $c$), to round ka time $\gamma c+1$; normal decoding ke relative speedup:

$$
\text{speedup}=\frac{1-\alpha^{\gamma+1}}{(1-\alpha)(\gamma c+1)}
$$

Yehi Leviathan adi ka Theorem 3.8 hai. $c\to0$ aur $\gamma\to\infty$ par speedup $1/(1-\alpha)$ ki taraf jaata hai. Paper ki Table 1 $c=0$ par kuch numbers deti hai; neeche wala widget same values deta hai, jaise $\alpha=0.9,\gamma=10$ par 6.86x।

### Khud karein: speculative decoding lab

Acceptance rate $\alpha$, draft length $\gamma$ aur draft cost ratio $c$ drag karein. Upar wala chart speedup vs $\gamma$, neeche wala ek round ke token count ka distribution; dots 2000 rounds ke same-rule simulation ki frequencies hain।

1. **Draft jitna lamba utna achha nahi.** Default settings ($\alpha=0.8$, $c=0.05$) par $\gamma=4$ speedup 2.80x; optimal $\gamma=8$, 3.09x; aur lamba $\gamma=16$ par gir kar 2.72x - kyunki peeche ke drafts accept hona mushkil, par draft time phir bhi lagta hai।
2. **$c=0$ par bhi ceiling hai.** $\alpha=0.8$ par max $1/(1-0.8)=5$x; $\gamma=4$ sirf 3.36x; $\gamma=32$ par hi lagbhag 5.0x ke paas।
3. **Acceptance rate draft length se zyada important.** $c=0.05$, $\gamma=4$ rakhein; $\alpha$ 0.8 se 0.6 - speed 2.80x se 1.92x; aur per-kept-token target model ke extra positions 1.49x se 2.17x: rejected drafts compute waste karte hain।
4. **Draft mehnga ho to fayda kha jaata hai.** $\alpha=0.8$ par $c$ 0.05 se 0.3 - optimal $\gamma$ 8 se 3, speedup sirf 1.55x।
5. **Dheema bhi ho sakta hai.** $\alpha=0.3$, $c=0.3$, $\gamma=4$ par speedup 0.65x - na use karne se bhi dheema. $\gamma=1$ par speedup $(1+\alpha)/(1+c)$ - fayda sirf $\alpha>c$ par।

## Draft kahan se aata hai

| Scheme | Draft source | Khaasiyat |
| --- | --- | --- |
| Independent small model | Same family, same tokenizer wala chhota model | Plug-and-play, no training; ek aur model rakhna padta hai. Leviathan adi: draft target se lagbhag 2 orders chhota ho to aam taur best |
| N-gram lookup | Statistical LM; evaluation sirf table lookup, $c\approx0$ | $\alpha$ kam: T5-XXL en-de translation par bigram model se $\alpha\approx0.2$ |
| Extra heads ([Medusa](https://arxiv.org/abs/2401.10774)) | Target model ke top par kuch heads, aage ke kai tokens parallel predict | Independent draft model nahi chahiye; tree attention se kai candidates ek saath verify; heads train karne padte hain |
| Feature-level draft ([EAGLE](https://arxiv.org/abs/2401.15077)) | Second-to-last layer ke features par autoregression se draft | Report: LLaMA2-Chat 70B par latency speedup 2.7-3.5x |
| MTP module (DeepSeek-V3) | Training-time MTP module, inference par reuse | Report: doosre token ki acceptance rate 85%-90% across topics; decode throughput 1.8x |

DeepSeek-V3 ke numbers ko upar wale formula se cross-check: next ke alawa 1 aur token predict = $\gamma=1$, expected output per round $1+\alpha$. $\alpha=0.85$ se 0.90 par 1.85-1.90; reported 1.8x thoda kam - farq draft module aur verification ka extra overhead: 1.8x ko $(1+\alpha)/(1+c)$ samjhein to $c$ lagbhag 0.03-0.06।

## Kab faaydemand nahi

| Situation | Wajah | Related quantity |
| --- | --- | --- |
| Acceptance rate low (open-ended writing, draft model weak) | Zyada-tar candidates reject; per round lagbhag 1 token | $\alpha$ chhota |
| Draft model itna sasta nahi | Har round $\gamma c$ extra time | $c$ bada |
| Batch bada, decode already compute-bound | $\gamma+1$ positions verify free nahi. Upar wale A100 misaal mein lagbhag batch 150 par compute bhar jaata hai; uske baad speculative ka fayda tezi se ghatta hai | Round ka time ab 1 nahi |
| Memory tight | Draft model aur uski KV cache extra | - |

## Code se: "distribution same" aur expected output verify

4-token toy distribution par do cheezein: accept + correction rule ke output frequencies $p$ ke barabar hain? Aur per-round average tokens formula ke barabar?

```python
import numpy as np

rng = np.random.default_rng(0)
p = np.array([0.50, 0.25, 0.15, 0.10])  # target model ki kisi position ki distribution
q = np.array([0.25, 0.25, 0.25, 0.25])  # draft model ki usi position wali distribution
residual = np.maximum(p - q, 0)
residual /= residual.sum()               # correction distribution norm(max(0, p - q))
alpha = np.minimum(p, q).sum()           # ek draft token ki accept probability

def one_position(n):
    x = rng.choice(4, size=n, p=q)                       # draft propose
    accept = rng.random(n) < np.minimum(1, p[x] / q[x])  # min(1, p/q) se accept
    out = np.where(accept, x, rng.choice(4, size=n, p=residual))  # reject par correction se
    return out, accept.mean()

out, rate = one_position(1_000_000)
print("output freq  :", np.round(np.bincount(out, minlength=4) / len(out), 3))
print("target dist p:", p)
print(f"accept rate {rate:.3f}, theory sum(min(p, q)) = {alpha:.2f}")

gamma, rounds = 4, 200_000
x = rng.choice(4, size=(rounds, gamma), p=q)
accept = rng.random((rounds, gamma)) < np.minimum(1, p[x] / q[x])
n_accepted = np.where(accept.all(axis=1), gamma, accept.argmin(axis=1))  # pehle reject se pehle ka count
print(f"tokens per round {np.mean(n_accepted + 1):.3f}, formula (1-a^(g+1))/(1-a) = {(1 - alpha ** (gamma + 1)) / (1 - alpha):.3f}")
```

Run result:

```text
output freq  : [0.5   0.25  0.149 0.1  ]
target dist p: [0.5  0.25 0.15 0.1 ]
accept rate 0.750, theory sum(min(p, q)) = 0.75
tokens per round 3.054, formula (1-a^(g+1))/(1-a) = 3.051
```

Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।

Output frequencies $p$ se teen decimals tak match; per-round simulation 3.054 vs formula 3.051 - sampling error ke andar।

## Summary aur exercises

**Is page ke mukhya points:**

1. Chhote batch wali decoding memory-bandwidth-bound hai; bada model kuch extra positions par lagbhag free।
2. Speculative decoding: draft model $\gamma$ tokens guess, bada model ek forward par verify, $\min(1,p/q)$ se accept, reject par correction distribution se resample - output distribution sirf bade model wale se exactly same।
3. Expected per-round $(1-\alpha^{\gamma+1})/(1-\alpha)$ tokens; speedup mein $\gamma c+1$ se divide; acceptance rate kam, draft mehnga ya batch bada - fayda ghatta hai, negative bhi ho sakta hai।

### Quick self-test

**1. Speculative decoding output quality kyun nahi ghatata?**

- [ ] Kyunki draft model bade model jitna achha hai
- [x] Kyunki draft tokens min(1, p/q) se accept hote hain, reject par correction distribution norm(max(0, p − q)) se sample hota hai - har position ka output distribution exactly target ki distribution
- [ ] Kyunki bada model draft ki saari galtiyan haath se theek karta hai
- [ ] Kyunki yeh sirf greedy decoding mein use hota hai

> Accept wala hissa min(p, q) deta hai; gap p − min(p, q) correction distribution poora karti hai - total exactly p. Kisi bhi sampling temperature par hold hota hai; greedy sirf special case hai।

**2. alpha = 0.8, draft length gamma = 4 - ek round mein expected tokens kitne?**

- [ ] 2.0
- [x] 3.36
- [ ] 4.0
- [ ] 5.0

> Expected = (1 − 0.8^5) / (1 − 0.8) = (1 − 0.32768) / 0.2 lagbhag 3.36. Ceiling gamma + 1 = 5 hai; sirf tab jab saare candidates accept hon।

**3. Kaun si situations speculative decoding ka fayda saaf ghatati hain? (multiple)**

- [x] Draft model ki predictions target se kaafi alag - acceptance rate low
- [x] Batch bahut bada, decode compute ceiling ke paas
- [x] Draft model target ke relative itna sasta nahi - c bada
- [ ] Generated text lamba hai

> Pehle teen alpha chhota, verification free nahi, c bada - in se match karte hain. Generated text jitna lamba, formula mein "per round kam se kam ek bada-model call" wala boundary effect utna chhota - adverse factor nahi।

**4. Draft token reject hone par us position ka token kahan se sample hota hai?**

- [ ] Seedha target model ki distribution p se
- [x] Correction distribution norm(max(0, p − q)) se
- [ ] Draft model ke doosre highest probability token se
- [ ] Draft model se dobara sampling

> Accept wala step min(p, q) de chuka hai; sirf p − min(p, q) bharna hai. Seedha p se sampling high-probability tokens ko double count karti - distribution badal jaata hai।

**Exercises:**

1. $\alpha=0.9,\gamma=2,c=0$ - per-round expected tokens aur speedup kitne?
2. Lab mein $\alpha=0.8,c=0.3$ set karein - optimal $\gamma$ kitna? $c=0.05$ se itna chhota kyun?
3. Target distribution $p=(0.5,0.25,0.15,0.1)$, draft uniform - $\alpha$ nikaalein; phir $\gamma=4$ par per-round expected tokens।

<details>
<summary>Reference answers</summary>

1. $(1-0.9^{3})/(1-0.9)=0.271/0.1=2.71$ tokens; $c=0$ par round ka time 1, to speedup bhi 2.71x - paper ki Table 1 se match।
2. Optimal $\gamma=3$, speedup lagbhag 1.55x. Draft steps mehnge hone par har extra guess $c=0.3$ target steps kharch karta hai, aur peeche ke candidates ki accept probability $\alpha^k$ se girti rehti hai - jaldi rukna chahiye।
3. $\alpha=\sum_x\min(p,q)=0.25+0.25+0.15+0.10=0.75$; per-round expected $(1-0.75^{5})/(1-0.75)\approx3.05$ tokens - upar wale code ke 3.051 se match।

</details>

## Aage padhein

- Original papers: Leviathan, Kalman aur Matias, [Fast Inference from Transformers via Speculative Decoding](https://arxiv.org/abs/2211.17192) (ICML 2023) - is page ke accept rule, Theorem 3.8 aur Table 1 isi se; Chen adi, [Accelerating Large Language Model Decoding with Speculative Sampling](https://arxiv.org/abs/2302.01318) (2023) - DeepMind ka same-time independent work, Chinchilla 70B par 2-2.5x।
- Cai adi, [Medusa](https://arxiv.org/abs/2401.10774) (2024); Li adi, [EAGLE](https://arxiv.org/abs/2401.15077) (2024)।
- DeepSeek-AI, [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) (2024): multi-token prediction aur acceptance rates।
- NVIDIA, [A100 Tensor Core GPU datasheet](https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf): is page ke bandwidth aur compute numbers।
- Related pages: [decoding aur sampling](https://dmxsf.com/hi/wiki/inference/decoding-and-sampling/), [KV cache](https://dmxsf.com/hi/wiki/inference/kv-cache/), [inference service](https://dmxsf.com/hi/wiki/inference/serving/), [model quantization](https://dmxsf.com/hi/wiki/inference/quantization/)।

- Spector aur Re, [An Online Speculative Decoding Framework](https://arxiv.org/abs/2310.07177) (2023): acceptance rate se online decide karte hain speculative chalana hai ya nahi; halki load par normal decoding par wapas।
- Miao adi, [SpecInfer](https://arxiv.org/abs/2305.09781) (MLSys 2024): token tree se kai draft paths ek saath parallel verify - per-step accepted tokens badhane ke liye।
- Fu adi, [EAGLE-2](https://arxiv.org/abs/2406.16858) (2024) aur [EAGLE-3](https://arxiv.org/abs/2503.01840) (2025): feature-level draft heads acceptance rate aur upar - production systems ka aam tareeka ban chuka hai।
- Yan adi, [Lookahead Decoding](https://arxiv.org/abs/2402.02057) (2024): independent draft model ke bina, Jacobi iteration se kai positions parallel aage।

## सहायक कोड

[Speculative decoding: the rule, the formulas, a real draft and target](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/speculative-decoding): The accept/reject rule that keeps the target's exact distribution, checked on the page's toy distribution, by exact algebra and on real models; the formulas of Leviathan et al.; a draft and target byte-level pair run with KV caches; and when it does not pay.

- सहायक रिपॉज़िटरी में चलाएँ (--quick से तेज़ जाँच): `uv run dmxsf run inference/speculative-decoding`
- [प्रयोग स्क्रिप्ट देखें](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/speculative-decoding/run.py)
- [प्रयोग विवरण](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/speculative-decoding/README.en.md)
- [`speculative.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/inference/speculative.py)
- [सूची में देखें](https://dmxsf.com/hi/code/#speculative-decoding)

## अक्सर पूछे जाने वाले सवाल

### Speculative decoding model ka output badal deta hai?

Nahi. Rule hai: draft token min(1, p/q) probability se accept hota hai, reject par correction distribution se sample - har position ka output distribution exactly target model ke p ke barabar rehta hai, isliye lossless speedup; greedy decoding mein target model ka hi greedy sequence milta hai (floating-point errors ko chhod kar). Sirf speed badalti hai, quality nahi।

### Draft model kaise chunein?

Sabse aam: same family, same tokenizer wala chhota model. Leviathan adi report karte hain ki draft model target se lagbhag do orders of magnitude chhota ho to aam taur par best - acceptance rate aur draft cost ka balance chahiye. Alag draft model nahi rakhna ho to Medusa ke extra heads, EAGLE ke feature-level draft, ya DeepSeek-V3 jaise training-time multi-token prediction (MTP) module ka reuse।

### Speculative decoding aam taur par kitna tez?

Acceptance rate, draft cost, hardware aur batch par nirbhar - fixed number nahi. Public reports: T5-XXL par 2-3x (Leviathan adi), Chinchilla 70B par 2-2.5x (Chen adi), LLaMA2-Chat 70B par EAGLE latency speedup 2.7-3.5x, DeepSeek-V3 ne MTP se decode throughput 1.8x bataya।

### Batch bahut bada ho to speculative decoding kaam karti hai?

Fayda ghat jaata hai. Speculative decoding ka fayda "batch chhoti, decode memory-bandwidth-bound, compute spare" se aata hai; batch itna bada ki compute bhar jaaye (A100 par 7B model ke liye lagbhag batch 150), to gamma+1 positions verify karna free nahi rehta, aur rejected drafts compute waste karte hain।

### KV cache aur quantization ke saath milkar use ho sakta hai?

Haan, stack ho sakta hai. KV cache target model ke verification ko sirf naye positions par kaam karne deta hai; quantization har step ke weight reads kam karta hai - dono target model ke ek step ki lagat ghataate hain; speculative decoding target model calls ki serial ginti ghataata hai. Draft model khud bhi quantize ho sakta hai, draft cost c kam karne ke liye।
