Temperature and response randomness in LLMs
By Flavio
Tagged: AI
What temperature actually does to next-token logits, why temperature=0 is still non-deterministic in cloud APIs, and measured reliability across 270 live runs.
Most developers learn one rule about LLM temperature: set it to 0 when you want reliable, repeatable output, and turn it up when you want creative writing.
That rule breaks down pretty fast once you test it against a real API.
When I ran 20 identical requests to gpt-4.1-mini with temperature: 0 and seed: 42, the API returned the exact same system_fingerprint (fp_97d03b3513) every time, and still gave me 20 different outputs. When I tried passing temperature: 0 to gpt-6-luna, the API refused the request with an HTTP 400 error. And across 270 live calls sweeping from 0 to 1.8, JSON extraction stayed at 100% accuracy at every temperature while JavaScript code generation dropped from 100% passing unit tests down to 60%.
Temperature is a single division inside the token sampler. Once you see what that division does to raw model scores, all three of those results stop looking weird and start looking predictable.
Language models output distributions, not answers
A language model does not think of a sentence and type it out. At every step of generation, it takes all the tokens in the conversation so far, runs them through its transformer layers, and produces one raw number for every token in its vocabulary.
If the vocabulary has 200,000 tokens, the model outputs a vector of 200,000 raw scores at every single token step. Those raw numbers are called logits. A logit can be positive, negative, or zero. On its own, a logit is not a probability, because the numbers do not add up to 1 and some of them are negative.
Before the runtime can pick the next token, it has to turn those 200,000 logits into a valid probability distribution where every value sits between 0 and 1 and the whole list sums to 1. That conversion happens through the softmax function. If you want the broader picture of how a transformer turns input text into those scores, AI fundamentals walks through the full loop, and build a language model from scratch shows the forward pass and sampling code step by step.
Right before softmax runs, the inference server applies your sampling settings. Temperature is the first and most important of those knobs. It never changes the model’s weights, never alters what the model knows, and never makes the model smarter or more factual. It only reshapes how sharply the final probability distribution favors the top-scoring tokens over the runner-ups.
Once softmax produces probabilities, the runtime rolls a weighted die using those probabilities and appends the winning token to the prompt. Then the entire forward pass runs again to predict the next token. Because every token you emit becomes part of the input for the next step, one different roll early in a response changes the path of the whole reply.
What temperature actually does to logits
Temperature scaling is one operation: divide every logit z_i by the temperature T before passing the vector into softmax.
scaled_logit_i = z_i / T
probability_i = exp(z_i / T) / sum_j(exp(z_j / T))
Think about what dividing by T does to the gap between two logits.
Suppose token A has a logit that is 3.5 points higher than token B. At T = 1.0, dividing by 1.0 leaves the gap at 3.5. Since exp(3.5) is about 33.1, token A is roughly 33 times more likely to be sampled than token B.
Now lower T to 0.2. Dividing by 0.2 multiplies every logit by 5. The gap between token A and token B jumps from 3.5 to 17.5. Since exp(17.5) is nearly 40,000,000, token A wipes out token B completely.
Now raise T to 2.0. Dividing by 2.0 cuts the gap in half, from 3.5 down to 1.75. Since exp(1.75) is only 5.75, token B suddenly climbs from a rare long shot to a real contender.
In the limit as T approaches 0, the gap between the highest logit and everything else blows up toward infinity, so the top token gets probability 1.0 and every other token gets 0. In practice, runtimes do not literally divide by zero. When you send temperature: 0, the sampler skips the division and simply picks argmax(logits), the single highest-scoring token.
At the other extreme, as T grows very large, every z_i / T shrinks toward 0, exp(0) approaches 1, and every token in the entire vocabulary approaches equal probability 1 / V. At that point the model is pulling random words out of a hat.
Let’s check this on real numbers instead of made-up ones. I asked gpt-4.1-mini for a completion with logprobs: true and top_logprobs: 8, and captured the exact natural log probabilities at a single token position where the model strongly preferred SQLite.
Here are the 8 raw logprob values the API returned at T = 1.0:
SQLite:-0.030666For:-3.530666sqlite:-7.030666better:-11.030666Better:-11.530666SQLite(with a leading space):-12.655666for:-13.905666Sql:-14.155666
Notice the gaps between those numbers. The jump from SQLite to For is exactly 3.500000, to sqlite is 7.000000, to better is 11.000000, and to SQLite is 12.625000. Those clean binary fractions (0.5, 0.125) show up because the logits were computed in reduced-precision floating point (bfloat16 or float16) inside the serving kernel.
One neat mathematical property lets us rescale these logprobs accurately without knowing the unnormalized raw logits. By definition, a log probability at T = 1 is logprob_i = z_i - log(Z), where log(Z) is the same constant for every token in the vocabulary at that step. Because softmax is shift-invariant (adding or subtracting the same constant from every input cancels out in the numerator and denominator), computing softmax(logprob_i / T) gives the exact rescaled conditional probabilities over those 8 candidates.
Here is the Node.js helper that takes those real logprobs and computes the rescaled distribution at any temperature. Subtracting maxVal before calling Math.exp is the standard numerical-stability trick so large numbers never overflow to Infinity.
const topLogprobs = [
{ token: 'SQLite', logprob: -0.030666351318359375 },
{ token: 'For', logprob: -3.5306663513183594 },
{ token: 'sqlite', logprob: -7.030666351318359 },
{ token: 'better', logprob: -11.03066635131836 },
{ token: 'Better', logprob: -11.53066635131836 },
{ token: ' SQLite', logprob: -12.65566635131836 },
{ token: 'for', logprob: -13.90566635131836 },
{ token: 'Sql', logprob: -14.15566635131836 },
]
function rescaleDistribution(candidates, temperature) {
if (temperature === 0) {
return candidates.map((c, index) => ({
token: c.token,
probPct: index === 0 ? 100 : 0,
}))
}
const scaled = candidates.map((c) => c.logprob / temperature)
const maxVal = Math.max(...scaled)
const exps = scaled.map((v) => Math.exp(v - maxVal))
const total = exps.reduce((sum, v) => sum + v, 0)
return candidates.map((c, index) => ({
token: c.token,
probPct: Number(((exps[index] / total) * 100).toFixed(2)),
}))
}
for (const temp of [0.2, 0.7, 1.0, 1.5, 2.0]) {
const dist = rescaleDistribution(topLogprobs, temp)
const summary = dist
.slice(0, 4)
.map((d) => `${JSON.stringify(d.token)}:${d.probPct}%`)
.join(' ')
console.log(`T=${temp.toFixed(1)} ${summary}`)
}
Running that function against the 8 real logprobs produces this exact probability table across five temperatures:
| Token | Raw logprob | P (T = 0.2) | P (T = 0.7) | P (T = 1.0) | P (T = 1.5) | P (T = 2.0) |
|---|---|---|---|---|---|---|
SQLite | -0.031 | 100.00% | 99.33% | 96.98% | 90.26% | 82.31% |
For | -3.531 | 0.00% | 0.67% | 2.93% | 8.75% | 14.30% |
sqlite | -7.031 | 0.00% | 0.00% | 0.09% | 0.85% | 2.49% |
better | -11.031 | 0.00% | 0.00% | 0.00% | 0.06% | 0.34% |
Better | -11.531 | 0.00% | 0.00% | 0.00% | 0.04% | 0.26% |
SQLite | -12.656 | 0.00% | 0.00% | 0.00% | 0.02% | 0.15% |
for | -13.906 | 0.00% | 0.00% | 0.00% | 0.01% | 0.08% |
Sql | -14.156 | 0.00% | 0.00% | 0.00% | 0.01% | 0.07% |
Look closely at the jump between T = 0.7 and T = 2.0. At T = 0.2, SQLite takes 100% of the rounded probability mass. Raising temperature to 0.7 gives For less than a 1% chance (0.67%). Once T hits 1.0, For reaches 2.93% and lowercase sqlite appears at 0.09%. By T = 2.0, SQLite has dropped to 82.31%, For has climbed to 14.30%, sqlite is 2.49%, and even weird tokenizations like SQLite with a stray leading space or Sql have measurable odds.
There is one more effect you cannot see from the top 8 tokens alone, and it explains why real models suddenly fall off a cliff near T = 1.8 or 2.0.
In our table, we renormalized over only 8 tokens. On the real server, softmax runs over the entire vocabulary of roughly 200,000 tokens. At T = 1.0, the remaining 199,992 junk tokens each have a logit around -18 to -25, so exp(-20) is roughly 2e-9. Even when you add 200,000 of them together, their combined probability is still tiny (0.0004, or 0.04%).
Now divide those same -20 logits by T = 2.0. Suddenly exp(-10) is 4.5e-5. Multiply 4.5e-5 by 100,000 low-probability vocabulary tokens and the collective tail mass jumps past 4.5, which is larger than the top token’s unnormalized weight of 1.0. Even when no single junk token looks likely on its own, the sheer number of garbage tokens in a 200,000-word vocabulary gangs up and steals probability mass from the good tokens.
And remember that a 300-token response rolls that die 300 times in a row. If each token has even a 1% chance of landing in the garbage tail, the odds of making it through 300 tokens without a single derailment are 0.99 ^ 300 = 4.9%. That math is why high temperatures rarely fail gently. They look fine for two sentences, then one stray identifier or broken brace ruins the rest of the output.

The chart above puts that rescaled distribution next to the measured pass rates from our 270-call experiment, which we will break down in detail after looking at what happens at T = 0.
Greedy decoding and the temperature = 0 myth
Every API tutorial tells you that temperature: 0 makes an LLM deterministic. You pass the same prompt twice, the sampler always picks the highest-scoring token (argmax), and you get back the exact same string.
On paper, that is true. On a real cloud inference cluster, it is false.
To measure how much drift actually happens, I sent the exact same prompt to gpt-4.1-mini 20 times in a row with temperature: 0 and seed: 42, and logged both the full output text and the system_fingerprint returned in each response.
Here is what came back:
- Unique outputs: 20 out of 20
- Unique
system_fingerprintvalues: 1 (fp_97d03b3513on all 20 responses) - First character where run 1 and run 2 diverged: character index 247
Here are the exact two snippets around character 247 from those two temperature: 0, seed: 42 calls:
Run A (around char 247):
...plete sequentially, improving overall efficiency compared to HTTP/1.1. However, because HT...
Run B (around char 247):
...plete sequentially, improving efficiency compared to HTTP/1.1. However, because HTTP/2 sti...
Look at that tiny split. For the first 246 characters, both runs emitted the exact same tokens. Then right after improving, Run A emitted overall and Run B emitted efficiency.
Both continuations are grammatically fine and mean almost the exact same thing, so the model assigned nearly identical logits to overall and efficiency at that position. Something inside the server nudged the logits by a hair, flipped which token sat on top by 0.0001, and argmax picked the other word.
Once Run A had improving overall in its context and Run B had improving efficiency, every subsequent forward pass saw a different prefix. Small phrasing differences snowballed through the remaining paragraphs until all 20 runs ended up distinct, even though every single one carried temperature: 0, seed: 42, and system_fingerprint: fp_97d03b3513.
Why did the logits change when the prompt, weights, temperature, seed, and server fingerprint were all identical? Three hardware and serving mechanics cause this, and all three are active on every major hosted API.
Floating-point math is not associative
In school math, (a + b) + c always equals a + (b + c). In IEEE 754 floating-point arithmetic, that identity fails whenever intermediate sums round differently.
Modern LLM inference runs mostly in 16-bit (BF16 or FP16) or 8-bit (FP8) floating point, where the mantissa has only a handful of bits of precision. A single transformer layer performs billions of multiply-accumulate operations across matrix multiplications and attention reductions. On a GPU, thousands of threads compute partial sums in parallel and combine them. If the reduction order changes even slightly, the last bit of the resulting float changes.
Dynamic continuous batching changes the kernel shape
A hosted API does not dedicate a GPU to your one request while it generates tokens. It uses continuous batching (also called in-flight batching) to pack your request alongside dozens of other users’ prompts arriving at the same millisecond.
On run 1, your token step might execute inside a batch of 7 sequences. On run 2, two seconds later, it might execute inside a batch of 29 sequences. Matrix multiplication libraries like cuBLAS and fused attention kernels pick different tile sizes and split-K reduction strategies depending on the batch dimension. Different tiling means a different addition order, which produces slightly different floating-point rounding at the output layer.
Even a single 1e-4 perturbation is enough to flip argmax whenever two reasonable words are tied. And across a 400-token answer, you hit dozens of tied phrasing positions like improving overall efficiency versus improving efficiency. You only need one flip for the whole rest of the output to fork.
Mixture-of-Experts routing adds batch coupling
Many modern cloud models use a Mixture-of-Experts (MoE) architecture, where a router sends each token to a small subset of specialized feed-forward subnetworks (for example, 2 or 8 experts out of 64 or 128).
To keep GPU memory and latency bounded, some MoE serving stacks enforce an expert capacity factor per batch. When too many tokens across the whole batch want the same expert in the same step, overflow tokens can be dropped or routed differently depending on who else is in the batch with you. Even without token dropping, grouping tokens by expert inside a variable-sized batch changes the exact matrix reduction shape for every expert layer, adding another source of tiny logit drift.
What seed and system_fingerprint actually buy you
If you are thinking, “Wait, isn’t seed supposed to fix this?”, look at where seed lives in the sampler. A random seed only controls the pseudo-random number generator used when drawing from the softmax distribution at T > 0. At T = 0, greedy argmax does not even consume a random number. And even at T > 0, a fixed seed produces the same sample only if the input probability vector is bit-for-bit identical first. If batching shifts the logits before the PRNG runs, the seed cannot undo it.
Similarly, system_fingerprint tracks backend configuration changes like model weights or serving software version. It does not lock which concurrent users share your GPU batch on a given millisecond.
Can you ever get true bit-for-bit determinism from an LLM? Yes, under tight constraints: if you run a dense (non-MoE) model yourself with batch-invariant kernels, fixed batch size (or batch size 1), fixed hardware, and deterministic CUDA reduction flags, you can get repeatable output. On a multi-tenant cloud API, you should treat temperature: 0 as low-variance mode, never as a strict pure function.
That means you should never design a system that breaks if two T = 0 calls differ by a word. Never key a cache on the model’s raw output text, never assert exact string equality in a flaky CI test on a prose response, and always validate structured fields or run real tests instead of praying T = 0 returns identical bytes.
Measuring temperature across 270 live calls
Theory is nice, but I wanted to see the real reliability curve on actual developer workloads instead of guessing where T = 0.7 turns dangerous.
I wrote a Node.js benchmark harness and ran 270 live calls against gpt-4.1-mini across six temperatures: 0, 0.2, 0.7, 1.0, 1.4, and 1.8. At each temperature, the script ran 15 trials across three distinct jobs (45 calls per temperature):
- JSON extraction: extract a structured JSON object with fixed keys and exact values from a short technical incident snippet, then check both
JSON.parse()validity and exact field equality. - Code generation with real unit tests: write a standalone JavaScript function
parseCacheControl(header)that parses HTTPCache-Controldirectives (handling flags likeno-cache, numeric values likemax-age=3600, quoted strings, and case normalization), then execute each returned function in Node.js against a real assertion suite. - Technical headline generation: write one clear blog post title explaining how SQLite WAL mode prevents reader-writer lock timeouts in Node.js, then count unique titles across the 15 trials.
Here is the core structure of the benchmark loop so you can run the same sweep against any model you use in production. Notice that the code task does not rely on eyeballing the output or asking another LLM to grade it. It compiles the function and runs concrete assertions against real Cache-Control headers.
import assert from 'node:assert/strict'
const TEMPERATURES = [0, 0.2, 0.7, 1.0, 1.4, 1.8]
const TRIALS = 15
function testParseCacheControl(codeText) {
const cleaned = codeText
.replace(/^```(?:js|javascript)?\s*/i, '')
.replace(/\s*```$/i, '')
.trim()
const factory = new Function(`${cleaned}\nreturn parseCacheControl`)
const fn = factory()
assert.deepEqual(fn('public, max-age=3600'), { public: true, 'max-age': 3600 })
assert.deepEqual(fn('no-cache, no-store, must-revalidate'), {
'no-cache': true,
'no-store': true,
'must-revalidate': true,
})
assert.deepEqual(fn('private, max-age=0, s-maxage=60'), {
private: true,
'max-age': 0,
's-maxage': 60,
})
assert.deepEqual(fn(''), {})
}
async function callModel(prompt, temperature) {
const res = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4.1-mini',
temperature,
messages: [{ role: 'user', content: prompt }],
}),
})
const data = await res.json()
return data.choices[0].message.content
}
When I ran the full 270-call sweep plus the 20-run determinism check and the gpt-6-luna compatibility probe, here is the terminal summary it produced.

And here is the complete measured table across all six temperature buckets:
| Temp | JSON valid | JSON exact | JSON unique | Code pass rate | Code unique | Title unique | Observed code errors |
|---|---|---|---|---|---|---|---|
0.0 | 100% | 100% | 2 / 15 | 100.0% | 4 / 15 | 1 / 15 | None |
0.2 | 100% | 100% | 2 / 15 | 93.3% | 5 / 15 | 2 / 15 | Unexpected end of input |
0.7 | 100% | 100% | 2 / 15 | 86.7% | 14 / 15 | 2 / 15 | Unexpected end of input, Unexpected token ';' |
1.0 | 100% | 100% | 6 / 15 | 73.3% | 15 / 15 | 4 / 15 | Unexpected end of input |
1.4 | 100% | 100% | 5 / 15 | 86.7% | 15 / 15 | 5 / 15 | Invalid left-hand side in assignment, Unexpected end of input |
1.8 | 100% | 100% | 5 / 15 | 60.0% | 15 / 15 | 8 / 15 | Unexpected end of input, Unexpected identifier 'numericKeys' |
There are four distinct surprises buried in this table, and each one teaches something practical about how sampling behaves in the wild.
Surprise 1: Even T = 0 produced 4 unique code implementations and 2 unique JSON strings
Look at the T = 0 row. Every JSON output parsed cleanly and matched every expected field (100%), and every parseCacheControl implementation passed all unit tests (100%). Yet the 15 identical T = 0 calls still produced 4 different JavaScript strings and 2 different raw JSON strings.
Only the short, single-line title task stayed 1 / 15 unique at T = 0. Why? Because a 12-token headline has far fewer opportunities to hit a near-tied logit step than a 150-token JavaScript function. The longer the generation, the higher the probability that GPU batch rounding flips at least one token along the way.
Surprise 2: JSON extraction stayed at 100% all the way to T = 1.8
If you expected JSON syntax to blow up at T = 1.4 or T = 1.8, look at columns 2 and 3. Every single trial from T = 0 to T = 1.8 returned valid JSON with 100% exact values.
Why did JSON survive temperatures that wrecked JavaScript code? Look at the entropy of the task. When a prompt gives the exact schema and short literal facts to copy out of the input, the model’s logits are extremely peaked at almost every position. The opening brace {, the exact quoted key names, the colons, and the literal copied values sit 10 to 15 logit points above any competing token. Dividing a gap of 12 by 1.8 still leaves a gap of 6.7, which means the right token still wins over 99.8% of the time.
The only tokens with flat, uncertain probabilities in short JSON extraction are cosmetic whitespace choices (spaces after colons, indentation width, trailing newlines). That is why JSON unique rose from 2 / 15 to 5 / 15 and 6 / 15 at T = 1.0 and above without causing a single parse error or wrong field value.
Do not over-generalize that result to every JSON task, though. If the model has to infer ambiguous categories, write long free-text summaries inside JSON string values, or emit a 2,000-token payload, entropy goes way up and high temperature will start dropping quotes or inventing keys. For strict production extraction, you still pair low temperature with schema-constrained structured outputs so the runtime masks invalid JSON tokens to -Infinity before sampling ever runs.
Surprise 3: Code generation degrades fast because syntax errors cascade
Now look at the parseCacheControl column. Pass rate drops from 100% at T = 0, to 93.3% at T = 0.2, to 86.7% at T = 0.7, to 73.3% at T = 1.0, ticks to 86.7% at T = 1.4, and crashes to 60.0% at T = 1.8.
First, notice that tick from 73.3% (11 / 15) at T = 1.0 up to 86.7% (13 / 15) at T = 1.4. With 15 trials per bucket, a difference of 2 trials is completely normal binomial sampling noise. At a true pass rate of 80%, the standard deviation of a 15-trial sample is over 10 percentage points. That is a good reminder when running your own evals: never tune a production hyperparameter based on 5 or 10 runs, because random variance will trick you into chasing ghosts.
Second, look at the actual Node.js syntax errors thrown across the failing trials:
Unexpected end of input(atT = 0.2,0.7,1.0,1.4,1.8)Unexpected token ';'(atT = 0.7)Invalid left-hand side in assignment(atT = 1.4)Unexpected identifier 'numericKeys'(atT = 1.8)
Why does code break so much harder than short JSON? Because code has far more branching decisions per function. You can write parseCacheControl with .split(','), a regex loop, reduce, a for...of loop, a Set of numeric directive names, or Number.isNaN. At every branch point, five valid coding idioms compete with close logits.
At T = 0.7, code_unique jumps from 5 / 15 (at T = 0.2) to 14 / 15. By T = 1.0, all 15 runs are unique (15 / 15). When you crank temperature up on a medium-entropy task like writing a parser, the model explores weird variable names, stray semicolons, and half-finished expressions. Because generation is autoregressive, once the sampler rolls a stray ; or writes an invalid assignment target on line 9, the model cannot backspace. It keeps predicting forward from a broken syntax tree, and new Function() throws immediately.
The Unexpected end of input failures also reveal a subtle failure mode: at higher temperatures, the model is more likely to add verbose commentary, extra helper functions, or stray Markdown fences around the code, which either strips awkwardly or hits the output token cap before the final closing brace }.
Surprise 4: Higher temperature barely makes headlines “creative”
This might be the most useful finding for anyone who cranks up temperature hoping for fresh writing. Look at the actual sample headlines gpt-4.1-mini produced at T = 0, T = 0.7, T = 1.0, and T = 1.8:
T = 0.0 (1/15 unique):
How SQLite WAL Mode Stops Reader-Writer Lock Timeouts in Node.js
T = 0.7 (2/15 unique):
How SQLite WAL Mode Avoids Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Stops Reader-Writer Lock Timeouts in Node.js
T = 1.0 (4/15 unique):
How SQLite WAL Mode Stops Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Prevents Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Eliminates Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Avoids Reader-Writer Lock Timeouts in Node.js
T = 1.8 (8/15 unique):
How SQLite WAL Mode Eliminates Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Stops Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Avoids Reader-Writer Lock Timeouts in Node.js
How SQLite WAL Mode Avoids Reader-Writer Lock Timeouts in Node.js
Read those four lines from T = 1.8 again. Even at T = 1.8, where code generation was failing 40% of the time with syntax errors, the headline generator stayed glued to the exact same sentence frame: How SQLite WAL Mode <Verb> Reader-Writer Lock Timeouts in Node.js. All temperature did was shuffle four synonyms in slot 5: Stops, Avoids, Prevents, Eliminates.
Why does that happen? Modern chat models go through heavy post-training (supervised fine-tuning and reinforcement learning from human preferences) that sharpens their phrasing distributions dramatically. Researchers call this mode collapse. The model has one favorite way to title a technical tutorial, so How, SQLite, WAL, Mode, and Reader-Writer have massive logit margins over every alternative. Only the verb slot has close competitors.
If you want genuinely different creative angles, turning temperature up from 0.7 to 1.8 is the wrong tool. You get synonym swaps until syntax collapses. Instead, keep temperature moderate (0.8 to 1.0) and ask for structural diversity in the prompt: ask for 10 titles in one call using 10 different angles (a question, a benchmark number, a bug symptom, a contrarian claim, a direct command). Prompting for distinct structures beats abusing temperature every single time.
How temperature interacts with top_p, top_k, min_p, and penalties
Temperature almost never runs alone in a production sampling stack. Most APIs and open-weight inference engines pass the logit vector through a chain of transforms before rolling the die. Knowing the exact order matters, because two knobs applied together can cancel each other out or produce bizarre side effects.
Let’s walk through every parameter in that pipeline and how it interacts with T.
top_p (nucleus sampling)
top_p sorts all vocabulary tokens from highest probability to lowest, adds their probabilities together from the top down, and cuts off the list as soon as the cumulative sum reaches p (for example, 0.9). Every token outside that nucleus gets set to 0, and the surviving tokens are renormalized to sum to 1.
The huge advantage of top_p is that it adapts to the model’s certainty at every step.
When the model is nearly sure about the next token, like our SQLite example at T = 1.0 (SQLite: 96.98%, For: 2.93%), setting top_p: 0.9 keeps only SQLite because one token already exceeds 0.90. When the model is choosing between ten equally plausible adjectives in a story, top_p: 0.9 keeps all ten.
Now look at what happens when you tweak temperature and top_p at the same time. Suppose you lower top_p to 0.85 AND raise temperature to 1.5. At T = 1.5, our SQLite token still holds 90.26%, so top_p: 0.85 slices the distribution right back down to one single token (SQLite) and erases the temperature bump completely. On the flip side, if you set temperature: 0.2 and top_p: 0.95, T = 0.2 already concentrates 100% of the mass on the top token, so top_p does nothing at all.
That is why OpenAI’s own API documentation advises altering temperature or top_p, not both. Leaving top_p at 1.0 (or at a gentle safety cap like 0.95 only when using high temperatures) and tuning temperature alone keeps your experiments readable. When you change two interacting knobs together, you cannot tell which one fixed or broke your eval.
top_k
top_k is simpler than top_p: keep only the k highest-scoring tokens (for example, top_k: 40), zero out the other 199,960 tokens, and renormalize.
The weakness of top_k is that it is blind to how confident the model actually is. When the model is 99.9% sure the next token in a JSON key is "status", top_k: 40 still forces 39 junk tokens to stay in the pool. If you also run a high temperature, those 39 junk tokens get inflated and occasionally sampled. Conversely, when 80 words are genuinely reasonable continuations, top_k: 40 cuts off 40 good words arbitrarily.
Some hosted APIs (like Anthropic and Google Gemini) expose top_k, while OpenAI’s chat completions API does not.
min_p
min_p is a newer truncation filter that solves the blind spots of both top_k and top_p, and it has become a favorite in open-weight serving engines like vLLM, SGLang, and llama.cpp.
Instead of setting a fixed count (top_k) or a fixed cumulative sum (top_p), min_p sets a relative floor proportional to the top token’s probability p_max:
keep token_i if p_i >= min_p * p_max
Look how clean that is on our real SQLite numbers at T = 2.0, where p_max = 82.31%. With min_p = 0.05, the cutoff threshold is 0.05 * 82.31% = 4.12%. SQLite (82.31%) and For (14.30%) survive, while sqlite (2.49%), better (0.34%), and all 199,992 garbage tail tokens get sliced off cleanly.
Because min_p scales with the top token’s confidence, it lets you run higher temperatures (even T = 1.2 or 1.5) to get real phrasing variety without suffering from the 200,000-token tail explosion we saw earlier. If you self-host open-weight models or call providers that expose min_p, pairing temperature: 1.0 with min_p: 0.05 is often much more stable than temperature plus top_p.
frequency_penalty and presence_penalty
Repetition penalties modify logits before temperature division.
presence_penaltysubtracts a flat constant from the logit of any token that has appeared at least once so far in the generated text. It nudges the model toward introducing new topics or vocabulary.frequency_penaltysubtracts a penalty proportional to how many times a token has appeared so far. It stops the model from getting trapped in loops like repeating the same sentence or bullet prefix over and over.
Watch out for how penalties interact with code and JSON. In JavaScript, Python, or JSON, tokens like {, }, ", ,, const, return, and indentation spaces appear dozens of times in every file. Turning on frequency_penalty during code generation or structured JSON output actively punishes the model for emitting valid syntax! Keep both penalties at 0 for code, JSON, SQL, and tool calls.
Here is how all seven sampling controls compare side by side:
| Parameter | Pipeline stage | What it modifies | Typical range | Main failure mode if misused |
|---|---|---|---|---|
temperature | Before softmax | Divides every logit z_i / T | 0.0 to 2.0 | Tail explosion above 1.2; false assumption of determinism at 0 |
top_p | After softmax | Keeps smallest top set summing to p | 0.8 to 1.0 | Fights with temperature when both are tuned together |
top_k | After softmax | Keeps only the top k tokens | 10 to 100 | Keeps junk tokens when confident, cuts good ones when flat |
min_p | After softmax | Drops tokens below min_p * p_max | 0.02 to 0.10 | Not exposed by every proprietary API |
presence_penalty | Before T scaling | Flat penalty on any already-used token | -2.0 to 2.0 | Forces awkward synonyms for domain terms that must repeat |
frequency_penalty | Before T scaling | Penalty scaled by prior token count | -2.0 to 2.0 | Breaks repeated syntax tokens (}, ", return) in code and JSON |
seed | During PRNG draw | Initializes sampler RNG | Integer | Does not override GPU batch non-determinism in cloud APIs |
Why reasoning models lock or reject temperature
If your application sends temperature: 0 on every request by default, switching to a reasoning model will break your code with an HTTP 400 error.
I tested this directly against gpt-6-luna by sending a standard request with temperature: 0. Here is the exact HTTP 400 payload the API returned:
{
"error": {
"message": "Unsupported value: 'temperature' does not support 0 with this model. Only the default (1) value is supported.",
"type": "invalid_request_error",
"param": "temperature",
"code": "unsupported_value"
}
}
OpenAI’s o-series and newer reasoning models reject non-default temperatures outright (or ignore them unless reasoning effort is disabled), and Anthropic’s extended thinking mode similarly locks temperature to 1.0 whenever thinking is turned on.
Why do labs take that knob away right when developers want maximum precision on math and coding?
There are three concrete engineering reasons.
First, reasoning models are trained with large-scale reinforcement learning over long chains of thought (techniques like RLVR and GRPO, where the model generates full reasoning traces and gets rewarded when the final answer passes a verifier). During RL training, the model samples its thinking tokens at temperature = 1.0. The learned policy and its internal confidence calibration are tuned specifically for that sampling distribution.
Second, greedy decoding (T = 0) causes pathological repetition loops inside long chains of thought. When a model generates 4,000 hidden reasoning tokens before answering, argmax gets trapped repeating phrases like “Wait, let me double check that… Wait, let me double check that…” until it exhausts the entire output token budget. Keeping T = 1.0 gives the model enough stochasticity to backtrack, question a dead-end hypothesis, and try a second approach inside its thinking trace.
Third, reasoning models have a different primary reliability knob: reasoning effort (or thinking budget). Instead of trying to squeeze extra accuracy out of a single forward pass by sharpening logits toward argmax, you give the model more test-time compute to verify its own steps before emitting the final answer.
In application code, this means you should never hardcode temperature: 0 globally inside a shared API client. Build a small model-capability check so your wrapper omits temperature automatically for reasoning models, and only sets it for standard non-reasoning models that accept it.
const LOCKED_TEMPERATURE_PREFIXES = ['o1', 'o3', 'o4', 'gpt-5', 'gpt-6']
function supportsCustomTemperature(model) {
const lower = model.toLowerCase()
return !LOCKED_TEMPERATURE_PREFIXES.some((prefix) => lower.startsWith(prefix))
}
function buildCompletionPayload({ model, messages, temperature = 0.2 }) {
const payload = { model, messages }
if (supportsCustomTemperature(model) && temperature !== undefined) {
payload.temperature = temperature
}
return payload
}
console.log(buildCompletionPayload({
model: 'gpt-4.1-mini',
messages: [{ role: 'user', content: 'Extract dates as ISO strings.' }],
temperature: 0,
}))
console.log(buildCompletionPayload({
model: 'gpt-6-luna',
messages: [{ role: 'user', content: 'Verify this SQL migration.' }],
temperature: 0,
}))
That five-line guard prevents an entire class of silent production outages when someone bumps a model string in an environment variable from a standard chat model to a reasoning model.
When higher temperature plus a verifier beats T = 0
Up to this point, our 270-call sweep made low temperature look like the clear winner for code: 100% pass rate at T = 0 versus 86.7% at T = 0.7.
So why would you ever run code generation at T = 0.7?
Because parseCacheControl is an easy problem where gpt-4.1-mini’s greedy first guess already works. Now consider a harder problem where a model’s greedy T = 0 guess gets stuck on a subtle edge case and fails.
If you run that hard prompt 5 times at T = 0, you will get the exact same wrong implementation (or minor whitespace variations of the same wrong logic) 5 times in a row. Your effective pass rate across 5 attempts is still 0%.
Now raise temperature to 0.7, generate N independent candidates in parallel, and run your real deterministic verifier (your unit test suite, TypeScript compiler, SQL explain check, or linter) on every candidate. Keep the first candidate that passes every check.
This pattern is called best-of-N sampling (often measured as Pass@k in coding benchmarks). The probability that at least one of N independent samples passes is:
P(at least one pass) = 1 - (1 - p)^N
Look what happens with real numbers.
Suppose on a tricky bug fix, a single sample at T = 0.7 has only a 35% chance of passing the test suite (p = 0.35), while T = 0 fails consistently because the greedy path hits a flawed assumption on line 4.
N = 1atT = 0.7:35.0%chance of a passing fixN = 3atT = 0.7:1 - (0.65)^3 = 72.5%N = 5atT = 0.7:1 - (0.65)^5 = 88.4%N = 8atT = 0.7:1 - (0.65)^8 = 96.8%
Even on our parseCacheControl numbers from the sweep, look at the diversity column at T = 0.7: 14 out of 15 implementations were structurally distinct, while individual trial accuracy stayed strong at 86.7%. Running just N = 3 samples at T = 0.7 pushes 1 - (1 - 0.867)^3 to 99.76%, while exploring genuinely different algorithmic approaches.
Here is a concrete Node.js helper that runs N parallel candidates at T = 0.7 and filters them through a real verifier function:
async function generateWithVerifier({
prompt,
verify,
samples = 4,
temperature = 0.7,
}) {
const attempts = Array.from({ length: samples }, () =>
callModel(prompt, temperature)
)
const candidates = await Promise.all(attempts)
const failures = []
for (const [index, candidate] of candidates.entries()) {
try {
verify(candidate)
return {
passed: true,
attempt: index + 1,
code: candidate,
}
} catch (error) {
failures.push({ attempt: index + 1, message: error.message })
}
}
return { passed: false, failures }
}
Notice the two requirements that make best-of-N work:
- You need a real, fast, deterministic verifier. Unit tests,
tsc --noEmit,JSON.parseplus a Zod schema, a SQL query planner, or a regex/parser check all qualify. If your only “verifier” is asking another LLM “which answer looks better?”, you lose most of the benefit because LLM judges have their own biases and blind spots. - Your temperature has to sit in the sweet spot (
0.6to0.8). Too low (0.1), and allNsamples collapse onto the same failing idea, wastingNtimes the tokens. Too high (1.6), and individual sample qualitypcraters from syntax errors faster than extra samples can compensate.
Also remember the cost math. Best-of-N multiplies your output token cost by N (though prompt caching keeps the repeated input prefix cheap). Use it selectively on hard tasks that already have automated checks, not on trivial requests where a single T = 0 call already passes 99% of the time.
Practical defaults by workload
When you are building an app or configuring an agent pipeline, you do not need to sweep six temperatures for every new feature. Most workloads cluster cleanly into five buckets.
| Workload | Starting T | Other sampling knobs | Pair with | Why this range works |
|---|---|---|---|---|
| Classification, routing, sentiment | 0.0 | top_p: 1.0, penalties 0 | Structured output enum schema | Sharpest focus on top label; smallest variance across batches |
| Data & JSON extraction | 0.0 to 0.2 | top_p: 1.0, penalties 0 | JSON Schema / Zod validation | Keeps copied values exact while schema prevents syntax drift |
| Single-shot code & SQL generation | 0.0 to 0.2 | top_p: 1.0, penalties 0 | Linter, typechecker, tests | Minimizes stray syntax tokens (Unexpected token ';', truncation) |
| Hard bug fixes with Best-of-N | 0.6 to 0.8 | top_p: 1.0 (or min_p: 0.05) | Automated test suite | Explores distinct fixes so verifier can pick a passing candidate |
| Technical docs & Q&A over context | 0.2 to 0.4 | top_p: 1.0, penalties 0 | Grounded source chunks | Keeps facts tight without robotic phrasing on long explanations |
| Brainstorming, titles, copy angles | 0.8 to 1.0 | top_p: 0.95 or min_p: 0.05 | Explicit structural diversity in prompt | Enough variation without crossing into syntax collapse above 1.2 |
Reasoning models (o3, gpt-6-luna, thinking) | Omit param | Use reasoning_effort instead | Tests or external checks | Model locks T = 1.0; passing 0 triggers HTTP 400 |
Notice how rarely you ever want a temperature above 1.0 in production. Between 0.0 and 1.0, you already span the full useful range from maximally sharp greedy decoding up to the model’s native training distribution. Above 1.2, tail tokens start leaking in faster than useful creativity increases, especially without min_p guarding the floor.
How I configure temperature
In my own projects and scripts, I treat temperature as a coarse switch rather than a dial I obsess over.
For anything that produces data my code is going to parse, route on, or store in a database, I set temperature: 0 (when the model allows it) and leave top_p at its default 1.0. I never rely on temperature: 0 alone for reliability, though. After seeing 20 out of 20 identical T = 0 runs diverge on gpt-4.1-mini, I treat T = 0 as one layer alongside strict JSON schemas, runtime Zod checks, and real assertions.
For coding agents and single-shot code generation on standard models, I stay in the 0 to 0.2 range. When I am running a coding tool backed by a reasoning model, I do not touch temperature at all and instead adjust the model’s reasoning effort. If an automated test suite is already in place and a hard bug resists a first pass, I would rather run 3 or 4 parallel attempts around T = 0.7 and let npm test pick the winner than keep retrying the same greedy prompt.
For writing helpers, headline ideas, or outlining drafts, I sit around 0.8 to 1.0 and push diversity through the prompt itself. Asking for five distinct structural angles at T = 0.9 gives me way better ideas than cranking temperature to 1.8 and getting Stops swapped for Eliminates four times in a row.
I also keep clear boundaries on what temperature is a poor fit for.
If a model is hallucinating nonexistent API flags, getting a business rule wrong, or ignoring a constraint in your system prompt, lowering temperature from 0.7 to 0 will almost never fix it. A wrong answer with high confidence just becomes a more consistently wrong answer. Fix the prompt, add the missing documentation to context, or switch models instead of turning the temperature dial.
And if you actually need bit-for-bit reproducibility for compliance, billing logs, or deterministic caching, temperature is the wrong tool completely. Cache the model’s response in your own database keyed by a hash of the request inputs, or pin a deterministic local execution environment, instead of expecting a multi-tenant cloud API at T = 0 to replay the same bytes twice.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: