AI Agents & LLMsMedium
What do temperature, top-p and top-k control?
Learning path, stage 1 of 5: How LLMs work · question 5 of 10They control how the next token is sampled from the model's probability distribution. Temperature reshapes the distribution: low is focused and close to deterministic, high is more varied. Top-k keeps only the k most likely tokens. Top-p (nucleus sampling) keeps the smallest set of tokens whose probabilities add up to p.
How each one works
- Temperature T: divide the logits by T before the softmax. When T approaches 0 you get greedy decoding (always the top token). T > 1 flattens the distribution and adds randomness.
- Top-k: cut the candidate list to the k best tokens, then sample.
- Top-p: cut to the "nucleus" that covers probability mass p (for example 0.9). This adapts: it keeps few tokens when the model is confident and more when it isn't.
Practical guidance
- Use low randomness for extraction, classification and code. Use more for brainstorming and creative writing.
- Tune one of them, not all three at once.
- Temperature 0 is not a guarantee of identical output. Batching and floating-point effects on the server can still change results.
- Check your provider. Some newer models, including recent Claude models, don't accept these parameters and expect you to steer through the prompt and settings like reasoning effort instead.
Sources
Code example
tsx
1// How temperature, top-k and top-p pick a token from raw logits.2function sample(logits: number[], { temperature = 1, topK = Infinity, topP = 1 } = {}): number {3 if (temperature === 0) return logits.indexOf(Math.max(...logits)); // greedy45 const scaled = logits.map((l) => l / temperature);6 const max = Math.max(...scaled);7 let probs = scaled.map((l, i) => ({ i, p: Math.exp(l - max) }));8 const z = probs.reduce((s, x) => s + x.p, 0);9 probs = probs.map((x) => ({ ...x, p: x.p / z })).sort((a, b) => b.p - a.p);1011 probs = probs.slice(0, topK); // top-k12 let cum = 0;13 probs = probs.filter((x) => (cum += x.p) - x.p < topP); // top-p nucleus1415 const total = probs.reduce((s, x) => s + x.p, 0);16 let r = Math.random() * total;17 for (const x of probs) if ((r -= x.p) <= 0) return x.i;18 return probs[0].i;19}2021console.log(sample([2.0, 1.0, 0.1], { temperature: 0.7, topP: 0.9 }));
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.