LLMs & GenAI

Temperature, Top-p & Sampling

Controlling randomness, creativity, and determinism in LLM text generation via decoding hyperparameters.

🟢 beginner5 min readinference
Decoding hyperparameters govern how raw model logits z are transformed and sampled during autoregressive text generation. Temperature T rescales logit differences z/T before Softmax, controlling distribution entropy (T → 0 is greedy deterministic; T > 1 is creative/diverse). Top-k sampling restricts sampling to the k highest-probability tokens. Top-p (Nucleus) sampling dynamically samples from the smallest set of tokens whose cumulative probability exceeds p.

The Logit-to-Token Pipeline

Raw Un-normalized Logits z [|V|]
            │
            ▼
   [ TEMPERATURE SCALING ]   ──► z_scaled = z / T
            │
            ▼
    [ SOFTMAX ACTIVATION ]   ──► P_i = exp(z_i / T) / ∑ exp(z_j / T)
            │
            ▼
  [ TOP-K / TOP-P FILTERING ]──► Zero out low-probability tails
            │
            ▼
    [ STOCHASTIC SAMPLING ]  ──► Sample token x_t ~ Filtered_P

1. Temperature ($T$)

Rescales logits prior to Softmax:

$$P(x_i \mid z, T) = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}$$

2. Top-$k$ Sampling

Restricts sampling pool strictly to the top $k$ highest-probability tokens (e.g., $k = 40$).

Drawback: Fixed $k$ is rigid. If top token has $P = 0.99$, Top-$40$ still includes 39 low-quality noise tokens. If top token has $P = 0.05$, Top-$40$ truncates valid continuations.

3. Top-$p$ (Nucleus) Sampling (Holtzman et al., 2019)

Dynamically selects the smallest set of tokens $V^{(p)}$ whose cumulative probability mass reaches $p$ (e.g., $p = 0.90$):

$$\sum_{x \in V^{(p)}} P(x \mid x_{<t}) \ge p$$

Confident State ("Capital of France is...")    Uncertain State ("The story begins in...")
  Top 1 Token ('Paris') = 92%                   Token 1 = 15%, Token 2 = 12%, Token 3 = 10%...
  Pool Size = 1 Token!                          Pool Size = 25 Tokens! (Expanded dynamically)

Recommended Preset Settings

Task TypeTemperature ($T$)Top-$p$Notes
Code / SQL Generation0.01.0Maximum determinism and precision
Factual QA / RAG0.0 – 0.20.9Prevents hallucinations
Conversational Chat0.70.9Good balance of natural flow and coherence
Creative Writing0.9 – 1.10.95Maximizes vocabulary variety

Say this out loud

"Temperature scales logits z/T before Softmax: T=0 gives deterministic argmax outputs for code and math, while higher T increases distribution entropy for creative text. Top-k filters a fixed number of tokens; Top-p (Nucleus) dynamically samples from the smallest pool of tokens reaching cumulative probability p, adapting dynamically when the model is confident vs uncertain."

Follow-ups to expect

Check yourself

Question 1 of 3

What happens to LLM text generation when Temperature T is set to 0.0 (Greedy Decoding)?

More in LLMs & GenAI

See all →
Pretraining → SFT → RLHF5 minFine-Tune vs RAG vs Prompt: Choosing5 minRetrieval-Augmented Generation5 min