Sampling, temperature and non-determinism

Study time
≈ 2 h (estimate)
Needs
L1-M01-L01
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M01 · Duration: ~120 min (estimate, including the independent exercise; L01 also includes first-time setup) · Previous: L02 · Next: L04 - Anatomy of an LLM application

1. Introduction

In traditional testing, a test that sometimes passes and sometimes fails is a flaky test. We treat it as a defect in the test or in the environment, and we fix it.

With an LLM, output that changes between runs is often intentional design. It comes from sampling. An AI QA Engineer must know when that variation is normal and when it is a defect, and must know how to measure it instead of running once and drawing a conclusion.

2. Learning objectives

  1. Explain how temperature changes the probability distribution of the next token.
  2. Compute probabilities from logits with a temperature-scaled softmax, and compare them with the code's result.
  3. Cite the official documentation showing that real APIs do not guarantee identical output, even when temperature is 0.
  4. Run a repeat-run test and report the number of distinct outputs and the rate of the most common output.
  5. Distinguish acceptable variety from a real defect (for example a change in the sentence's meaning).

3. Prerequisites and tools

  • You have completed L01, especially the part on greedy and sampling (section 5.2).
  • High-school maths: division, percentages. The exponential function eˣ is explained in the lesson itself.

4. Concepts

4.1 Logits and probabilities

At each step, the model gives each candidate token a raw score called a logit. A logit is not yet a probability: it can be negative, and the logits do not add up to 1. The softmax function turns the logits into probabilities that add up to 1.

P(token_i) = e^(logit_i / T)  /  tổng_j e^(logit_j / T)

(In the formula, "tổng_j" means the sum over all candidates j.)

  • e ≈ 2.718. The operation eˣ turns every number into a positive number and amplifies the gaps between numbers.
  • T is the temperature.

Everyday example. A restaurant gives four dishes on its menu a "fits the customer's taste" score: 4.0; 2.5; 2.0; 0.5. That score does not yet say what percentage of customers will pick each dish. Softmax does the conversion: it turns raw scores into percentages that add up to exactly 100%. The top-scoring dish gets most of it, but the others still get a share.

4.2 Temperature

Anthropic's glossary describes temperature as the parameter that controls randomness when generating text. A high temperature gives more varied, more creative output. A low temperature gives more conservative output that sticks to the most probable wording [R1].

An analogy: logits are like the exam scores of candidates.

  • Small T is like a committee that almost always picks the top scorer; low scorers have only a very small chance.
  • Large T is like a lottery in which high scorers hold slightly more tickets, but low scorers still have a chance.
  • At T = 0, many systems (and this lab) pick the top token directly. That is greedy decoding.

Worked example: T = 0.5. The same four logits 4.0; 2.5; 2.0; 0.5 (section 5.1).

  1. Divide by T: 8; 5; 4; 1.
  2. Subtract the largest (8): 0; −3; −4; −7 (section 5.2 explains why).
  3. Take eˣ: 1; 0.0498; 0.0183; 0.0009. Sum ≈ 1.0690.
  4. Divide by the sum: goes ≈ 0.935; went ≈ 0.047; is going ≈ 0.017; go ≈ 0.001.

Compared with T = 1 (goes ≈ 0.72), lowering the temperature to 0.5 pushes "goes" from 72% to about 94%. Check it with the lab (run on 2026-11-06 on Python 3.14.6 and 3.12.3, Linux, identical results; the same holds for the other outputs in this lesson):

python -c "from lab.sampling import *; print({k: round(v, 4) for k, v in softmax(LOGITS, 0.5).items()})"
{'goes': 0.9354, 'went': 0.0466, 'is going': 0.0171, 'go': 0.0009}

The demo in section 8.2 prints the same numbers rounded to 2 digits: goes=0.94 went=0.05.

The range of temperature values differs between providers. For example, OpenAI's Chat Completions documentation states that temperature is between 0 and 2, with a default of 1 [R2]. The same documentation also notes that parameter support can differ by model, especially for newer reasoning models [R2]. Always check the documentation of exactly the API and the model you are testing.

Update 2026-10-31 - the Claude API no longer has this parameter. From API version 2026-10-21, the Claude API has removed temperature, top_p and top_k: a request that sends any of them gets error 400 on every model [R4]. The Python SDK anthropic 2.3.0 sends this version by default and no longer accepts the temperature parameter (tried on 2026-10-31: passing temperature raises TypeError). You can no longer control sampling through parameters, but the output can still differ between calls (section 4.3). Lesson L1-M03-L02 turns this into a test case: the product's client must not send removed parameters.

4.3 Non-determinism: temperature 0 is still not enough

This is the point testers misunderstand most often.

  • Anthropic states: even when temperature is 0, the results are not fully deterministic, and the same input can give different outputs between API calls. This holds both for Anthropic's own service and when calling through a third-party cloud provider [R1].
  • OpenAI has a seed parameter (in Beta) and states explicitly "Determinism is not guaranteed". It recommends watching the system_fingerprint field to know when the backend changes [R2].

Consequence: "Set temperature = 0 and the test will be stable" is a false assumption. You must design tests that tolerate variation, or measure that variation.

Everyday example. A pho shop cooks with the same recipe, the same cook and the same amount of spices. The broth still differs a little every day, because the fire, the bones and the humidity are never exactly the same. "Same recipe" is like "temperature 0": it reduces the differences, but it does not guarantee today's bowl is identical to yesterday's. A quality checker therefore tastes many bowls, not one bowl followed by a conclusion.

4.4 Common misconceptions

Misconception Reality
"Different outputs mean there is a bug." It may be by design. A bug is when the output violates a requirement, for example the wrong meaning or the wrong format.
"At temperature 0 there is no need to run repeatedly." Wrong, as shown in 4.3.
"It passed 3 runs, so the feature is stable." 3 runs are far too few to estimate a defect rate. L1-M06-L02 teaches how to compute a confidence interval.
"A high temperature is always worse." For creative tasks, such as writing varied example sentences for learners, variety can be a requirement.

Good vs bad: a test case for the grammar-correction feature. Written in English because the dev team reads it:

Weak:  Run "She go to school every day" once.
       Expected: reply == "She goes to school every day."

Good:  Run "She go to school every day" 50 times.
       Expected, on every run: valid JSON; "corrected" keeps the present simple ("goes");
       "explanation_vi" is in Vietnamese.
       Report: x/50 runs meet all three rules; list each failing output.

The weak one runs once and demands one exact string, so it can pass by luck and can also fail unfairly when the model words a correct answer differently. The good one runs many times, checks rules on every output and reports a rate.

5. Technical deep dive

5.1 Working through an example by hand

The lab uses 4 candidates with logits made up for illustration. The prompt is: correct the sentence "She go to school".

Candidate Logit
goes 4.0
went 2.5
is going 2.0
go 0.5

At T = 1, the probability of "goes" is e⁴ / (e⁴ + e^2.5 + e² + e^0.5) ≈ 54.6 / (54.6 + 12.18 + 7.39 + 1.65) ≈ 54.6 / 75.8 ≈ 0.72. This number matches the lab's output in section 8.

5.2 Numerical stability

The code subtracts the largest logit from every logit before computing eˣ. The subtraction does not change the result, because the numerator and the denominator are multiplied by the same constant, but it prevents overflow when logits are large. You will see this technique in many libraries.

Worked example. Without subtracting the largest value, e¹⁰⁰⁰ goes beyond what a computer's floating-point numbers can represent:

python -c "import math; print(math.exp(1000))"
OverflowError: math range error
python -c "from lab.sampling import softmax; print(softmax({'a': 1000, 'b': 999}, 1.0))"
{'a': 0.7310585786300049, 'b': 0.2689414213699951}

The lab's softmax subtracts 1000 first, so it only has to compute e⁰ = 1 and e⁻¹ ≈ 0.368, then divide: 1 / 1.368 ≈ 0.731. Everyday example: measure everyone's height in the class relative to the tallest student ("5 cm shorter") instead of from the floor. The ranking and the ratios do not change, but the numbers are small and easy to work with.

5.3 Where non-determinism comes from

  1. Sampling when the temperature is greater than 0. This is intentional randomness.
  2. The infrastructure serving the model: providers confirm that output can change even at temperature 0 [R1][R2]. They do not fully publish the causes in the pages cited, so this lesson does not speculate further.
  3. The model or the backend changes over time. OpenAI recommends watching system_fingerprint [R2]. A new model or a new configuration can also change behaviour. This is the regression topic of L1-M06.

Good vs bad: the log line for each repeated run.

Weak log Good log
run 14: FAIL 2026-11-06 10:42, model id, API version, system_fingerprint (if the API has it), parameters sent, input, exact output, which rule failed

When this week's defect rate differs from last week's, only the good log tells you whether it is sampling, a model change, or a change in the product itself.

6. The QA perspective

  • What to test: the stability of the properties that must be stable, such as the JSON format, the correctness of the corrected sentence, and the answer language. Do not test the exact string of free-form text.
  • Why: a user gets one answer each time. If 3 out of every 10 runs are wrong, about 30% of answers are defective; users who ask many times are even more likely to hit the defect.
  • What can go wrong: a change of meaning (correcting "She go" to "She went" gets the tense wrong); JSON that is sometimes there and sometimes not; answers sometimes in Vietnamese, sometimes in English.
  • Expected behaviour: written as a measurable threshold and agreed with the product owner. For example: "Over 50 runs, 100% of outputs are valid JSON, and at least 95% keep the tense of the original sentence." The numbers here are examples, not an industry standard.
  • How to detect: run N times with the same input, count the distinct outputs, measure the rate of the most common output (mode rate), and check each output against the rules.
  • How to report: "The defect occurred 7/20 times (35%), model X, temperature 1.0 (if the API has this parameter), date Y", with an example of a correct output and a wrong output. Do not write "fails occasionally".

Worked example: more runs bring the rate closer to the probability. In section 8.2, 20 runs gave "went" 35%, while the theoretical probability is 16%. Run 100 times with the same seed:

python -c "from lab.sampling import *; c = repeat_run(LOGITS, 1.0, runs=100, seed=2026); print(dict(c.most_common()))"
{'goes': 73, 'went': 14, 'is going': 10, 'go': 3}
Candidate Probability (T = 1.0) 20 runs (section 8.2) 100 runs
goes 0.72 13 (65%) 73 (73%)
went 0.16 7 (35%) 14 (14%)
is going 0.10 0 10 (10%)
go 0.02 0 3 (3%)

With 100 runs every rate sits close to its probability, and two more wrong outputs appear ("is going" changes the meaning, "go" is still ungrammatical). With 20 runs you would not even know these two outputs exist.

7. Real-world scenarios

Scenario 1 - Grammar correction (fictional, using the lab's numbers). At T = 1.0, out of 20 runs the toy model returned "went" 7 times. "Went" fixes the grammar error but changes the tense of the sentence, which means the meaning is wrong. Going by the toy model's theoretical probability (P(went) ≈ 0.16), a single run has about an 84% chance of not showing this defect. Lesson: for features that need accuracy, measure over many runs, and make recommendations (for example lowering the temperature, if the API still supports that parameter; the Claude API does not, see section 4.2) backed by numbers.

Scenario 2 - An email-drafting assistant for customer service (fictional). The product team wants varied greetings so that emails do not all look the same. A test that "every output is identical" contradicts the requirement here. The right test is: every output is polite, uses the customer's correct name, promises nothing the policy does not allow, and does show variety (the number of distinct greetings > 1 over 20 runs).

8. Hands-on tutorial

8.1 Reading the code

lab/sampling.py:

def softmax(logits, temperature):
    if temperature < 0:
        raise ValueError("temperature must be >= 0")
    if temperature == 0:
        top = max(sorted(logits), key=lambda k: logits[k])
        return {k: (1.0 if k == top else 0.0) for k in logits}
    scaled = {k: v / temperature for k, v in logits.items()}
    peak = max(scaled.values())  # subtract the max for numerical stability
    exps = {k: math.exp(v - peak) for k, v in scaled.items()}
    total = sum(exps.values())
    return {k: e / total for k, e in exps.items()}
  • {k: ... for k in logits} is a compact way to build a new dict (a key → value table) from an old one.
  • T = 0 is handled separately (greedy), because you cannot divide by 0. max(..., key=...) picks the candidate with the largest logit.
  • repeat_run(logits, temperature, runs, seed) draws runs samples with a seeded random number generator, then counts the results.
  • consistency(outputs) returns the number of runs, the number of distinct outputs, the most common output and its rate. These are the numbers a tester needs to put into a report.

8.2 Running the demo

python -m lab.sampling

Actual output (2026-10-31):

T=0    goes=1.00  went=0.00  is going=0.00  go=0.00
T=0.5  goes=0.94  went=0.05  is going=0.02  go=0.00
T=1.0  goes=0.72  went=0.16  is going=0.10  go=0.02
T=1.5  goes=0.58  went=0.21  is going=0.15  go=0.06

T=0    20 runs: {'goes': 20}
         {'runs': 20, 'distinct': 1, 'mode': 'goes', 'mode_rate': 1.0}
T=1.0  20 runs: {'goes': 13, 'went': 7}
         {'runs': 20, 'distinct': 2, 'mode': 'goes', 'mode_rate': 0.65}

Reading the result:

  • The higher the temperature, the more evenly the probability is spread. At T = 1.5, "go" (still ungrammatical) has a 6% chance.
  • 20 runs at T = 1.0 give 13 "goes" and 7 "went". The observed rate of "went" is 35%, higher than the theoretical probability of 16%. With a small number of runs, the observed rate fluctuates strongly. This is why lesson L1-M06-L02 teaches how to compute confidence intervals.
  • "is going" also fixes the grammar and keeps the present tense, but it carries a different meaning (in progress). There are several acceptable answers, so the expected result must be a rule, not a string.

8.3 Running the tests

python -m pytest tests/test_sampling.py -v

Expected result: 10 tests pass. test_probabilities_sum_to_one is parametrised with 4 temperature values, so it counts as 4 tests.

@pytest.mark.parametrize("temperature", [0, 0.5, 1.0, 1.5])
def test_probabilities_sum_to_one(temperature):
    assert sum(softmax(LOGITS, temperature).values()) == pytest.approx(1.0)

@pytest.mark.parametrize runs the same test with several data sets [R3]. You will use it to run many test scenarios in lesson L05.

8.4 Important note

test_same_seed_reproduces_the_toy_exactly holds only for the toy model, because the random number generator is entirely in our hands. With a real API, do not write tests that assume the same seed gives the same output [R2].

8.5 Troubleshooting

Symptom Cause Fix
Your counts differ from the lesson You changed seed or runs Use seed=2026 and runs=20 to match the lesson
ValueError: temperature must be >= 0 A negative temperature was passed This is the correct behaviour; see the corresponding test

9. Independent exercise

Problem: The product team wants a quality gate: the feature may only be released if the most common output accounts for at least 90% of the runs.

Requirements:

Copy the starter file exercises/test_l03_gate.py into tests/ and fill in the TODO places.

  1. Write the function stability_gate(outputs, min_mode_rate) reusing consistency(). It returns the dict of consistency() plus a verdict key whose value is "PASS" or "FAIL".
  2. Run repeat_run(LOGITS, 0.7, runs=100, seed=2026), feed the result into the gate with a threshold of 0.9, and record the verdict.
  3. Write tests for both the PASS case (T = 0) and the FAIL case.
  4. Write 3-5 sentences: is a 90% threshold suitable for a grammar-correction feature? Which kind of defect does a gate based on "mode rate" miss?

Test data: LOGITS in lab/sampling.py; repeat_run(LOGITS, 0.7, runs=100, seed=2026) and repeat_run(LOGITS, 0, runs=100, seed=2026).

Deliverable: tests/test_l03_gate.py, a short report (number of runs, mode, mode_rate, verdict) and the commentary.

Acceptance criteria: the tests pass; the report has the number of runs, mode, mode_rate and verdict; the commentary points out at least one limitation of the gate.

Hint: list(counter.elements()) turns a Counter into a list of outputs.

9.1 Extra exercise: measure a rule pass rate, not the mode rate (15-20 minutes)

Problem: the gate in the exercise above uses the mode rate, so a model that is stable but wrong (always "went") still PASSES. You write a second measure: the share of outputs that meet the rule.

Requirements:

  1. Copy exercises/test_l03_extra_rule_rate.py into tests/ and run it once: 5 tests fail with TODO.
  2. Write rule_pass_rate(outputs, acceptable): the share of outputs that are in the set acceptable, raising ValueError for an empty list (no runs means no evidence). Do not use consistency().
  3. At TODO 2, read the T = 1.0, 20-run counts in section 8.2, compute the pass rate by hand and fill in expected.

Acceptance criteria: 5 passed. You can explain why test_stable_but_wrong_is_zero gives 0.0 while the mode rate of the same data is 1.0.

Hint: sum(1 for out in outputs if out in acceptable) / len(outputs).

9.2 Real-world scenario: two features, two kinds of "stable" (fictional)

Context. The fictional marketplace ChoPho has two LLM features: (A) suggest 5 product titles to a seller from a short description; (B) read a photo of a bank-transfer receipt and extract the amount and the date to credit the seller's wallet. The product owner asks: "Can we test the stability of these two features the same way?"

Task: write a half-page decision note for the product owner.

A good answer has:

  • For (A), says that variety is a requirement: the test does not demand identical outputs; it demands that every title meets the rules (length, no banned words, right language) and that there are at least 2 different titles over N runs
  • For (B), says that the amount and the date must be correct on every run, checked with a reference answer on a set of receipts whose values are known
  • A concrete number of runs and threshold for each feature, labelled as a proposal to agree on, not an industry standard
  • A reminder that temperature 0 (if the API still has the parameter) does not guarantee identical outputs
  • How to report: rate x/N, examples of wrong outputs, model and run date
  • Names the biggest risk of (B) (money credited wrongly to the wallet) and proposes a safeguard beyond testing, for example the seller confirms the amount before it is credited

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

According to Anthropic's documentation, setting temperature = 0 guarantees identical output on every API call.

P03 · Short answer

Out of 40 runs, 34 give the same output. What is the mode rate? With a threshold of 0.9, what does the gate return?

P05 · Short answer

An LLM test in CI fails 1 time out of 10 runs. A developer suggests "rerun until it passes". How do you respond?

P06 · Fill in the blank

The ___ function turns logits into probabilities that add up to ___.

P07 · Multiple choice

The demo python -m lab.sampling prints: T=1.0 20 runs: {'goes': 13, 'went': 7}. What is the mode rate?

P08 · True or false

In the 20 runs at T = 1.0, the observed rate of "went" equals the theoretical probability of "went".

P09 · Spot the bug

The softmax function below was copied from lab/sampling.py but has one defect. Find it.

def softmax(logits, temperature):
    if temperature < 0:
        raise ValueError("temperature must be >= 0")
    if temperature == 0:
        top = max(sorted(logits), key=lambda k: logits[k])
        return {k: (1.0 if k == top else 0.0) for k in logits}
    scaled = {k: v * temperature for k, v in logits.items()}
    peak = max(scaled.values())  # subtract the max for numerical stability
    exps = {k: math.exp(v - peak) for k, v in scaled.items()}
    total = sum(exps.values())
    return {k: e / total for k, e in exps.items()}

P10 · Select all that apply

According to §5.3, what are the sources of non-determinism? Select all that apply.

P11 · Put in order

Put in order the steps the lab's softmax function performs when the temperature is greater than 0.

  1. Divide each logit by the temperature
  2. Divide each value by the total
  3. Compute e to the power of each value
  4. Subtract the largest value from every value

P12 · Multiple choice

Scenario 2 in §7: the product team wants varied greetings in customer-service emails. Which test matches the requirement?

P13 · Recall

Lesson: L1-M01-L01

Lesson L01: which way of choosing the next word always takes the word with the highest probability, so that the same input gives the same output?

P15 · Multiple choice

The worked example in §4.2 computes softmax at T = 0.5 for the four logits 4.0; 2.5; 2.0; 0.5. After step 1 (divide by T) and step 2 (subtract the largest), the four numbers are:

P16 · True or false

At T = 1.0 with seed 2026, 100 runs give "went" 14 times (14%), closer to the theoretical probability of 16% than 20 runs (7 times, 35%).

P17 · Match

Match each number in a repeat-run report with its meaning (§8.1, §9.1).

P18 · Spot the bug

The function below is a wrong solution to the extra exercise §9.1. Find the defect.

def rule_pass_rate(outputs, acceptable):
    if not outputs:
        raise ValueError("no runs: cannot compute a pass rate")
    return consistency(outputs)["mode_rate"]

P19 · Select all that apply

About subtracting the largest logit in §5.2, which statements are true? Select all that apply.

P20 · Apply now

In code-labs/l1-m01, copy exercises/test_l03_extra_rule_rate.py into tests/, run python -m pytest tests/test_l03_extra_rule_rate.py once before changing anything, then do the extra exercise in §9.1 and run it again.

Checklist

11. Summary

  • Concepts: logit, softmax, temperature, greedy, sampling. Non-determinism comes from both sampling and infrastructure, and temperature 0 does not guarantee identical output on a real API.
  • Skills: compute probabilities; run a repeat-run; report distinct, mode and mode_rate; design a quality gate.
  • Traps: running once and drawing a conclusion; using a fixed string as the expected result; equating "variety" with "defect"; "rerunning until it passes".
  • You can now: measure the stability of an LLM feature and report it with numbers.

12. References

ID Title Publisher URL Accessed Relevance
R1 Glossary (Temperature) Anthropic https://platform.claude.com/docs/en/about-claude/glossary 2026-10-31 Definition of temperature; non-determinism at temperature 0
R2 Chat Completions - Create (API reference) OpenAI https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create 2026-10-31 Temperature range 0-2, default 1; seed (Beta), "Determinism is not guaranteed", system_fingerprint
R3 How to parametrize fixtures and test functions pytest https://docs.pytest.org/en/stable/how-to/parametrize.html 2026-10-31 @pytest.mark.parametrize
R4 Versions (API version 2026-10-21) Anthropic https://platform.claude.com/docs/en/api/versioning 2026-10-31 temperature, top_p, top_k removed, error 400 on every model

Version note: sampling parameters and the determinism policy change by provider and model. Last reviewed: 2026-10-31.

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Logit Điểm số thô của token trước khi chuyển thành xác suất
Softmax Hàm chuyển điểm số thành xác suất có tổng bằng 1
Temperature Tham số điều chỉnh độ ngẫu nhiên
Non-determinism Cùng input nhưng output có thể khác nhau
Repeat-run test Chạy lặp cùng một input để đo độ ổn định
Mode rate Tỷ lệ của output xuất hiện nhiều nhất
Quality gate Điều kiện phải đạt trước khi release
Flaky test Test lúc pass lúc fail mà không có thay đổi