Search Tutorials
--Ads--LLM Inference, Temperature and Sampling
How LLMs generate text step by step, and how temperature, top-p, top-k and effort settings affect RAG answers.
Inference is the process of running a trained model to produce output. For a language model, that means generating text one token at a time, and at each step a decoding strategy decides which token to pick. Settings such as temperature, top-p and top-k control that choice. This lesson explains how they work, what they mean for RAG, and how newer models replace them with settings such as effort.
What you will learn
- How a model generates text step by step
- What temperature, top-p and top-k do
- Which settings suit RAG answers
- Other inference settings: maximum tokens, stop sequences, effort and reasoning
Prerequisites
Generation, step by step
- The model reads the prompt and everything generated so far.
- It outputs a score (logit) for every token in its vocabulary.
- The scores are turned into probabilities with the softmax function.
- A decoding strategy picks one token.
- The token is appended, and the loop repeats until a stop condition: an end-of-text token, a stop sequence, or the maximum number of output tokens.
Decoding strategies in code
This simulation uses made-up scores for five candidate next tokens to show what each setting does:
import numpy as np
tokens = ["Paris", "Lyon", "France", "the", "beautiful"]
logits = np.array([6.0, 3.0, 2.5, 2.0, 1.0]) # raw model scores (made up)
def probabilities(logits, temperature=1.0):
z = logits / max(temperature, 1e-6)
p = np.exp(z - z.max())
return p / p.sum()
for t in (0.2, 1.0, 2.0):
print(f"temperature {t}: ", dict(zip(tokens, probabilities(logits, t).round(3))))
def top_k(p, k):
keep = np.argsort(-p)[:k]
out = np.zeros_like(p); out[keep] = p[keep]
return out / out.sum()
def top_p(p, threshold):
order = np.argsort(-p)
cumulative = np.cumsum(p[order])
keep = order[: np.searchsorted(cumulative, threshold) + 1] # smallest set reaching the threshold
out = np.zeros_like(p); out[keep] = p[keep]
return out / out.sum()
p = probabilities(logits, 1.0)
print("top-k=2 :", dict(zip(tokens, top_k(p, 2).round(3))))
print("top-p=0.9:", dict(zip(tokens, top_p(p, 0.9).round(3))))
temperature 0.2: {'Paris': 1.0, 'Lyon': 0.0, 'France': 0.0, 'the': 0.0, 'beautiful': 0.0}
temperature 1.0: {'Paris': 0.909, 'Lyon': 0.045, 'France': 0.027, 'the': 0.017, 'beautiful': 0.006}
temperature 2.0: {'Paris': 0.629, 'Lyon': 0.14, 'France': 0.109, 'the': 0.085, 'beautiful': 0.031}
top-k=2 : {'Paris': 0.952, 'Lyon': 0.048, 'France': 0.0, 'the': 0.0, 'beautiful': 0.0}
top-p=0.9: {'Paris': 1.0, 'Lyon': 0.0, 'France': 0.0, 'the': 0.0, 'beautiful': 0.0}
| Setting | What it does | Effect |
|---|---|---|
| Greedy decoding | Always pick the most likely token | Deterministic, can be repetitive |
| Temperature | Divides the scores before softmax | Below 1: sharper, more predictable; above 1: flatter, more varied |
| Top-k | Sample only from the k most likely tokens | Removes the unlikely tail |
| Top-p (nucleus) | Sample from the smallest set whose probabilities add up to p | Adapts to how confident the model is |
What to use for RAG
- RAG answers should be faithful and consistent, so where sampling settings are available, use a low temperature (for example 0 to 0.3) and leave top-p and top-k at their defaults.
- Use higher temperatures only for creative tasks, such as generating varied synthetic test questions.
- Low temperature does not prevent hallucination: a model can be consistently wrong. Grounding, citations and verification matter far more (LLM Hallucinations).
Providers differ
Each API exposes different controls, so check the documentation for the model you use:
- Open-weight models (Ollama, vLLM, Hugging Face transformers) usually expose temperature, top-p, top-k, repetition penalties and seeds. With Ollama:
ollama.chat(model=..., messages=..., options={"temperature": 0.2}). - Hosted APIs vary. Some reasoning-oriented models restrict or ignore sampling parameters. Current Claude models do not accept
temperature,top_portop_k; you steer them with the prompt and theeffortsetting instead.
Other inference settings
| Setting | Purpose in RAG |
|---|---|
| Maximum output tokens | Caps answer length and cost; check whether the answer was cut off (stop reason) |
| Stop sequences | End generation at a marker, for example after a closing tag |
| Effort / reasoning settings | How much the model thinks before answering: low for simple lookups, higher for multi-step reasoning |
| Seed | Some providers offer best-effort reproducibility for testing |
| Streaming | Returns tokens as they are generated (Streaming) |
import anthropic
client = anthropic.Anthropic()
msg = client.messages.create(
model="claude-opus-5-5",
max_tokens=800, # cap answer length
output_config={"effort": "low"}, # quick, inexpensive answer
messages=[{"role": "user", "content": "In one sentence: what is top-p sampling?"}],
)
print(msg.stop_reason, msg.content[0].text)
Inference speed and cost
- Input tokens are processed in parallel and are relatively fast; output tokens are generated one at a time, so long answers dominate latency.
- Thinking or reasoning tokens also take time and are billed; choose the lowest effort that gives good answers.
- Self-hosted inference servers speed things up with batching and caching (vLLM, LM Studio and NVIDIA NIM).
Key takeaways
- Models generate one token at a time; decoding settings choose each token.
- Temperature sharpens or flattens the probabilities; top-k and top-p cut off unlikely tokens.
- For RAG, prefer low randomness where available, but rely on grounding to prevent hallucination.
- APIs differ: some modern models replace sampling parameters with effort or reasoning settings.
Frequently asked questions
Does temperature 0 make outputs identical every time?
Often nearly, but not guaranteed: hardware and batching differences can still cause small variations.
Should I set both top-p and temperature?
Usually adjust one of them, not both, and test the effect on your own questions.
Practice exercises
- With a local Ollama model, ask the same question five times at temperature 0 and at 1.0, and compare the answers.
- Extend the demo to sample 1,000 tokens at each temperature and count how often each token appears.