AIForum.

How Temperature, Top-p, and Top-k Shape LLM Output

On this page

THE SHORT ANSWER

Temperature reshapes the probability distribution a language model produces for its next token, while top-k and top-p truncate that distribution into a shortlist before sampling. Understanding the difference explains why the same prompt produces stable output at one setting and wildly varied output at another. This guide covers the mechanics, how the parameters interact, and how to test them without drawing the wrong conclusion.
Quick facts

Temperature, top-p, and top-k are sampling parameters. They do not change what a language model knows or how it was trained; they change how the model chooses each next token from the probability distribution it produces at inference time. Temperature reshapes that distribution so unlikely tokens become more or less likely to be picked. Top-k and top-p cut the distribution down to a shortlist before a token is drawn. If you run local models in llama.cpp, Ollama, or LM Studio, or send requests to a hosted API, these are usually the first three knobs you touch, and the ones most often adjusted without a clear idea of what changed.

This guide covers the mechanics of each parameter, how they interact, and how to test them without drawing the wrong conclusion. It assumes you know roughly what a token is and that you have seen a sampling settings panel or an API request body.

What the model produces before sampling begins

A large language model operates on sequences of tokens: words, letters, or sub-word units. Given an input sequence, it predicts the next token by producing a discrete probability distribution over its entire vocabulary, using the softmax function as the final layer of the network. That raw distribution is what sampling parameters act on.

The vocabulary is large, but the shape of the problem is easy to see with a toy example. A five-token vocabulary might produce a distribution like this:

t0 -> 0.40
t1 -> 0.20
t2 -> 0.20
t3 -> 0.15
t4 -> 0.05

The values sum to 1, as a probability distribution must. This example is illustrative and comes from a published explanation of token selection strategies; real vocabularies are far larger. For GPT-style tokenizers, 100 tokens is on average about 75 words.

Everything that follows is a rule for turning that distribution into a single chosen token. None of these rules adds knowledge the model does not have, and none removes knowledge it does. They only change which candidates survive and how often each is selected.

Temperature: reshaping the distribution

According to Amazon Bedrock’s inference parameter documentation, temperature affects the shape of the probability distribution for the predicted output and influences the likelihood of the model selecting lower-probability outputs. In technical terms, the temperature modulates the probability mass function for the next token: a lower temperature steepens the function and leads to more deterministic responses, while a higher temperature flattens it and leads to more random responses. Choosing a lower value influences the model toward higher-probability outputs; choosing a higher value influences it toward lower-probability outputs.

Two properties of temperature are worth internalizing:

  • It does not truncate. Every token in the vocabulary keeps a nonzero probability, however small. Temperature changes the odds; it does not create a cutoff.
  • It is applied to the whole distribution at once. Raising temperature makes tail tokens more competitive and head tokens less dominant. Lowering it concentrates probability on the top candidate.

At temperature 0, or the lowest value a runtime accepts, the distribution collapses toward the single highest-probability token. This is greedy decoding: always take the top candidate. It is the closest thing to a deterministic mode that sampling offers, though as noted below it is not an absolute guarantee of identical output across runs.

Top-k: a fixed-size shortlist

Top-k sets the number of most-likely candidates the model considers for the next token. A lower value means fewer candidate tokens are considered, regardless of how the probability is distributed across them.

The procedure is mechanical: order the tokens in descending order of probability, keep the first k, renormalize so the kept probabilities sum to 1 again, and sample from that reduced set. In the toy distribution above, a top-3 strategy keeps the 0.40, 0.20, and 0.20 tokens. Those three sum to 0.80, so each is divided by 0.80, producing a new distribution of 0.50, 0.25, and 0.25.

Because k is a fixed number, top-k behaves identically whether the model is confident or uncertain. When the top token already holds 0.95 of the probability mass, a top-k of 40 still admits 39 unlikely tokens into the pool. When the distribution is nearly flat, a small k can discard reasonable alternatives. That rigidity is the main reason top-p exists.

Top-p: a shortlist sized by probability mass

Top-p, also called nucleus sampling, sorts tokens in descending probability and keeps the smallest set whose cumulative probability reaches p. The kept tokens are then renormalized and sampled from. With p = 0.9, the shortlist contains however many tokens are needed to cover 90 percent of the probability mass.

The practical consequence is adaptivity. When the model is confident, the nucleus is small, sometimes one or two tokens. When the model is genuinely uncertain, the nucleus grows and admits more alternatives. Instead of asking how many candidates to allow, top-p asks how much of the probability mass to allow.

In the toy example, top-p = 0.80 keeps the same three tokens as top-3, because their cumulative probability is exactly 0.80. Top-p = 0.90 would need the fourth token, since the first three only reach 0.80 and the fourth brings the cumulative total to 0.95. The same cutoff rule produces different shortlist sizes on different distributions.

How the three settings interact

In most implementations the pipeline runs in a consistent order: temperature reshapes the distribution first, then truncation filters such as top-k and top-p remove candidates, then the surviving probabilities are renormalized and a token is sampled. The exact order and the exact interaction rules vary between runtimes, and some runtimes disable top-k when top-p is active or treat a top-k value of 0 as off. Default values and accepted ranges also depend on the model, as the Bedrock documentation notes. For any specific runtime, its own documentation is the authority on ordering and defaults.

The practical implication is that changing two parameters at once usually produces a result you cannot attribute to either one. If you lower temperature and tighten top-p in the same step, you will not know which change caused the difference in output.

Starting points by task

The table below offers starting points, not universal defaults. Documented defaults and ranges vary by model, so treat these as a place to begin a sweep rather than a specification.

TaskSuggested starting pointReasoning
Structured extraction, classification, JSON outputTemperature at or near 0; top-p permissive or disabledYou want the highest-probability continuation, not variety.
Code generation and refactoringLow temperature; keep top-p permissiveSyntax and API names reward the most likely tokens, but some flexibility helps with naming and structure.
Technical explanation, retrieval-grounded answersModerate-low temperatureReduces drift while keeping phrasing natural.
Brainstorming, marketing drafts, creative writingHigher temperature with top-p around 0.9You want the tail tokens to have a real chance.
Generating several distinct variantsHigher temperature, or vary the seedVariety comes from sampling, not from the prompt alone.

If you are unsure where to start, begin with the model’s documented defaults, change one parameter at a time, and keep a written record. Many reports that a model got worse turn out to be a settings change rather than a model change.

Testing sampling settings reproducibly

The following protocol is a design for a controlled comparison; it is not a report of measured results. It works for a single local model or a hosted endpoint.

  1. Fix the prompt, the system message, and the maximum output length.
  2. Record the runtime and version, the model and version, the quantization, the context length, and every sampling setting. Without this, a result cannot be reproduced or explained.
  3. Set a seed if your runtime supports one, and record it.
  4. Change exactly one parameter per run: sweep temperature at several values, then top-p, then top-k.
  5. Run each configuration more than once. A single sample tells you almost nothing about a stochastic process.
  6. Compare complete outputs side by side rather than relying on the impression that one felt better.
  7. Note where outputs are identical. Identical outputs at low temperature are expected; identical outputs at high temperature suggest the setting is not being applied where you think it is.

Common pitfalls

  • Equating low temperature with factual accuracy. Temperature only makes the model more likely to choose its highest-probability continuation. If that continuation is wrong, low temperature produces the wrong answer confidently and repeatedly.
  • Setting top-k and top-p aggressively at the same time. The stricter filter wins, and you lose the adaptivity that top-p is meant to provide.
  • Expecting bit-identical output at temperature 0. Greedy decoding removes sampling randomness, but floating-point summation order, batching, and runtime or hardware differences can still produce variation in practice. Treat temperature 0 as much more reproducible, not as a guarantee.
  • Confusing sampling parameters with training parameters. Temperature, top-k, and top-p are inference-time settings. They do not fine-tune the model, change its weights, or alter how much memory the weights and KV cache require.
  • Changing settings without logging them. In any automated pipeline, an untracked sampling change is indistinguishable from a regression.

Why this matters in local and automated workflows

Local runtimes expose these parameters directly, which is both a benefit and a hazard: you have full control, and full responsibility for recording what you set. Parameter names and conventions differ between runtimes, so check the runtime’s own documentation before assuming a value means the same thing it meant elsewhere.

In automation, sampling settings belong in configuration alongside the model version and quantization. If a WordPress publishing workflow or a batch summarization job calls a model through an API, log the sampling settings with each generation. When an output looks wrong three weeks later, the log is what lets you reproduce it. For anything published or acted on automatically, keep a human review step: sampling parameters control style and variability, not correctness.

A practical next step

Pick one real task you already run. Freeze every setting except temperature, and generate outputs at four values spanning low to high. Read them side by side and note where the content changes and where only the phrasing changes. Then repeat the exercise with top-p while holding temperature fixed. That single session of controlled comparison will teach you more about your model’s behavior than any recommended preset.

If you want to compare notes, share your model, runtime, quantization, the settings you swept, and the outputs that differed. Concrete configurations are what make community troubleshooting useful.

FAQ

Does setting temperature to 0 make the output fully deterministic?

It removes sampling randomness by concentrating probability on the highest-ranked token, which is why it is treated as greedy decoding. It is not an absolute guarantee of identical output across runs, because floating-point summation order, batching, and runtime or hardware differences can still introduce variation.

Should I set both top-k and top-p at the same time?

You can, but the stricter filter effectively wins, which removes the adaptivity that top-p provides. Many practitioners leave top-k off and tune top-p, or tune only one of the two. Check your runtime's documentation, since some runtimes disable top-k when top-p is active.

Does temperature change what the model knows?

No. Temperature, top-k, and top-p are inference-time settings applied to the probability distribution the model already produced. They do not fine-tune weights, add knowledge, or change how much memory the model needs.

What should I change first if output is too repetitive or too unpredictable?

Change one parameter at a time. For repetitive output, a modest temperature increase or a slightly looser top-p usually helps. For output that drifts too far, lower temperature first and leave top-p permissive, then tighten top-p only if needed.

Do these settings affect generation speed or memory use?

They are applied at the final token-selection step rather than inside the model's forward pass, so they do not change weight size or KV cache requirements. Their effect on throughput is negligible compared with the cost of generating the tokens themselves.

References

  1. https://docs.aws.amazon.com/bedrock/latest/userguide/inference-parameters.html
  2. https://peterchng.com/blog/2023/05/02/token-selection-strategies-top-k-top-p-and-temperature/

Related terms

Temperature
An inference parameter that reshapes the next-token probability distribution without truncating it. Lower values concentrate probability on the top candidates; higher values spread it out.
Top-k sampling
A truncation strategy that keeps only the k most-likely candidate tokens, renormalizes their probabilities, and samples from that fixed-size set.
Top-p (nucleus sampling)
A truncation strategy that keeps the smallest set of tokens whose cumulative probability reaches p, so the shortlist grows or shrinks with the model's confidence.
Greedy decoding
Always selecting the single highest-probability next token, which is what low or zero temperature approximates.
Softmax
The final network layer that converts raw model scores into a discrete probability distribution over the vocabulary.
Renormalization
Dividing the kept probabilities by their sum after truncation so the reduced set again sums to 1.
Seed
A value that initializes the random sampling process, allowing the same prompt and settings to be replayed more consistently when the runtime supports it.

Leave a Reply

Your email address will not be published. Required fields are marked *