Sub topic 10
Sampling Parameters and Output Variability
This chapter covers why the same prompt can produce different replies, and which settings control that variation. It assumes you have read the earlier chapters on prompt anatomy and output formats. You should be comfortable reading short Python snippets and know basic JSON.
Why the same prompt gives different answers
A language model does not look up a stored answer. It generates text one token at a time. A token is a small piece of text, often a word or part of a word. At each step the model produces a score for every token in its vocabulary. Those scores are turned into probabilities, and one token is chosen. The chosen token is appended to the text, and the process repeats until the reply ends.
The choice step is where variability comes from. If the model gives "positive" a probability of 0.80 and "neutral" a probability of 0.15, a program that picks randomly according to those probabilities will pick "neutral" about one time in seven. Settings that change how this choice is made are called sampling parameters. They are usually set in the API call or the chat interface, not in the prompt text.
Sampling parameters do not change what the model knows. They change how much risk it takes when choosing among tokens it already considers plausible.
Temperature
Temperature is the most commonly used sampling parameter. It rescales the probabilities before a token is picked.
- A low temperature makes the distribution sharper. The most likely token becomes even more likely, so replies are more consistent.
- A high temperature flattens the distribution. Less likely tokens get a larger share, so replies are more varied and sometimes stranger.
- A temperature of 0 usually means "always pick the most likely token". This is called greedy decoding.
The following table gives typical starting points. Exact ranges differ by provider. Many APIs accept 0 to 1, and some accept 0 to 2. Check the documentation for the model you use.
| Task | Typical temperature | Reason |
|---|---|---|
| Classification, extraction | 0 to 0.2 | You want the same label every time |
| Summaries, question answering over a document | 0.2 to 0.5 | Accuracy matters, light wording variation is fine |
| Drafting emails, general writing | 0.5 to 0.8 | Some variety helps the text read naturally |
| Brainstorming names, slogans, ideas | 0.8 and above | Variety is the goal |
The effect on probabilities
The following script shows the effect of temperature without calling any model. It takes made-up scores for three tokens and converts them to probabilities at different temperatures. The probability of token i is proportional to exp(score_i / T), where T is the temperature.
import math
def softmax_with_temperature(scores, temperature):
scaled = [s / temperature for s in scores]
biggest = max(scaled) # subtract for numerical stability
exps = [math.exp(s - biggest) for s in scaled]
total = sum(exps)
return [e / total for e in exps]
tokens = ["positive", "neutral", "negative"]
scores = [3.0, 2.0, 0.5]
for t in (0.2, 1.0, 2.0):
probs = softmax_with_temperature(scores, t)
row = ", ".join(f"{tok}={p:.2f}" for tok, p in zip(tokens, probs))
print(f"T={t}: {row}")At T=0.2, "positive" gets almost all the probability. At T=2.0, the three options are much closer together. Temperature 0 cannot be computed with this formula because it divides by zero, which is why APIs treat 0 as a special case and take the top token directly.
Top-p and top-k
Temperature changes all probabilities. Two other parameters instead cut off the unlikely tokens before sampling.
- Top-k keeps only the
kmost likely tokens. Withtop_k = 40, the model samples from the 40 best candidates and ignores the rest. - Top-p, also called nucleus sampling, keeps the smallest group of tokens whose probabilities add up to at least
p. Withtop_p = 0.9, the model samples from the most likely tokens that together cover 90% of the probability. The size of the group changes from step to step. If the model is confident, the group may contain one or two tokens. If it is unsure, the group is larger.
Top-p adapts to the situation, which is why it is more common than top-k. Not every provider offers both. Some offer only temperature and top-p.
Combining them
Temperature and top-p both affect randomness, and their effects overlap. A common recommendation is to change one and leave the other at its default. If you lower both at once, you cannot tell which change caused a difference in your results.
Other parameters that affect the output
Several other settings influence length and repetition. They are not sampling in the strict sense, but they appear in the same place in API calls.
| Parameter | What it does | Common use |
|---|---|---|
| `max_tokens` | Sets a hard limit on reply length | Prevent very long replies and control cost |
| Stop sequences | Ends generation when a given string appears | Stop after one answer in a few-shot pattern |
| Frequency and presence penalties | Reduce the chance of repeating tokens already used | Reduce repetitive text in long outputs |
| Seed | Asks the provider to use a fixed random seed | Make results more reproducible |
Two of these have gotchas that matter in practice.
max_tokenscuts off text; it does not shorten it. If the limit is reached in the middle of a JSON object, the reply is invalid JSON. Setting a low limit does not make the model write a shorter answer. To get a shorter answer, say so in the prompt, and usemax_tokensonly as a safety limit.- Stop sequences help few-shot prompts. In the few-shot pattern from the earlier chapter, the model may continue and invent a new
Review:entry after its answer. Setting"\nReview:"as a stop sequence ends the reply right after the label.
Is temperature 0 fully deterministic?
Not always. Even at temperature 0, many hosted models can return slightly different text for the same prompt. Reasons include:
- Floating-point arithmetic on parallel hardware can produce tiny differences in scores, and two tokens with nearly equal scores may swap order.
- The provider may route requests to different servers or software versions.
- Some models and modes do not allow temperature to be set to 0, or ignore it.
- A seed parameter, where offered, improves reproducibility but is typically documented as best effort.
The practical conclusion is that you should not build a system that assumes identical text on every call. Instead, constrain what you accept, as the next section shows.
Measuring variability in code
Because outputs can vary, a single test run tells you little. You can estimate variability by sending the same prompt several times and counting the distinct replies. The function below uses call_model, the same kind of function used in the evaluation chapter: any function that sends a prompt to a model and returns its text. It accepts a temperature argument here so you can compare settings.
from collections import Counter
def sample_replies(call_model, prompt, temperature, runs=10):
replies = []
for _ in range(runs):
reply = call_model(prompt, temperature=temperature)
replies.append(reply.strip().lower())
return Counter(replies)
def agreement(counter):
total = sum(counter.values())
most_common_count = counter.most_common(1)[0][1]
return most_common_count / total
# Example with a fake model so the code runs without any API.
import random
def fake_model(prompt, temperature):
# Higher temperature makes the fake model wander more often.
if random.random() < temperature * 0.3:
return random.choice(["positive", "neutral", "negative"])
return "positive"
for t in (0.0, 0.7, 1.5):
counts = sample_replies(fake_model, "Review: great phone", t, runs=50)
print(t, dict(counts), f"agreement={agreement(counter=counts):.2f}")The agreement value is the share of runs that produced the most common reply. For a classification task you want it near 1.0. For a brainstorming task, a low value is fine and often desirable.
Choosing settings in practice
Use this decision order when you are setting up a prompt.
- Decide whether the task has one right answer (classification, extraction, math, code) or many acceptable answers (writing, ideas).
- For one-right-answer tasks, start with temperature 0 or close to it. Keep top-p at its default.
- For open-ended tasks, start at the provider default, then adjust upward or downward in small steps.
- Set
max_tokenshigh enough that valid replies are never cut off, and add a stop sequence if the pattern needs one. - Test each setting with several runs, not one, and compare the results with the same test cases.
Failure modes at each end
| Setting too low | Setting too high |
|---|---|
| Repetitive, bland text | Off-topic or incoherent text |
| Identical ideas on every run | Invented facts and wrong labels more often |
| Can get stuck repeating a phrase in long output | Broken formats, such as invalid JSON |
| Little variety across users | Results that differ between test runs, so comparisons are unreliable |
Low temperature does not make the model correct. It makes the model consistent. A model that is wrong at temperature 0 will be consistently wrong. If the answers are wrong, improve the prompt, add examples, or split the task, as covered in earlier chapters.
Sampling and structured output
Earlier chapters showed that you should validate a JSON reply in code. Sampling settings make this more important. A higher temperature increases the chance that the model adds extra text such as "Sure! Here is the answer:" or drops a closing brace. A low temperature reduces these problems but does not remove them.
A reliable pattern is to validate, then retry once with a lower temperature if validation fails.
import json
ALLOWED = {"positive", "negative", "neutral"}
def parse_reply(reply):
try:
data = json.loads(reply)
except json.JSONDecodeError:
return None
if not isinstance(data, dict) or data.get("sentiment") not in ALLOWED:
return None
return data
def classify_with_retry(call_model, prompt):
for temperature in (0.5, 0.0):
reply = call_model(prompt, temperature=temperature)
data = parse_reply(reply)
if data is not None:
return data
return None # caller decides what to do: log, flag for review, or failThe function returns None rather than guessing when both attempts fail. That makes the failure visible to the code that calls it. Some providers also offer a structured output or JSON mode that constrains generation to valid JSON. Use it when available, and still validate the values, because valid JSON can contain a label you did not allow.
Common mistakes
- Judging a prompt from a single run at a nonzero temperature. The result may be luck.
- Changing the prompt and the temperature in the same experiment.
- Assuming temperature 0 guarantees byte-identical output.
- Setting
max_tokenslow to get brevity, then receiving truncated replies. - Copying parameter values from a different model or provider without checking that the range and meaning match.
- Leaving a high temperature in a production classification step because it was convenient during brainstorming.
Exercise
A classification prompt returns "neutral" on 6 of 10 runs and "positive" on the other 4, with temperature 0.9. A teammate suggests raising max_tokens to fix this. What would you do instead, and how would you check that it worked?
Show answer
max_tokens controls length, not variability, so it will not help. First lower the temperature to 0 or close to it and leave top-p at its default. Then run the same prompt on the same input 10 or more times and compute the agreement, meaning the share of runs giving the most common label. If the answers are still split at low temperature, the prompt is ambiguous about this input, so add a clearer rule or a few-shot example that covers it and test again on a set of labeled cases.
Exercise
Using the softmax_with_temperature function, scores of [3.0, 2.0, 0.5] give probabilities at T=1.0. Will the probability of the top token go up or down at T=0.5, and will it go up or down at T=2.0?
Show answer
At T=0.5 the top token's probability goes up, because dividing by a smaller temperature makes the gaps between scores larger and the distribution sharper. At T=2.0 it goes down, because the gaps shrink and the distribution flattens. You can confirm by running the script with those temperatures.
Exercise
Your few-shot sentiment prompt ends with "Sentiment:" and the model sometimes replies "positive" and then continues with a made-up "Review: ..." line. Which parameter fixes this, and what value would you give it?
Show answer
Use a stop sequence. Set it to "\nReview:" so generation ends as soon as the model starts a new review entry. Keep max_tokens as a safety limit as well, but it does not solve the problem by itself.