Sampling Strategies: Temperature, Top-k, and Top-p

Temperature alone is powerful but has limitations. That’s why almost every production LLM (including Grok) combines it with Top-k or Top-p (nucleus) sampling.

This document explains the “why” and “how” behind these techniques, using the same spirit as the prototype: make the invisible mechanics visible and understandable.


The Problem with Temperature Alone

Even with a well-chosen temperature, the model can still:

Top-k and Top-p solve this by restricting the set of tokens the model is allowed to sample from at each step.

They act as a filter after temperature has shaped the distribution.


1. Top-k Sampling (Simple but Rigid)

How it works

  1. The model calculates probabilities for all tokens in the vocabulary.
  2. It keeps only the k most probable tokens.
  3. It renormalizes the probabilities of those k tokens so they sum to 1.
  4. It samples from this smaller, high-quality set.

Example (simplified)

Suppose after the context "Elara listened in wonder", the model’s top probabilities look like this:

TokenProbabilityRank
.41%1
,23%2
From18%3
and7%4
she4%5
the2%6
machinee0.8%7

Pros

Cons

This rigidity is why Top-p (nucleus sampling) was invented.


2. Top-p Sampling (Nucleus Sampling) — Usually Better

How it works

Instead of taking a fixed number of tokens (k), we take the smallest set of tokens whose cumulative probability is at least p.

This dynamic set is called the nucleus.

Example (same probabilities, p = 0.9)

TokenProbCumulative
.41%41%
,23%64%
From18%82%
and7%89%
she4%93%

This is dynamic — it automatically adapts to how confident (or uncertain) the model is at each generation step.

Common values used in practice


Temperature + Top-p (The Winning Combination)

Most APIs let you use both together. The typical order of operations is:

  1. Apply temperature to the logits (logits = logits / temperature)
  2. Convert to probabilities with softmax
  3. Apply top-p (or top-k) filtering on those probabilities
  4. Renormalize the filtered probabilities and sample

This gives you two independent, intuitive controls:

ControlEffectAnalogy
TemperatureHow sharp or flat the distribution isHow “creative” vs “safe”
Top-pHow wide the allowed set of tokens isHow much “exploration room”

Visual Intuition

Low Temp + Low Top-p     → Very safe, almost deterministic
Low Temp + High Top-p    → Safe but allows some exploration
High Temp + Low Top-p    → Creative but still constrained (weirdness limited)
High Temp + High Top-p   → Maximum creativity + chaos

Real-World Defaults (Approximate)

Model / APITypical TemperatureTypical Top-p
Grok / xAI0.7 – 1.00.9
GPT-4o0.70.9
Claude 3.50.7— (uses different internal method)
Creative writing1.0 – 1.20.95
Coding / structured0.2 – 0.40.8

Note: Some models (notably Claude) achieve similar effects through different techniques and may not expose top_p directly.


How This Prototype Currently Samples

Look at generate_text in simple_llm_prototype.py:

next_logits = logits[0, -1, :] / max(temperature, 1e-6)
probs = torch.softmax(next_logits, dim=-1)
next_id = torch.multinomial(probs, num_samples=1).item()

Currently it only uses temperature. Adding top-k or top-p would go between the softmax and the torch.multinomial call:

  1. Compute probs as above.
  2. Filter to the nucleus (top-p) or top-k tokens.
  3. Renormalize the filtered probabilities.
  4. Sample with torch.multinomial on the filtered set.

The --show-probs flag already uses torch.topk internally to display the model’s beliefs — the same primitive used in top-k sampling.


Experiments Worth Trying

Once top-p / top-k are added to the prototype (or if you implement them yourself):


For even more control, production systems often add:

These are usually combined with temperature + top-p.


Summary

Understanding these three knobs (and their interactions) removes a lot of the mystery around why models sometimes feel “inspired” and sometimes feel “drunk.”


This is document “2” in the sampling series for the prototype. The core generation loop remains the same: predict, filter, sample, append, repeat.

Reflect on why a tiny model makes these problems extremely visible