Concepts / Temperature and Output Randomness

Temperature and Output Randomness

Temperature controls how random a model's output is. Higher values let lower-probability tokens surface more often, but the picture of chaos is an intuition, not an exact measurement.

  • Programming

Same Question, Different Answers

Ask a model the same question twice and you may get two different answers. Sometimes that variety is useful, and sometimes it is a problem. A customer-facing product needs answers that are consistent and correct, while a brainstorming tool may want surprising ideas. The difference between those two needs is largely a matter of how a model's output is drawn from its probability estimates, and that is the subject of this article.

Before reading on, make a prediction. Suppose you raise the temperature setting. Think about which tokens, the high-probability ones or the low-probability ones, would be more likely to show up in the output.

What do you think happens?

When temperature is raised, will lower-probability tokens appear more often or less often?

  • More often

  • Less often

  • Exactly the same

Reveal answer
Answer:

More often

The source states that higher temperature values let lower-probability tokens surface more often. Temperature therefore changes how much room unlikely choices get, not only how many choices there are.

Where Randomness Enters a Response

A model produces output by making a series of choices, one token after another. At each step it has a set of candidate tokens, each with an estimated probability. Sampling methods are the practical choices that control how the next token is drawn from those estimates, and how several complete outputs can be produced and compared.

The source frames the whole topic around one question asked at each step: where does the randomness enter, and what control do I have over it? It names three tools, and each answers a different question. Temperature controls the randomness of each individual choice. Log probabilities are a window into the model's confidence. Self-consistency uses several draws and a scoring rule to pick one result. Keeping these three apart in your mind makes the rest of the article easier to follow.

How Temperature Reshapes Token Choices

Temperature controls how random a model's output is. Higher values let lower-probability tokens surface more often. Lower values keep the output closer to the tokens the model rates most likely. The effect is applied to each choice, so a higher temperature gives many small chances for an unlikely token to win, and those chances add up over a long output.

Likely tokenchosen most oftenLikely tokenless dominantUnlikely tokenrarely surfacesUnlikely tokensurfaces more oftentemperature raisedtemperature raised
How the relative chance of a likely token and an unlikely token shifts when temperature is raised. The shift is described qualitatively, not as exact numbers.

Read the diagram as a before and after of the same two tokens. The likely token still exists after the change, but it no longer dominates as strongly. The unlikely token gains share, which is exactly what the source means when it says higher temperature lets lower-probability tokens surface more often. The diagram is an illustration of direction, not a measurement of specific probabilities.

Log Probabilities as a Window into Confidence

Definition

A log probability is the logarithm of a token's probability. It is a different way of writing the same underlying likelihood, and the source describes it as a window into the model's confidence in a token.

Why use the logarithm at all? The source does not spend much time on that, but the practical point is that the values line up with confidence in a readable way. A token the model considers very likely has a probability close to 1, and its log probability is close to 0. A token the model considers very unlikely has a probability close to 0, and its log probability is a large negative number. So a log probability near zero signals a likely token, and a more negative value signals a less likely one.

Probability near 1log probability near 0Probability near 0log probability a largenegative number
How a token's probability maps to its log probability. Likely tokens sit near zero on the log scale, and unlikely tokens fall far below zero.

Keep this mapping in mind when you read logprob values. You are not looking at a score out of 100 where bigger is better in every sense. You are looking at a logarithm of a probability, so values closer to zero mean the model rated that token as more likely.

What Providers Expose and Where Limits Apply

Not every provider makes logprobs available, and the ones that do may limit what you can see. As of the source's writing, the OpenAI API showed logprobs only for up to the 20 most likely tokens at each position. It had once allowed retrieving logprobs for arbitrary text supplied by the user, but that option was discontinued in September 2023. Anthropic did not expose logprobs for its models, according to the source.

ProviderWhat the source reports about logprobsWhat this limits
OpenAI APIShows logprobs for up to the 20 most likely tokens at each position. Retrieving logprobs for user-supplied arbitrary text was discontinued in September 2023.You see only the top of the distribution, not every token the model could have chosen.
AnthropicDid not expose logprobs for its models.A technique that relies on logprobs cannot be run directly against these models.

Provider access to logprobs as described in the source at the time of writing

Tiny Probabilities and Underflow

Probabilities for individual tokens can be extremely small, and a small number has to be stored in some numeric format. The underflow problem occurs when a number is too small to be represented in a given format, so it gets rounded down to zero.

The danger is that once a value has been rounded to zero, the information that it was small but not impossible is gone. Anything that depends on comparing those tiny values can no longer tell them apart. Two tokens that were very different in how unlikely they were may end up looking identical, which is why the source treats the boundary between tiny and impossible as something worth preserving.

Self-Consistency: Generate, Score, Select

Self-consistency is a technique for improving the quality of generated output. Instead of accepting the first output, you generate several outputs for the same input and select the best one. The source notes that Wang et al. (2023) called this approach self-consistency. The best one is chosen by a scoring rule, and the rule the source connects to this technique is the average logprob of each output.

Single inputsame prompt for all drawsSample candidatesseveral outputs generatedScore each candidateaverage logprobKeep highest scorecompare averagesReturn winnerone output returnedrepeat generationeach outputscoresbest output
The steps in order, from one input through sampling several candidates, scoring each one, and returning the winner.
  1. 1
    Start with one input and generate several outputs for it.
  2. 2
    Compute a score for each output, using the average of its per-token log probabilities.
  3. 3
    Compare the scores across all candidates.
  4. 4
    Return the output with the highest average logprob as the result.

Asking the API for the Best Candidate

In the OpenAI API, the best_of parameter can be set to a specific value to carry out this process. The source's example sets it to 10, which asks the model to return the output with the highest average logprob out of 10 different outputs. You do not write the comparison yourself in that case, but it helps to understand what the parameter is doing.

python
Notes on the code
  • best_of is the parameter name, used as a keyword argument in the request
  • The value 10 means ten candidate outputs are generated and compared
  • The API returns the candidate with the highest average logprob

Average Logprob as the Scoring Rule

The comparison score in self-consistency is the average of the per-token log probabilities across a whole output. Averaging puts outputs of different lengths on a common footing: you divide the total by the number of tokens, so a long output is not penalized only for having more tokens. Each per-token value is a log probability, so values closer to zero indicate more likely tokens, and a higher average means a more confident output overall.

Formula
Worked example

Choosing Between Two Candidates by Average Logprob

Two candidate outputs were generated for the same input. Candidate A has per-token logprobs of -0.2, -0.4, and -0.1. Candidate B has per-token logprobs of -0.1 and -0.9. Which candidate does the scoring rule select?

  1. 1
    Average Candidate A

    Sum the values: -0.2 + -0.4 + -0.1 = -0.7. Divide by the 3 tokens to get an average of -0.7 / 3, which is about -0.233.

  2. 2
    Average Candidate B

    Sum the values: -0.1 + -0.9 = -1.0. Divide by the 2 tokens to get an average of -0.5.

  3. 3
    Compare the averages

    Both averages are negative, and the one closer to zero is higher. About -0.233 is higher than -0.5, so Candidate A ranks higher.

Result

Candidate A is returned. Its average is higher, meaning its tokens were on average rated as more likely.

Paying for Several Candidates

Generating several outputs costs more than generating one, since paid model APIs often charge per output token. Generating ten candidates means paying for roughly ten outputs' worth of tokens, so the technique is a deliberate trade of cost for a chance at a better result.

The source points out that some of that cost can be reduced. For instance, the input might be processed once and reused across all of the outputs, rather than being processed again for each one. This is a useful thing to ask about when you evaluate a provider or a method.

Where Sampling Controls Stop

Sampling controls only go so far. The source describes a model whose structured output is unreliable, and reports that the percentage of correctly generated JSON objects, depending on the application and model, ranged anywhere from 0% up to the high 90s. Turning temperature or scoring rules does not repair a model that cannot produce the format at all.

When a model is this brittle, the source's suggested fix is to replace it with a different model rather than to keep tuning the sampling controls. Another route the source mentions is training a model from scratch on data in the desired format, though the source says that is outside its scope. Fine-tuning, which adjusts a pre-trained model to better suit a specific task or dataset, is related. Some fine-tuning services adjust the model to the desired format automatically.

Hallucination, meaning the generation of incorrect or misleading information, is one reason these controls matter. In a review of three months of customer support requests for an AI company, the source's author found that one-fifth of the questions concerned handling the inconsistency of AI models. In a 2023 panel, the speakers agreed that hallucination is the biggest blocker for many AI enterprise use cases.

Mistakes With Temperature and Logprobs

  • Common mistake

    Treating higher temperature as a way to make answers more accurate

    Why it fails

    Higher temperature lets lower-probability tokens surface more often. That increases variety, which is useful for brainstorming but not a guarantee of correctness.

    Do this instead

    Match the temperature to the job. Use lower settings when consistency matters and higher settings when surprising ideas are the goal.

  • Common mistake

    Reading the temperature picture as exact probabilities

    Why it fails

    The source is explicit that the picture of chaos is an intuition, not an exact measurement.

    Do this instead

    Use the direction of the effect for reasoning, and measure real behavior when precise numbers matter.

  • Common mistake

    Assuming every provider returns logprobs

    What it looks like

    Writing a method that needs per-token logprobs and then discovering the chosen provider does not expose them.

    Why it fails

    The source reports that Anthropic did not expose logprobs for its models, so the technique depends on the provider.

    Do this instead

    Check what each provider returns before designing a logprob-based technique.

  • Common mistake

    Assuming you can see the full distribution of tokens

    Why it fails

    The source reports that the OpenAI API showed logprobs only for up to the 20 most likely tokens at each position.

    Do this instead

    Treat logprob views as partial and reason only about the tokens you can actually see.

  • Common mistake

    Treating tiny probabilities as identical because both round to zero

    Why it fails

    Underflow rounds a too-small number down to zero, erasing the difference between tiny and impossible values.

    Do this instead

    Be aware of the numeric format you are working in, and do not compare values that have already been rounded to zero.

  • Common mistake

    Believing the highest average logprob candidate is guaranteed to be correct

Practice: Pick the Winning Candidate

MEDIUM

Three candidate outputs were generated for the same input. Candidate X has per-token logprobs of -0.3, -0.3, and -0.6. Candidate Y has per-token logprobs of -0.5 and -0.1. Candidate Z has per-token logprobs of -0.2, -0.2, -0.2, and -0.4. Compute each average and state which candidate the self-consistency scoring rule would return.

Hints
  • Add up each candidate's logprobs first, then divide by how many tokens that candidate has.
  • Remember that a candidate with more tokens is not penalized simply for being longer, because you divide by the count.
  • The winner is the candidate whose average is closest to zero, since a higher average means its tokens were rated as more likely.

Key Takeaways

  • Temperature controls how random a model's output is: higher values let lower-probability tokens surface more often, and the picture of chaos is an intuition rather than an exact measurement.
  • A log probability is the logarithm of a token's probability, so values near zero indicate likely tokens and large negative values indicate unlikely ones; providers differ in whether they expose it and how many top tokens they show.
  • Self-consistency generates several outputs for one input, scores each by its average logprob, and returns the highest scorer; the best_of parameter in the OpenAI API implements this, with the source's example using 10.
  • Generating several candidates costs more because APIs often charge per output token, though input processing can sometimes be reused across outputs.
  • Sampling controls have limits: when a model is unreliable, the source suggests replacing it rather than tuning sampling further.

Related concepts

More concepts starting with T