{"course":{"slug":"building-with-ai","title":"Building with AI","url":"https://addaly.com/learn/building-with-ai","level":"intermediate","track":"build"},"lesson":{"slug":"sampling-and-determinism","title":"Temperature, sampling, and why the same input gives a different answer","url":"https://addaly.com/learn/building-with-ai/sampling-and-determinism","position":4,"of":80,"minutes":9,"answer":"Use the controls supported by the selected model, and evaluate accuracy and reproducibility on representative cases.","keyIdea":"Use the controls supported by the selected model, and evaluate accuracy and reproducibility on representative cases."},"body":{"format":"markdown","text":"## What the model actually produces\n\nA text-generation system scores possible next tokens and uses a decoding method to select one. Some APIs expose sampling settings. Others manage decoding without exposing those controls. The following is a simplified sampler for a model that supports these settings.\n\nA common sampling pipeline works as follows:\n\n1. Divide every logit by the **temperature**.\n2. Apply softmax to turn the scores into probabilities summing to 1.\n3. Optionally cut the tail: **top_k** keeps the k highest, **top_p** (nucleus) keeps the smallest set whose probabilities sum to at least p.\n4. Draw one token at random from what is left.\n\nTemperature divides before the softmax, so it stretches or flattens the distribution. At `temperature=2` the gaps between candidates shrink and unlikely tokens become reachable. At `temperature=0.1` the top candidate dominates. At exactly 0, most implementations skip sampling and take the argmax.\n\nTemperature changes the relative probabilities in this simplified sampler. It does not establish whether a generated claim is true. Hosted implementations and supported controls vary by model.\n\n## Check which controls the model supports\n\nClaude Sonnet 5.5, used in this chapter's request examples, rejects `temperature`, `top_p` and `top_k`. Leave them out of those requests. [Current model controls](https://platform.claude.com/docs/en/models/sonnet-5-5/overview).\n\nFor a model that exposes temperature, compare low settings for a repeatable classification task and higher settings for varied drafts. Treat ranges as experiment settings. Measure task accuracy and output variety separately. A low temperature cannot guarantee factuality or a valid schema.\n\nChange one supported control at a time, record its value and compare results on a fixed test set. This makes the effect easier to interpret.\n\n## Temperature 0 is not deterministic\n\nFor a model that accepts zero temperature, repeated requests can still differ. Numerical computation, serving behavior or a changed model version are possible causes. Different answers alone do not identify the cause.\n\n**Floating-point addition is not associative.** Summing a batch of numbers on a GPU in a different order gives a very slightly different result. Two logits that are nearly tied can swap places. One swapped token at position 40 can change the tokens after it, because each token conditions the next. A rounding difference in the twelfth decimal place becomes a different paragraph.\n\n**Batching can affect computation.** Some serving systems group concurrent requests. Depending on the kernels and their reproducibility guarantees, changes to batch shape can affect numerical results.\n\n**Some mixture-of-experts implementations have capacity-dependent routing.** Such routing may introduce another source of variation. Its relevance depends on the model and serving implementation.\n\nSome providers expose a seed or a serving-version identifier. Follow that provider's reproducibility contract and log the supported metadata. A seed alone does not establish that every part of inference is deterministic.\n\n## What to do about it\n\nChoose checks that match the task. Exact strings can be appropriate for an enumerated label. Structured fields are useful when several phrasings are acceptable.\n\nThe following illustrative fixtures compare exact prose matching with checks on selected structured fields. The production test still needs the expected values for its own case.\n\n```python\nimport json\n\nprose = \"The refund window is 30 days.\"\nassert prose == \"The refund window is 30 days.\"\n\nstructured = '{\"days\": 30, \"currency\": \"INR\"}'\ndata = json.loads(structured)\nassert data[\"days\"] == 30\nassert data[\"currency\"] in {\"INR\", \"USD\"}\n```\n\nThree habits follow from that:\n\n- Where you can, make the model emit **structured output** and assert on the fields. A number in a field is checkable; a sentence is an argument.\n- Where you cannot, assert on invariants: it cited at least one source, it did not mention a competitor, it stayed under 200 words, it refused an out-of-scope question.\n- To reuse a reviewed answer, cache it under the relevant inputs, prompt version, model version and access scope. Set an expiry or invalidation rule when its source data can change.\n\n## The uncomfortable consequence\n\nA single success or failure is limited evidence. Under an illustrative model of independent attempts with a 95% success probability, four attempts all succeed about 81% of the time. Repeated evaluations on representative cases help estimate performance, and failures reveal cases that need investigation.\n\nThis is the reason the evaluation module later in this course exists, and it is why builders who skip it end up debugging by anecdote."},"check":{"question":"The model weights, request input and greedy decoding rule are confirmed unchanged. Which numerical mechanism can still change the selected token when scores are nearly tied?","options":[{"text":"Some hidden randomness remains in the sampler that temperature 0 does not disable.","correct":false,"tempting":"Locates the cause in the sampler, when at temperature 0 most implementations take the argmax and do no sampling at all."},{"text":"The provider silently switched model versions between calls.","correct":false,"tempting":"The stated setup rules out a model-version change."},{"text":"The prompt contains ambiguity the model resolves differently each time.","correct":false,"tempting":"Treats the model as making a fresh interpretive choice, when the same weights and same argmax rule should give the same interpretation."},{"text":"Small numerical differences during inference can change the ordering of nearly tied token scores.","correct":true}]},"prev":{"slug":"tokens-and-the-context-window","title":"Tokens, language and the context budget","url":"https://addaly.com/learn/building-with-ai/tokens-and-the-context-window"},"next":{"slug":"streaming-and-perceived-speed","title":"Streaming, and the difference between fast and feeling fast","url":"https://addaly.com/learn/building-with-ai/streaming-and-perceived-speed"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Temperature, sampling, and why the same input gives a different answer', in Building with AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/building-with-ai/sampling-and-determinism (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Temperature, sampling, and why the same input gives a different answer","courseTitle":"Building with AI","module":{"index":1,"slug":"the-call-underneath-everything","title":"The call underneath everything"},"answer":null,"keyIdea":"Use the controls supported by the selected model, and evaluate accuracy and reproducibility on representative cases.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"what-the-model-actually-produces","runs":[{"text":"What the model actually produces"}]},{"t":"p","runs":[{"text":"A text-generation system scores possible next tokens and uses a decoding method to select one. Some APIs expose sampling settings. Others manage decoding without exposing those controls. The following is a simplified sampler for a model that supports these settings."}]},{"t":"p","runs":[{"text":"A common sampling pipeline works as follows:"}]},{"t":"ol","start":1,"items":[[{"text":"Divide every logit by the "},{"text":"temperature","b":true},{"text":"."}],[{"text":"Apply softmax to turn the scores into probabilities summing to 1."}],[{"text":"Optionally cut the tail: "},{"text":"top_k","b":true},{"text":" keeps the k highest, "},{"text":"top_p","b":true},{"text":" (nucleus) keeps the smallest set whose probabilities sum to at least p."}],[{"text":"Draw one token at random from what is left."}]]},{"t":"p","runs":[{"text":"Temperature divides before the softmax, so it stretches or flattens the distribution. At "},{"text":"temperature=2","code":true},{"text":" the gaps between candidates shrink and unlikely tokens become reachable. At "},{"text":"temperature=0.1","code":true},{"text":" the top candidate dominates. At exactly 0, most implementations skip sampling and take the argmax."}]},{"t":"p","runs":[{"text":"Temperature changes the relative probabilities in this simplified sampler. It does not establish whether a generated claim is true. Hosted implementations and supported controls vary by model."}]},{"t":"h2","id":"check-which-controls-the-model-supports","runs":[{"text":"Check which controls the model supports"}]},{"t":"p","runs":[{"text":"Claude Sonnet 5.5, used in this chapter’s request examples, rejects "},{"text":"temperature","code":true},{"text":", "},{"text":"top_p","code":true},{"text":" and "},{"text":"top_k","code":true},{"text":". Leave them out of those requests. "},{"text":"Current model controls","href":"https://platform.claude.com/docs/en/models/sonnet-5-5/overview"},{"text":"."}]},{"t":"p","runs":[{"text":"For a model that exposes temperature, compare low settings for a repeatable classification task and higher settings for varied drafts. Treat ranges as experiment settings. Measure task accuracy and output variety separately. A low temperature cannot guarantee factuality or a valid schema."}]},{"t":"p","runs":[{"text":"Change one supported control at a time, record its value and compare results on a fixed test set. This makes the effect easier to interpret."}]},{"t":"h2","id":"temperature-0-is-not-deterministic","runs":[{"text":"Temperature 0 is not deterministic"}]},{"t":"p","runs":[{"text":"For a model that accepts zero temperature, repeated requests can still differ. Numerical computation, serving behavior or a changed model version are possible causes. Different answers alone do not identify the cause."}]},{"t":"p","runs":[{"text":"Floating-point addition is not associative.","b":true},{"text":" Summing a batch of numbers on a GPU in a different order gives a very slightly different result. Two logits that are nearly tied can swap places. One swapped token at position 40 can change the tokens after it, because each token conditions the next. A rounding difference in the twelfth decimal place becomes a different paragraph."}]},{"t":"p","runs":[{"text":"Batching can affect computation.","b":true},{"text":" Some serving systems group concurrent requests. Depending on the kernels and their reproducibility guarantees, changes to batch shape can affect numerical results."}]},{"t":"p","runs":[{"text":"Some mixture-of-experts implementations have capacity-dependent routing.","b":true},{"text":" Such routing may introduce another source of variation. Its relevance depends on the model and serving implementation."}]},{"t":"p","runs":[{"text":"Some providers expose a seed or a serving-version identifier. Follow that provider’s reproducibility contract and log the supported metadata. A seed alone does not establish that every part of inference is deterministic."}]},{"t":"h2","id":"what-to-do-about-it","runs":[{"text":"What to do about it"}]},{"t":"p","runs":[{"text":"Choose checks that match the task. Exact strings can be appropriate for an enumerated label. Structured fields are useful when several phrasings are acceptable."}]},{"t":"p","runs":[{"text":"The following illustrative fixtures compare exact prose matching with checks on selected structured fields. The production test still needs the expected values for its own case."}]},{"t":"code","lang":"python","label":"Python","text":"import json\n\nprose = \"The refund window is 30 days.\"\nassert prose == \"The refund window is 30 days.\"\n\nstructured = '{\"days\": 30, \"currency\": \"INR\"}'\ndata = json.loads(structured)\nassert data[\"days\"] == 30\nassert data[\"currency\"] in {\"INR\", \"USD\"}"},{"t":"p","runs":[{"text":"Three habits follow from that:"}]},{"t":"ul","items":[[{"text":"Where you can, make the model emit "},{"text":"structured output","b":true},{"text":" and assert on the fields. A number in a field is checkable; a sentence is an argument."}],[{"text":"Where you cannot, assert on invariants: it cited at least one source, it did not mention a competitor, it stayed under 200 words, it refused an out-of-scope question."}],[{"text":"To reuse a reviewed answer, cache it under the relevant inputs, prompt version, model version and access scope. Set an expiry or invalidation rule when its source data can change."}]]},{"t":"h2","id":"the-uncomfortable-consequence","runs":[{"text":"The uncomfortable consequence"}]},{"t":"p","runs":[{"text":"A single success or failure is limited evidence. Under an illustrative model of independent attempts with a 95% success probability, four attempts all succeed about 81% of the time. Repeated evaluations on representative cases help estimate performance, and failures reveal cases that need investigation."}]},{"t":"p","runs":[{"text":"This is the reason the evaluation module later in this course exists, and it is why builders who skip it end up debugging by anecdote."}]}],"check":{"question":[{"text":"The model weights, request input and greedy decoding rule are confirmed unchanged. Which numerical mechanism can still change the selected token when scores are nearly tied?"}],"options":[{"text":[{"text":"Some hidden randomness remains in the sampler that temperature 0 does not disable."}],"correct":false,"tempting":[{"text":"Locates the cause in the sampler, when at temperature 0 most implementations take the argmax and do no sampling at all."}]},{"text":[{"text":"The provider silently switched model versions between calls."}],"correct":false,"tempting":[{"text":"The stated setup rules out a model-version change."}]},{"text":[{"text":"The prompt contains ambiguity the model resolves differently each time."}],"correct":false,"tempting":[{"text":"Treats the model as making a fresh interpretive choice, when the same weights and same argmax rule should give the same interpretation."}]},{"text":[{"text":"Small numerical differences during inference can change the ordering of nearly tied token scores."}],"correct":true,"tempting":null}],"order":[2,1,0,3],"why":null},"prev":{"slug":"tokens-and-the-context-window","title":"Tokens, language and the context budget","minutes":10},"next":{"slug":"streaming-and-perceived-speed","title":"Streaming, and the difference between fast and feeling fast","minutes":9}}}