Temperature and response randomness in LLMs In 270 live API calls sweeping temperature from 0 to 1.8, JSON extraction held 100% accuracy at every setting while JavaScript code generation fell from 100% passing unit tests to 60%, according to a measurement study by developer Flavio. Twenty identical requests to gpt-4.1-mini with temperature 0 and seed 42 returned the same system fingerprint (fp_97d03b3513) but 20 different outputs, and gpt-6-luna rejected temperature 0 with an HTTP 400 error. The results show temperature is a single division of logits before softmax that reshapes the sampling distribution rather than guaranteeing determinism, so reliability varies by task type. Temperature and response randomness in LLMs By Flavio https://flaviocopes.com/about/ Tagged: AI https://flaviocopes.com/tags/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 https://flaviocopes.com/ai-fundamentals/ walks through the full loop, and build a language model from scratch https://flaviocopes.com/build-llm-from-scratch/ shows the forward pass and sampling code step by step. Right before softmax runs, the inference server applies your sampling settings. Temperature https://flaviocopes.com/ai-glossary/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.030666 - For : -3.530666 - sqlite : -7.030666 - better : -11.030666 - Better : -11.530666 - SQLite with a leading space : -12.655666 - for : -13.905666 - Sql : -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 . js 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 fingerprint values: 1 fp 97d03b3513 on 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 : 1. 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. 2. Code generation with real unit tests : write a standalone JavaScript function parseCacheControl header that parses HTTP Cache-Control directives handling flags like no-cache , numeric values like max-age=3600 , quoted strings, and case normalization , then execute each returned function in Node.js against a real assertion suite. 3. 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. python 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 at T = 0.2 , 0.7 , 1.0 , 1.4 , 1.8 - Unexpected token ';' at T = 0.7 - Invalid left-hand side in assignment at T = 1.4 - Unexpected identifier 'numericKeys' at T = 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