---
title: Temperature, top-k and top-p (nucleus) sampling distribution
url: https://gurkanozkan.ai/learn/coding/mle-temperature-top-k-and-top-p-nucleus-sampling-distribution-15/
markdown: https://gurkanozkan.ai/learn/coding/mle-temperature-top-k-and-top-p-nucleus-sampling-distribution-15.md
kind: coding
difficulty: Medium
topics:
  - LLM
  - Decoding
  - Sampling
json: https://gurkanozkan.ai/api/learn/coding/mle-temperature-top-k-and-top-p-nucleus-sampling-distribution-15.json
robots: noindex
---

# Temperature, top-k and top-p (nucleus) sampling distribution

Return the distribution you would sample the next token from: 1. `p = softmax(logits / temperature)`. 2. Rank tokens by p descending, with ties broken by lower index. 3. If `top_k` is set, keep only the first `top_k` tokens. 4. If `top_p` is set, renormalise over the kept tokens, then keep the shortest ranked prefix whose cumulative probability ≥ `top_p`. 5. Return a full-length list: zeros for dropped tokens, renormalised to sum to 1.

## Signature

```python
def sampling_distribution(logits: list[float], temperature: float = 1.0, top_k: int | None = None, top_p: float | None = None) -> list[float]: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(sampling_distribution([0.0, 0.0, 0.0, 0.0]), [0.25, 0.25, 0.25, 0.25])
True

>>> close(sampling_distribution([2.0, 1.0, 0.0], top_k=1), [1.0, 0.0, 0.0])
True
```

## Hints

1. Compute the softmax over the logits first.
2. Temperature scaling: p_i proportional to exp(z_i / T); top-k keeps the k largest probabilities (ties -> lower index), top-p walks the descending cumsum.
3. Renormalise after zeroing; check the reference for exact tie-breaking.

## Reference solution

```python
import numpy as np

def sampling_distribution(logits, temperature=1.0, top_k=None, top_p=None):
    z = np.asarray(logits, float) / temperature
    z = z - z.max()
    p = np.exp(z); p = p / p.sum()
    order = sorted(range(len(p)), key=lambda i: (-p[i], i))
    keep = set(order)
    if top_k is not None:
        keep = set(order[:top_k])
        order = order[:top_k]
    if top_p is not None:
        q = np.array([p[i] for i in order]); q = q / q.sum()
        c = 0.0; kept = []
        for i, qi in zip(order, q):
            kept.append(i); c += qi
            if c >= top_p - 1e-12:
                break
        keep = set(kept)
    out = np.array([p[i] if i in keep else 0.0 for i in range(len(p))])
    return (out / out.sum()).tolist()
```

## What a strong solution covers

- Stable softmax.
- Correct order of operations (top-k, then nucleus on the renormalised set).
- Inclusive cumulative threshold.
- Deterministic tie order.
- Discusses temperature → 0 (greedy) and why top-p adapts to entropy.

## Common mistakes

- applying top-p on the original rather than the top-k-renormalised probabilities
- excluding the token that crosses the threshold.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
