The pipeline behind one token
At each decoding step the model produces a vector of logits, one per vocabulary entry, typically thirty thousand to two hundred thousand numbers. Those logits are not probabilities. They are unbounded scores, and the gap between the top score and the tenth score is what all the sampling parameters operate on.
The standard pipeline is: apply penalties to logits for tokens already present, divide by temperature, optionally keep only the top-k logits, optionally apply top-p, then softmax to get a probability distribution, then draw one sample. Some servers add min-p, typical sampling, or a no-repeat n-gram filter. The order matters, and it is not identical across implementations, which is why the same numbers can behave differently in vLLM, llama.cpp and the OpenAI API.
A greedy decoder skips all of it and takes the argmax. Everything else is a way of spending some randomness in exchange for diversity, and every parameter is a different way of deciding how much randomness and where.
Two other mechanisms sit outside this chain and are worth separating in your head. logit_bias adds a fixed value to specific token ids before sampling, which is deterministic and useful for forcing or forbidding a literal such as a date format. Stop sequences are not sampling at all: they terminate generation when a string appears, and they can cut a valid document in half if the string occurs inside it.
Temperature is a divisor, not a dial for creativity
Temperature divides every logit by T before the softmax. With T below one, differences between logits are amplified, so the leader pulls further ahead and the distribution concentrates. With T above one, differences shrink, the tail gets more mass, and unlikely tokens become reachable. At T equal to one you sample from the model's raw distribution. As T approaches zero the distribution collapses onto the argmax, which is why temperature zero is treated as greedy.
The important property is that temperature is monotonic. Dividing by a positive number preserves the order of the logits, so temperature can never make a token that was ranked twentieth become the most likely one. It only changes how much probability mass the lower ranks keep. If the model does not know an answer, raising the temperature will not find it; it will only make the wrong answers more varied.
A concrete example helps. Suppose the top three tokens have probabilities 0.70, 0.20 and 0.05 at T=1, and the rest of the vocabulary is negligible. At T=0.5 the leader rises to roughly 0.92 and the third token is effectively gone. At T=1.5 the leader drops to roughly 0.62 and the third rises to about 0.11. The ranking is unchanged in all three cases; the shape of the distribution is not.
You can think of temperature as controlling the effective size of the vocabulary the model is choosing from. At low temperature only a handful of tokens have meaningful mass; at high temperature hundreds do. That is why low temperature produces the same answer phrased the same way, and why high temperature produces the same idea phrased differently, or a different idea entirely.
Typical defaults exist because they work across many tasks: 0.7 for chat, 0.2 to 0.4 for code, 0.0 for extraction and classification, 0.9 to 1.1 for brainstorming. Treat them as starting points, not laws. A model with a sharper distribution, or a task with a narrower answer space, shifts the useful range.
Top-p, top-k and the shape of the tail
Top-p, or nucleus sampling, sorts the tokens by probability, keeps the smallest set whose cumulative probability reaches p, discards the rest, and renormalises. With p equal to 0.9, the model samples only from the tokens that together account for ninety per cent of the mass. The size of that set is not fixed: it might be three tokens when the model is confident and three hundred when it is not.
That adaptivity is the point. Top-k keeps a fixed number of candidates, so k equal to fifty is far too permissive when the model is certain and far too restrictive when it is confused. Top-p adjusts to the shape of the distribution, which is why it is the better default and why most providers expose it alongside temperature.
The two interact in a way that trips people up. Temperature is applied first, so it changes the distribution that top-p then truncates. Setting temperature to 1.5 with top-p 0.9 gives you a flattened distribution truncated at ninety per cent, which is often more coherent than temperature 1.5 alone, because the long tail is cut off. Setting temperature to 0.3 with top-p 0.9 gives you a sharp distribution whose nucleus may be a single token, making top-p irrelevant.
Top-k still has a use: as a hard floor against pathological tokens. A common recipe is top_k 40 to 50 combined with top_p 0.95. min-p is a newer alternative that keeps tokens with probability at least a fraction of the top token's probability, and it tends to hold up better at high temperatures than top-p because it scales with confidence.
One practical warning: top-p equal to 1.0 disables truncation entirely. That is the correct setting for greedy extraction and a bad setting for creative work at high temperature, because you are sampling from the full tail including tokens the model considers absurd.
Repetition penalty, presence penalty, frequency penalty
Repetition penalties attack a real failure: models loop, repeating a phrase or a sentence structure until the token limit. The fix is to reduce the logit of tokens that have already appeared.
The classic implementation, from the CTRL paper, is multiplicative and asymmetric. If a token's logit is positive, divide it by the penalty; if it is negative, multiply it by the penalty. Dividing a positive logit makes it smaller, and multiplying a negative one makes it more negative, so both cases push the token down. A penalty of 1.0 is a no-op, 1.1 is mild, 1.3 is aggressive.
OpenAI-style APIs split this into two additive penalties. Presence penalty subtracts a fixed amount from any token that has appeared at least once, which pushes the model toward new topics. Frequency penalty subtracts an amount proportional to how many times the token has appeared, which pushes toward new words. Both are in the range of roughly -2 to 2, and both apply to the whole context including the prompt.
That last detail is the source of most of the damage. A repetition penalty does not know which tokens are structural. In a JSON response it penalises the opening brace, the quotes, the commas and the key names, all of which must repeat. In code it penalises indentation, closing braces, semicolons and the variable names the program is about. In a quotation task it penalises the name of the person being quoted. The model, forbidden from repeating the token it needs, finds a synonym, changes the key name, or drops the closing brace.
If you must use a penalty, keep it small: 1.05 to 1.15 for repetition penalty, or a presence penalty of 0.1 to 0.3. Never use one on a structured-output task. Constrained decoding and repetition penalties actively fight each other, because the grammar says a brace is the only legal token and the penalty says the brace is forbidden, and the mask wins by forcing a very low-probability choice.
A better fix for looping is usually the prompt or the context, not the sampler. Loops come from repetitive input, from a model that has lost the thread, or from a max_tokens budget longer than the content needs. Truncating the context and restating the task works more reliably than punishing the vocabulary.
Settings by task
These are starting points that assume a modern instruct model and a clean prompt. Move them by small increments and measure on your own evaluation set, because the right value depends on the model's calibration as much as on the task.
- Classification and extraction: temperature 0, top_p 1.0, no penalties, and a schema constraint if the server supports one.
- JSON and tool calls: temperature 0 to 0.2, top_p 1.0, repetition penalty 1.0. Structured output plus any penalty is a bug waiting to happen.
- Code generation: temperature 0.2 to 0.4, top_p 0.95, top_k 40, no frequency penalty. Code needs exact identifiers repeated.
- Code explanation and review: temperature 0.3 to 0.5, top_p 0.95.
- Chat and summarisation: temperature 0.6 to 0.8, top_p 0.9 to 0.95.
- Brainstorming and naming: temperature 0.9 to 1.1, top_p 0.95, top_k 0, and a presence penalty around 0.2 to force variety.
- Long-form drafting: temperature 0.7 to 0.9, top_p 0.95, and a small frequency penalty around 0.1 to reduce phrase loops without breaking names.
- Agentic loops with tool calls: temperature 0 to 0.3. Predictability beats variety when the next step executes a command.
Reasoning models are a special case
Models trained for long chain-of-thought often publish their own recommended sampler settings, and those settings frequently sit in the middle of the range rather than at zero. A model that was trained with a particular temperature during reinforcement learning expects a similar distribution at inference; running it greedily can push it into repetitive loops, because the most likely token after a long reasoning trace is sometimes the one that restarts the trace.
Read the model card before applying your house defaults. Several reasoning models recommend something like temperature 0.6 with top_p 0.95, and some explicitly advise against greedy decoding for that reason. The recommendation is not arbitrary: it reflects the sampling regime used during training and evaluation.
This is also why benchmark numbers are not comparable across sampler settings. A model evaluated at temperature 0.6 with five samples and majority voting is being measured differently from one evaluated greedily, and the gap can be several points on a reasoning benchmark. When you compare two models, match the sampler or accept that you are measuring the configuration as much as the weights.
Determinism, seeds and why temperature zero still varies
Temperature zero means argmax, and argmax is deterministic in exact arithmetic. Production inference is not exact arithmetic. Floating-point reductions happen in an order that depends on batch composition, kernel selection and GPU architecture. Continuous batching means your request shares a forward pass with a different set of neighbours on every call, and the resulting logits can differ in the last few decimal places. When two top logits are nearly tied, that difference flips the winner.
Setting a seed fixes the pseudo-random number generator used for sampling. It does not fix the logits. Two runs with the same seed and the same prompt can diverge if the batching differs, and they will almost certainly diverge across different hardware or different inference engine versions.
If you need reproducible outputs for a test suite, do not rely on the sampler. Compare against a rubric or a normalised structure, or run the model behind a cache keyed by the exact prompt and parameters. Record the model revision, the engine version and the sampler settings alongside any result you intend to cite.
There is also the multi-token subtlety: temperature is applied independently at each step, so a slightly different early token changes the entire context for every later step. Small sampling differences compound. This is why an evaluation run at temperature 0.7 with one seed is not reproducible in the way a unit test is, and why evaluation harnesses usually report averages over several samples.
Mistakes that cost the most
Most sampling problems are configuration problems with a clear signature.
- Using a repetition penalty on JSON, code or extraction. The symptom is missing closing braces, renamed keys and paraphrased quotes.
- Setting temperature above 1.0 and leaving top_p at 1.0. The model samples from the full tail, including tokens it rates as absurd.
- Setting both temperature and top_p very low, then wondering why outputs are identical. Two truncations compound; one is usually enough.
- Assuming temperature zero is reproducible across servers. It is not, for the batching reasons above.
- Tuning temperature to fix a prompt problem. If the model has the wrong instructions, a lower temperature only makes it consistently wrong.
- Copying a provider's defaults into a self-hosted stack. Defaults differ: some servers default to temperature 0.6, others to 1.0, and llama.cpp's default sampler chain is not the same as vLLM's.
- Changing several parameters at once. Change one, run the eval, keep or revert, then move to the next.
Diagnosing from the symptom
Sampler problems have recognisable signatures, and matching the symptom to the parameter saves a lot of blind tuning.
- Verbatim loops, the same sentence three times: repetition penalty too low, context too long, or a prompt that invites a list without saying when to stop.
- Loops that survive a penalty increase, with words swapped for odd synonyms: the penalty is too high and the model is being forced off the token it needs.
- Coherent but dull, near-identical outputs across calls: temperature too low, or top_p truncating to one candidate.
- Grammar intact, facts drifting: temperature too high. Lower it before adding more instructions.
- Word salad, missing function words, broken syntax: temperature well above 1.0 with no truncation, or a top_k that is far too large for a small model.
- JSON that parses but has renamed keys: a repetition penalty or frequency penalty is active. Turn it off.
- Output that stops mid-sentence: max_tokens, not sampling. Check the finish reason before touching temperature.
- Different answers from identical requests at temperature zero: batching non-determinism. Fix the evaluation method, not the sampler.