Lesson 6.2 · 2 of 5 · 4 min read · Reviewed 24 Nov 2026
Top-p and top-k
By the end, you can
- Explain top-p and top-k sampling.
- Know when to adjust them.
Top-k
Keep the k most likely tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id.; renormalise; sample.
k = 3: " sunny" 0.45, " cloudy" 0.30, " lovely" 0.15 (rest removed)
Top-p (nucleus sampling)
Sort tokens by probability; keep adding until the total reaches p; sample from that set.
p = 0.9: " sunny" 0.45 + " cloudy" 0.30 + " lovely" 0.15 = 0.90 -> keep these
When the model is confident, the set is small; when it’s unsure, the set grows. That adaptiveness is why top-pTop-p: Nucleus sampling: pick the next token only from the smallest set whose probabilities add up to p. is popular.
Using them with Claude
Many model APIs and open-weight runtimes expose top_p and top_k, usually as advanced settings you change one at a time. Older Claude models accepted them too. Current Claude models don’t support samplingSampling: Choosing the next token from the model’s probability distribution, rather than always taking the most likely one. settings (temperature, top_p, top_k): depending on model and API version they’re rejected or ignored. Remove them, and on Claude shape output with the prompt, examples and structured outputsStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types. instead.
When you might use them
- Cutting rare, off-the-wall tokens in creative generation while keeping variety
- Experiments where you want precise control of the candidate set
For everyday work, leave them at defaults and tune prompts and examples instead. That is the only option on current Claude models.
Key points
- Top-k keeps only the k most likely tokens before sampling; top-p keeps the smallest set whose probabilities add up to p.
- Both cut off the long tail of unlikely tokens.
- Where these settings exist, change one at a time. Current Claude models don't accept sampling settings at all.
Implement top-k and top-p filters
Write both tail-cutting filters and see that top-p adapts to how confident the model is while top-k does not.
You will have: Two filter functions and a table of how many tokens each keeps for a confident and an unsure distribution.
Steps
- Run the starter: both filters keep every token.
- Fill in top_k(): keep the k most likely tokens and renormalise.
- Fill in top_p(): sort by probability, keep adding until the total reaches p, renormalise.
- Run both on the unsure and the confident distribution with k = 3 and p = 0.9.
- Explain why top-p keeps fewer tokens for the confident prompt.
Done when
- top_k keeps 3 tokens for both prompts.
- top_p keeps 3 tokens for the unsure prompt and 1 for the confident one.
- Kept probabilities add up to 1.00.
Open in the Playground No API key needed.
Starter code (Python)
UNSURE = {" sunny": 0.45, " cloudy": 0.30, " lovely": 0.15, " warm": 0.05, " grey": 0.04, " purple": 0.01}
CONFIDENT = {" Paris": 0.91, " a": 0.03, " the": 0.02, " located": 0.02, " Lyon": 0.01, " home": 0.01}
def renorm(d):
s = sum(d.values())
return {k: v / s for k, v in d.items()}
def top_k(probs, k):
return probs # TODO: keep the k largest, then renorm
def top_p(probs, p):
return probs # TODO: keep the smallest top set whose total reaches p, then renorm
for name, dist in [("unsure", UNSURE), ("confident", CONFIDENT)]:
a, b = top_k(dist, 3), top_p(dist, 0.9)
print(f"{name}: top_k keeps {len(a)}, top_p keeps {len(b)}")
Show a solution
UNSURE = {" sunny": 0.45, " cloudy": 0.30, " lovely": 0.15, " warm": 0.05, " grey": 0.04, " purple": 0.01}
CONFIDENT = {" Paris": 0.91, " a": 0.03, " the": 0.02, " located": 0.02, " Lyon": 0.01, " home": 0.01}
def renorm(d):
s = sum(d.values())
return {k: v / s for k, v in d.items()}
def top_k(probs, k):
best = sorted(probs, key=lambda t: -probs[t])[:k]
return renorm({t: probs[t] for t in best})
def top_p(probs, p):
kept, total = {}, 0.0
for t in sorted(probs, key=lambda t: -probs[t]):
kept[t] = probs[t]
total += probs[t]
if total >= p - 1e-9:
break
return renorm(kept)
for name, dist in [("unsure", UNSURE), ("confident", CONFIDENT)]:
a, b = top_k(dist, 3), top_p(dist, 0.9)
print(f"{name}: top_k keeps {len(a)}, top_p keeps {len(b)} {list(b)} total={sum(b.values()):.2f}")