# Decoding aur sampling: temperature, Top-k, Top-p aur beam search

> Decoding probability ko token banata hai: greedy sabse bada chunta hai, temperature dhaar badalti hai, Top-k/Top-p tail kaatte hain, beam search kai candidates rakhta hai; yeh output ki certainty, diversity aur quality tay karte hain।

- URL: https://dmxsf.com/hi/wiki/inference/decoding-and-sampling/
- [DMXSF](https://dmxsf.com/hi/about/)
- शुरुआती
- अपडेट किया गया: 2026-11-18
- Tags: Decoding & sampling, Inference

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

- Spasht karein model scores aur probability distribution deta hai, jawab nahi।
- Samjhayein greedy, temperature, Top-k, Top-p har ek selection kaise badalta hai, aur kuch lines ke code se implement karein।
- Batayein beam search kai candidates ek saath kaise rakhta hai।
- Task ke hisaab se temperature, Top-p aur repetition penalty jaise parameters chunein।

## Model scores deta hai, jawab nahi

Is vishay se pehla sampark hai to pehle [pehla inference service](https://dmxsf.com/hi/wiki/inference/first-inference-service/) dekhein।

Language model har step par vocabulary ke har token ke liye score vector $z \in \mathbb{R}^{|\mathcal{V}|}$ (logits) deta hai, jo softmax se probability banta hai:

$$
p_i = \frac{\exp(z_i)}{\sum_{j} \exp(z_j)}
$$

**Decoding** ke sawaal: yeh probability diya hai, to agla token kaun sa chunein? Chunne ka tareeka badla to ek hi model ka behaviour poori tarah badal jaata hai: koi stable par dheema, koi zinda-dil par bhatakne wala।

Aage poore page mein ek hi misaal chalegi. Maan lo model ne 4 candidate tokens ko scores diye $z = [4, 3, 1, 0]$, default probability lagbhag $[0.696,\ 0.256,\ 0.035,\ 0.013]$.

## Greedy decoding: hamesha sabse bada chuno

Sabse aasaan tareeka: har step par sabse bade probability wala token:

$$
x_t = \arg\max_i\, p_i
$$

Fayda: deterministic aur fast; standard jawab wale tasks ke liye theek। Nuksan:

- **Diversity ki kami**: ek hi input hamesha ek hi output deta hai।
- **Repeat mein fansna**: local-optimal chunav model ko baar-baar wahi phrase ki taraf le ja sakta hai, "…ka…ka…" jaise loops bante hain।
- **Overall best zaroori nahi**: har step best hona poore sentence ki maximum probability ki guarantee nahi।

## Temperature: distribution ko tez ya samtal banano

**Temperature** $T$ softmax se pehle scores ko scale karti hai:

$$
p_i(T) = \frac{\exp(z_i / T)}{\sum_{j} \exp(z_j / T)}
$$

- $T < 1$: score ka farq badhta hai, distribution tez (peaked), bade probability wale token par hawi, output zyada conservative।
- $T = 1$: original distribution।
- $T > 1$: score ka farq sikud jaata hai, distribution samtal (flatter), chhote probability wale tokens ko mauka, output zyada faila hua।
- $T \to 0$: greedy decoding ki taraf।

Pichhli misaal $z = [4, 3, 1, 0]$ par:

| Temperature | Token 1 | Token 2 | Token 3 | Token 4 |
| --- | --- | --- | --- | --- |
| $T = 0.5$ | 0.879 | 0.119 | 0.002 | 0.000 |
| $T = 1$ | 0.696 | 0.256 | 0.035 | 0.013 |
| $T = 2$ | 0.509 | 0.309 | 0.114 | 0.069 |

Dhyan dein temperature **order nahi badalti**, sirf probabilities ke beech ka farq badalti hai. Yeh "randomness ki matra" regulate karti hai, "kaun sa chunna" nahi।

> [!NOTE] Temperature badalne se creativity badli hi nahi
> Temperature badhne se "interesting chhoti-probability options" aur "bilkul na chale wale chhoti-probability options" dono badhte hain. Temperature jitni zyada, grammar galti, topic se hatana aur factual errors utne zyada likely. Creative tasks mein aam taur par truncation (Top-p) ke saath milkar use hoti hai, akeli temperature nahi badate।

## Top-k: sirf pehle k mein se chuno

Long tail mein hazaron chhoti-probability tokens hote hain; akela har ek matlabi nahi, par unki total probability mass ignore nahi ki ja sakti. Probability ke hisaab se sample karte waqt kabhi-kabhi unmein se ek chun jaata hai aur output mein achanak ajeeb shabd aa jaata hai।

**Top-k** ka tareeka: sirf sabse bade probability wale $k$ tokens rakho, baaki zero karo, dobara normalize karke sample karo।

Misaal mein $k = 2$ lein: token 1 aur token 2 rehte hain, dobara normalize karke $[0.731,\ 0.269,\ 0,\ 0]$ milta hai।

Top-k ki dikkat: $k$ fixed hai. Model bahut sure ho (distribution tez) to $k = 50$ bahut faltu candidates ghusata hai; model bahut unsure ho (distribution samtal) to $k = 50$ sahi options kaat sakta hai।

## Top-p (nucleus sampling): cumulative probability se kaatna

**Top-p**, jise nucleus sampling bhi kehte hain, Holtzman adi ne 2019 ke paper *The Curious Case of Neural Text Degeneration* mein diya. Yeh probability ghatte kram mein sort karta hai, **minimum set rakhta hai jiska cumulative probability p tak pahunch jaaye**, baaki phenk deta hai, phir dobara normalize:

$$
\mathcal{V}_p = \text{sabse chhota set jismein } \sum_{i \in \mathcal{V}_p} p_i \ge p
$$

Is set ka size **adaptive** hai: model bahut sure ho to ek-do token mein hi $p$ lag jaata hai, candidates kam; model unsure ho to $p$ tak pahunchne ke liye zyada tokens chahiye, candidates zyada।

Misaal mein $p = 0.9$ lein: token 1 ke baad cumulative 0.696, token 2 jodne par 0.953, jo 0.9 se paar hai, isliye pehle do rehte hain - result wahi $[0.731,\ 0.269,\ 0,\ 0]$।

Kuch inference frameworks **min-p** bhi dete hain: jinki probability "sabse bade probability ke kisi anupaat" se kam na ho unhe rakhna. Yeh bhi Top-p jaisa adaptive hai, par threshold maximum probability ke relative hai, cumulative probability ke nahi।

## Khud try karein

Neeche wala demo fixed candidate tokens use karta hai ("aaj mausam…" ke agla shabd; probabilities hand-set kiye gaye illustrative values hain). Slider ghisakkar dekhein teen parameters distribution kaise badalte hain, phir "sample" button dabakar bahut saare samples ke baad ki frequencies dekhein।

## Ek poora implementation

Neeche PyTorch ka aam sampling function hai, jismein temperature, Top-k aur Top-p combine hain:

```python
import torch

def sample_next_token(
    logits: torch.Tensor,
    temperature: float = 1.0,
    top_k: int | None = None,
    top_p: float | None = None,
) -> int:
    """logits: [vocab]. Returns the sampled token id."""
    if temperature == 0:  # greedy decoding par utar jaata hai
        return int(logits.argmax())

    probs = torch.softmax(logits / temperature, dim=-1)
    sorted_probs, sorted_ids = probs.sort(descending=True)

    keep = torch.ones_like(sorted_probs, dtype=torch.bool)
    if top_k is not None:
        keep[top_k:] = False
    if top_p is not None:
        cumulative = sorted_probs.cumsum(dim=-1)
        # jinka cumulative probability (current token jodne se pehle)
        # top_p tak pahunch chuka tha, sab hatao (sabse bada token hamesha bachta hai)
        keep &= (cumulative - sorted_probs) < top_p

    filtered = torch.where(keep, sorted_probs, torch.zeros_like(sorted_probs))
    filtered = filtered / filtered.sum()  # dobara normalize
    choice = torch.multinomial(filtered, num_samples=1)
    return int(sorted_ids[choice])
```

Pichhli misaal ke `logits = [4, 3, 1, 0]` par `top_p=0.9` ya `top_k=2` dono candidate distribution $[0.731, 0.269, 0, 0]$ dete hain; `temperature=0.5, top_p=0.9` par $[0.881, 0.119, 0, 0]$ milta hai।

Kuch implementation baatein yaad rakhein:

- Pehle temperature scaling, phir Top-k / Top-p. Order badla to result badal jaata hai।
- Top-p ki truncation condition hai "**current token jodne se pehle** cumulative probability $p$ se chhoti ho", tabhi "minimum set jiska cumulative exactly $p$ tak pahunchta hai" banta hai, aur sabse bade probability wala token kabhi nahi katta।
- Truncation ke baad dobara normalize karna zaroori hai, warna valid probability distribution nahi bachta।

## Beam search: kai candidates ek saath

Greedy decoding har step par ek hi choice rakhta hai. **Beam search** $B$ sabse achhi partial sequences ek saath rakhta hai; har step har sequence ko ek token se badhata hai, aur saare expansions mein se sabse zyada total log-probability wali $B$ chunta hai:

$$
\text{score}(x_{1:t}) = \sum_{s=1}^{t} \log p(x_s \mid x_{<s})
$$

Beam search translation, summarization jaise tasks mein achha chalta hai jahan **output space seemit ho aur reference jawab kafi clear ho**, kyunki yeh "poore sentence ki maximum probability" ke zyada kareeb hai. Score log-probability ka sum hai, isliye lambi sequence ka score kam hota hai - length normalization aksar chahiye hoti hai।

Par open-ended generation (chat, likhai) mein beam search aksar **pheeka, dohraane wala** text deta hai. Holtzman adi ke research ke mutabiq insaan likhte waqt har step ki probability itni zyada hoti hi nahi; poore sentence ki maximum probability ka peecha karne se insaani text ke distribution se hat jaate hain. Isliye chat models zyada tar sampling use karte hain, beam search nahi।

## Repetition penalty aur related parameters

Kuch services generation history par penalty parameters bhi deti hain, repetition rokne ke liye:

| Parameter | Tareeka |
| --- | --- |
| Repetition penalty | Pehle aa chuke token ke score ko scale karna, dobara aane ki sambhavna ghataana |
| Frequency penalty | Token kitni baar aa chuka hai uske hisaab se linear katauti; jitna zyada aaya utna zyada kata |
| Presence penalty | Bas aane par ek fixed score kata, naye topics ki baat karne ke liye |
| Max generation length | Generate hone wale tokens ki ginti seemit, infinite generation se bachav |
| Stop sequences | Diya gaya string aane par turant ruk jaana |

Zyada sakht penalty correctness nuksaan deti hai: code, JSON aur proper nouns mein wahi token dobara aana hi chahiye hota hai।

## Parameters kaise chunein

Neeche aam starting points hain - **final verdict nahi**; apne task ke evaluation se adjust karein:

| Task | Suggested start | Wajah |
| --- | --- | --- |
| Information extraction, classification, structured output | Temperature 0-0.2 | Stability chahiye, jawab taqreeban unique |
| Code generation | Temperature 0-0.3 | Grammar sakht, chhoti galti badh jaati hai |
| Q&A, summarization | Temperature 0.2-0.7 | Accuracy aur naturalness ke beech santulan |
| Chat, likhai | Temperature 0.7-1.0, Top-p 0.9-0.95 | Naturalness aur diversity chahiye |
| Brainstorming, creative | Temperature 0.9+, Top-p ke saath | Failavna chahiye, par long tail kaatni hai |

Ek aur experience: **ek baar mein sirf ek parameter badlein**, aur fixed eval set par kai samples ka average dekhein, kisi ek output ke achhe-bure se faisla na karein।

> [!WARNING] Temperature 0 bhi byte-for-byte guarantee nahi
> Parallel floating-point summation ka order, batching ka combination aise factors greedy decoding wali service mein bhi kabhi-kabhi suksma inconsistency de dete hain. Strict reproducibility chahiye to model version, random seed aur inference config fix karein, aur business mein chhote farq ko sahen karein।

## Decoding aur inference optimization ka rishta

Decoding inference ka aakhri step hai, par poore inference system se gehri tarah juda hai:

- Har token ke liye forward pass dobara hota hai, isliye [KV cache](https://dmxsf.com/hi/wiki/inference/kv-cache/) decoding ki lagat ghataane ke liye sabse zaroori hai।
- [Speculative decoding](https://dmxsf.com/hi/wiki/inference/speculative-decoding/) chhota model se kai tokens ka draft banwata hai, bada model ek saath verify karta hai; rejection sampling se final distribution direct sampling jaisa hi rehta hai (paper: [Fast Inference from Transformers via Speculative Decoding](https://arxiv.org/abs/2202.01310))।
- Output ko strictly JSON ya kisi grammar mein fit karna ho to har step par illegal tokens ko pehle mask karke sample karein; ise constrained decoding kehte hain, dekhein [structured output aur function calling](https://dmxsf.com/hi/wiki/applications/structured-output-and-function-calling/)।
- Service layer par temperature, Top-p, max length aur stop conditions aam taur par per-request parameters hain, dekhein [LLM inference service](https://dmxsf.com/hi/wiki/inference/serving/)।

## Summary aur exercises

**Is page ke mukhya points:**

1. Decoding probability distribution ko concrete token banata hai; greedy deterministic par repeat kar sakta hai, sampling diverse par bhatak sakta hai।
2. Temperature score ka farq scale karti hai, order nahi badalti; Top-k fixed $k$ rakhta hai, Top-p cumulative probability se adaptive kaat-ta hai।
3. Pehle temperature, phir truncation, phir normalization; beam search clear-reference tasks ke liye, open-ended generation ke liye nahi।
4. Parameters task ke evaluation se adjust hon; ek baar mein ek hi।

### Quick self-test

**1. Temperature 1 se 0.5 karne par, baaki sab same, kya hoga?**

- [ ] Sabse bade probability wala token badal jaayega, kyunki order badal jaata hai
- [x] Distribution tez hota hai, sabse bade probability wale token ka hissa badhta hai, order same rehta hai
- [ ] Distribution samtal hota hai, chhote probability wale tokens ko mauka milta hai
- [ ] Sab tokens ki probability girti hai

> Temperature softmax se pehle scores scale karti hai, score ka farq badhta hai, isliye bade probability wala token aur hawi hota hai, par order nahi badalta. Is page ki misaal mein sabse badi probability 0.696 se 0.879 gayi।

**2. Model bahut sure hai - sabse bade token ki probability hi 98%. Ab Top-p = 0.9 aur Top-k = 50, har ek kitne candidates rakhega?**

- [ ] Dono 50
- [ ] Top-p 50, Top-k 1
- [x] Top-p sirf 1, Top-k phir bhi 50
- [ ] Dono sirf 1

> Top-p "minimum set jiska cumulative exactly p tak pahunchta hai" rakhta hai; pehla token hi 0.9 paar karta hai, set sirf 1 ka - candidate count adaptive hai. Top-k ka k fixed hai, 49 faltu candidates phir bhi aa jaate hain।

**3. Kisi step ke scores [4, 3, 1, 0] hain, probability lagbhag [0.696, 0.256, 0.035, 0.013]. Top-p = 0.9 par kitne tokens rehte hain?**

- [ ] 1
- [x] 2
- [ ] 3
- [ ] 4

> Pehle token ke baad cumulative 0.696, jo 0.9 se kam; doosre ke baad 0.953, jo 0.9 se zyada - isliye pehle do rehte hain, dobara normalize karke [0.731, 0.269, 0, 0] banta hai।

**4. Temperature aur Top-p ek saath use karte waqt sahi order kya hai?**

- [ ] Pehle Top-p truncation, phir temperature scaling, aakhir normalization
- [x] Pehle temperature scaling, phir truncation, truncation ke baad dobara normalization, aakhir sampling
- [ ] Pehle sampling, phir temperature se chuna token adjust karna
- [ ] Order se result par farq nahi padta

> Truncation scaled probability par hota hai; order badla to result badalta hai. Truncation ke baad normalize na karo to valid probability distribution nahi bachta।

**5. Chat models zyada tar sampling use karte hain, beam search nahi - kyun?**

- [ ] Kyunki beam search parallel compute nahi ho sakta
- [ ] Kyunki beam search sirf English ke liye hai
- [x] Kyunki open-ended generation mein poore sentence ki maximum probability ka peecha pheeka, dohraane wala text deta hai, jo insaani text ke distribution se hat jaata hai
- [ ] Kyunki beam search ko temperature parameter nahi chahiye

> Beam search translation, summarization jaise limited-output, clear-reference tasks mein achha hai. Holtzman adi ke research ke mutabiq insaani likhai ki har-step probability itni zyada nahi hoti।

**6. Temperature 0 (greedy decoding) se kya byte-for-byte same output ki guarantee hai?**

- [ ] Haan, kyunki greedy deterministic algorithm hai
- [x] Zaroori nahi; parallel floating-point summation ka order, batching ka combination waghera suksma numerical farq de dete hain
- [ ] Kabhi nahi, kyunki model ke andar random numbers hain
- [ ] Bas random seed badal do

> Do paas ke logits suksma numerical farq mein rank badal sakte hain, aur ek token ka farq aage ki generation ko alag mod par le jaata hai. Strict reproducibility chahiye to model version, seed aur inference config fix karein, chhote farq ko sahen karein।

**Exercises:**

1. Haath se: $z = [2, 1, 0]$ par $T = 1$ aur $T = 0.5$ ki probability distribution nikaalein।
2. Upar wale function ko batch version banayein (`logits` shape `[batch, vocab]`), aur `top_p` ki truncation check karne wala unit test likhein।
3. Apne jaane-maane model API par ek hi prompt ko temperature 0, 0.7, 1.2 par 5-5 baar sample karein, output ke farq record karein aur wajah samjhayein।

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

1. $T = 1$ par $\exp(2),\exp(1),\exp(0)$ lagbhag $7.389,\ 2.718,\ 1$, total $11.107$, probability $[0.665,\ 0.245,\ 0.090]$. $T = 0.5$ par scores $[4,\ 2,\ 0]$ hote hain, $\exp$ lagbhag $54.598,\ 7.389,\ 1$, total $62.987$, probability $[0.867,\ 0.117,\ 0.016]$. Temperature ghatne se sabse badi probability 0.665 se 0.867 gayi, order same।

2. Batch version ki kunji: sab operations last dimension (`dim=-1`) par; truncation ke baad `scatter` se probability ko vocabulary ke original order mein wapas rakhein:

   ```python
   import torch

   def filter_probs(logits, temperature=1.0, top_k=None, top_p=None):
       """logits: [batch, vocab]. Returns truncated, renormalized probs."""
       probs = torch.softmax(logits / temperature, dim=-1)
       sorted_probs, sorted_ids = probs.sort(dim=-1, descending=True)
       keep = torch.ones_like(sorted_probs, dtype=torch.bool)
       if top_k is not None:
           keep[:, top_k:] = False
       if top_p is not None:
           cumulative = sorted_probs.cumsum(dim=-1)
           keep &= (cumulative - sorted_probs) < top_p
       filtered = torch.where(keep, sorted_probs, torch.zeros_like(sorted_probs))
       filtered = filtered / filtered.sum(dim=-1, keepdim=True)
       # vocabulary ke original order mein wapas
       return torch.zeros_like(filtered).scatter(-1, sorted_ids, filtered)

   def test_top_p():
       logits = torch.tensor([[4.0, 3.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0]])
       out = filter_probs(logits, top_p=0.9)
       # pehli row: pehle do rakho aur dobara normalize
       expected = torch.tensor([0.7311, 0.2689, 0.0, 0.0])
       assert torch.allclose(out[0], expected, atol=1e-4)
       # doosri row: distribution poora flat; 0.9 tak pahunchne ke liye
       # chautha tak jodna padta hai, sab rehte hain
       assert torch.allclose(out[1], torch.full((4,), 0.25))
       # har row ka sum 1
       assert torch.allclose(out.sum(dim=-1), torch.ones(2))
       # p bahut chhota ho to bhi sabse bada token bach jaata hai
       tiny = filter_probs(logits[:1], top_p=1e-6)
       assert torch.equal(tiny, torch.tensor([[1.0, 0.0, 0.0, 0.0]]))

   test_top_p()
   print("all tests passed")  # output: all tests passed
   ```

   Sampling ke liye `filter_probs` ke result par `torch.multinomial(probs, num_samples=1)` call karein; yeh pehle hi batch support karta hai।

3. Expected observation (exact text model aur prompt par nirbhar; apne records ko final maanein): temperature 0 par 5 outputs lagbhag same, online services mein kabhi-kabhi suksma farq; temperature 0.7 par wording alag shuru hoti hai, par mukhya baatein same; temperature 1.2 par farq sabse zyada - topic se hatna, na-chalne wala text ya factual errors ho sakte hain. Wajah: temperature jitni zyada, chhoti-probability token ko chune ka mauka utna zyada, aur generation token-by-token pichhle text par nirbhar hai - ek step alag hua to aage sab alag mud jaata hai aur farq badhta jaata hai. Record karte waqt 5 outputs mein kitne alag jawab hain yeh ginti lein - trend dekhna text-by-text comparison se aasaan hai।

</details>

## सहायक कोड

[Decoding and sampling: temperature, top-k, top-p, min-p, beam search, penalties](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/decoding-and-sampling): The page's four-token example reproduced exactly (temperature, top-k, top-p, min-p, and why the order matters), whether samples follow the processed distribution, what each knob does to real text, beam search, repetition penalties, and whether batch shape changes greedy output.

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

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

### Temperature 0 aur top_k=1 ek hi baat hai?

Siddhant mein dono greedy decoding ke barabar hain, yaani hamesha sabse bade probability wala token। Alag services temperature=0 ko alag tarah implement karte hain: kuch seedha argmax bana dete hain, kuch use bahut chhota positive number maante hain; reproducible result ke liye aam taur par random seed bhi fix karna aur batching ke floating-point differences se bachna padta hai।

### Top-p aur Top-k saath use ho sakte hain?

Haan, Top-p aur Top-k saath use ho sakte hain. Aam tareeka: pehle Top-k se sabse bade probability wale k tokens rakhein, phir unmein Top-p se kaat lein, aakhir mein dobara normalize karke sample karein. Par bahut saare parameters ek saath badane se behaviour unpredictable ho jaata hai - pehle temperature fix karke sirf ek truncation parameter badlein, aur eval set se validate karein।

### Ek hi prompt par har run ka result alag kyun hai?

Kyunki default decoding probability ke hisaab se random sampling hai; har step par alag token chun sakta hai aur farq generation ke saath badhta jaata hai। Temperature kam karne, greedy decoding ya fixed random seed se farq ghatta hai, par zyada tar online services mein byte-for-byte same ki guarantee nahi।

### Code generation ya information extraction mein temperature kaise set karein?

In tasks ke sahi jawab clear hote hain, isliye aam taur par kam temperature (0 se 0.3) ya greedy decoding use hoti hai, stability ke liye। Diversity chahiye wale tasks jaise brainstorming ya creative writing mein 0.7 se upar ka temperature Top-p ke saath use hota hai। Exact value apne task ke eval results se lein।
