Where non-determinism comes from

Study time
≈ 2.5 h (estimate)
Needs
L1-M01-L03, L1-M05-L05
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-M06 · Duration: ~150 min (estimate, including the independent exercise) · Previous: L1-M05-L05 · Next: L02 - Repeat-run testing and pass rates

1. Introduction

In L1-M01-L03 you saw that the same input can give different outputs. This module turns that observation into a testing method: run repeatedly, measure the pass rate, compare two versions, and triage when something changes.

The first lesson answers a question that every later step depends on: why does the output change? There are at least three sources, and each needs a different treatment in a test. Confusing them leads to two typical mistakes: reporting a "regression" for a normal fluctuation, or ignoring a real regression because you think "it's just randomness".

2. Learning objectives

  1. Distinguish three sources of variation: sampling, the serving infrastructure, and a change of model or prompt.
  2. Explain what a pinned model ID guarantees and what it does not, according to Anthropic's documentation.
  3. Run the same question many times and read the distribution of the answers.
  4. Distinguish a change in wording from a change in quality.
  5. Record enough configuration for a result to be comparable later.

3. Prerequisites and tools

  • L1-M01-L03: sampling, temperature, and why temperature 0 is still not enough.
  • L1-M04-L01: property-based oracles.
  • The code lab code-labs/l1-m06, installed as described in its README. Only pytest is needed.

4. Concepts

4.1 Source 1: sampling

The model chooses the next token by sampling from a probability distribution (L1-M01-L03). This randomness is intentional. From API version 2026-10-21, the Claude API no longer accepts temperature, top_p, top_k (it returns error 400) [R1]. You no longer control sampling with parameters, but the output can still differ between calls.

Everyday example. You order an iced milk coffee at the same café, from the same barista, every morning. Today it is a little sweeter, tomorrow a little stronger, but it is still the café's milk coffee. The barista is not doing it wrong: making drinks by hand always varies a little. Sampling is the same. Variation is part of how the model works, not a sign that something is broken.

4.2 Source 2: the serving infrastructure

Even when the model and the parameters stay the same, the output can still change. Anthropic's glossary says: "Even with temperature set to 0, the results will not be fully deterministic, and identical inputs might produce different outputs across API calls" [R2]. The page on model IDs is even more explicit: "infrastructure updates produce minor differences in observable behavior even when the model ID and weights have not changed" [R3].

A study by Thinking Machines Lab (2025) explains one cause: the load on the system changes, so the batch size changes, and the model's computation "lacks 'batch invariance'". In their experiment, 1000 generations at temperature 0 gave 80 different answers [R4]. This is a result on their system, not a figure from a specific provider, but it shows why "temperature 0 is stable" is a false assumption.

A "batch" is a group of requests that the server processes together. When traffic is low, your request may travel alone; when it is busy, it travels with many others, and the order of the computations inside changes with it.

Everyday example. A phở shop cooks to exactly one recipe, but at peak hours it uses the big pot and at quiet hours the small one. The bowls are nearly identical, yet now and then a regular says "the broth tastes a bit different today". Nobody changed the recipe; only the way of cooking for the crowd changed.

Good vs bad.

Weak assumption Good assumption
Thinking "Greedy or temperature 0 always gives the same output, so one run is enough" "Greedy still varies a little (demo §8.1: 99 out of 100 runs, not 100 out of 100), so run it repeatedly and measure a rate"
Consequence A rare deviation is reported as a bug, or ignored without anyone measuring it The deviation is counted, and becomes a problem only when its rate crosses a threshold (L02)

4.3 Source 3: a change of model or prompt

  • Your prompt or code changes. This is a change you control, and it is the main reason to run regression tests (L04).
  • The model changes. According to the documentation, "Each Claude model ID identifies a pinned version of the model", "the underlying model remains constant for the lifetime of that ID. This guarantee covers model IDs, not the convenience aliases", and for models from the 4.6 generation onward, an ID without a date "maps to a single, fixed model snapshot" [R3]. The same page also states which part can change: "the serving infrastructure around the model can change over time" [R3]. An old-style alias such as claude-sonnet-4-5 "resolves to the most recent dated snapshot for that minor version" [R3], which means it can point to a new snapshot.
  • The model is retired. The deprecations page says that once a model is retired, "Requests to retired models fail", and recommends "thorough testing of your applications with the new models well before the retirement date" [R1].

Consequences for a tester: record the model ID in every test result; know that a pinned model ID still has small fluctuations caused by the infrastructure; and treat a model change as a change that needs a regression test, just like a prompt change.

Everyday example. A pinned model ID is like a book that says "3rd edition" on the cover: the content does not change. An old-style alias is like asking for "the latest edition": today that is the 3rd, next month it may be the 4th. The infrastructure is like the printing house: the same edition printed in another plant may have slightly different ink.

Good vs bad. The same result, recorded two ways:

Weak record Good record
Line Q-REFUND: 95% pass Q-REFUND: 95/100 pass, faq-v1@sim-2026-09/sample, seed 7, 2026-11-06 (with a real API: the model ID returned in the response, the prompt version, the commit, the time of the run)
Why Next month nobody knows which prompt, which model or how many runs produced this number It can be compared with the next run, and you see at once which part of the configuration changed

4.4 A change in wording is not a change in quality

The two sentences "Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng" and "Thời hạn đổi trả là 30 ngày, tính từ khi nhận hàng" (both say that returns are accepted within the return window, counted from the day the goods are received; they are the lab's answers, quoted verbatim) differ in their words but are both correct. A test that compares strings reports a "change"; a property-based test (L1-M04-L01) does not. That is why this module measures the pass rate of a property-based oracle, not the rate of string matches.

Worked example. Run Q-REFUND 20 times on the old snapshot and 20 times on the new one, and grade every answer with the case's oracle. Save the following as try_l01.py in the lab folder, run python try_l01.py, then delete the file:

from collections import Counter

from lab import dataset, oracles
from lab.simulated_model import SimulatedFAQModel

case = next(c for c in dataset.load() if c["id"] == "Q-REFUND")
for snapshot in ("sim-2026-09", "sim-2026-10"):
    model = SimulatedFAQModel(model_snapshot=snapshot)
    texts = [model.answer("Q-REFUND", seed=7, run=r).text for r in range(20)]
    passes = sum(not oracles.check(t, case["oracle"]) for t in texts)
    print(f"{snapshot}: {len(Counter(texts))} distinct answers, {passes}/20 pass the oracle")
    for text, k in Counter(texts).most_common():
        verdict = "pass" if not oracles.check(text, case["oracle"]) else "FAIL"
        print(f"  {k:2}  {verdict}  {text}")

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions gave identical output):

sim-2026-09: 3 distinct answers, 19/20 pass the oracle
  14  pass  Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng.
   5  pass  Thời hạn đổi trả là 30 ngày, tính từ khi nhận hàng.
   1  FAIL  Bạn được đổi trả trong 30 ngày.
sim-2026-10: 3 distinct answers, 19/20 pass the oracle
  11  pass  Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng.
   8  pass  Thời hạn đổi trả là 30 ngày, tính từ khi nhận hàng.
   1  FAIL  Bạn được đổi trả trong 30 ngày.

Step by step:

  1. Compare strings: the most common answer appears 14 times on the old snapshot and 11 times on the new one; the second answer 5 and 8 times. A string-comparison test reports "changed".
  2. Compare with the oracle: both sides pass 19/20. The only failing answer is the one without "kể từ ngày nhận hàng" (counted from the day of receipt), and it appears on both sides.
  3. Conclusion: the wording changed, the quality according to the oracle did not. 20 runs are few; L02 tells you how sure that number is. Demo §8.1 runs 100 times and reaches the same conclusion.

Good vs bad.

Weak test Good test
Check assert reply.text == "Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng." after one call assert oracles.check(reply.text, case["oracle"]) == [] for every run, then count the passes
On the 20 runs above Fails 6/20 times on the old snapshot and 9/20 on the new one, although 5 and 8 of those are correct answers 19/20 on both sides; only the answer that really misses a fact fails

5. Technical deep dive

5.1 The simulation in the lab

SimulatedFAQModel(prompt_version, model_snapshot, mode) is a table of weighted answers (see the docstring of lab/simulated_model.py):

Source In the simulation
Sampling mode="sample": each call picks an answer according to the weights
Infrastructure mode="greedy": always picks the answer with the largest weight, except for a small probability of serving another answer
Change Each pair (prompt_version, model_snapshot) has its own weight table

Each call receives a seed and a run. The same configuration, question, seed and run always give the same answer. This is a property of the simulation, so that the lesson can be reproduced. A real API does not behave like this.

5.2 The Python you need for this lesson

  • collections.Counter(iterable) counts occurrences; .most_common() sorts from most to least frequent.
  • random.Random("chuỗi seed") (a seed string) creates a separate random number generator. The Python documentation: "By reusing a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running" [R5].

6. The QA perspective

Source How to handle it in a test What to record in the result
Sampling Run repeatedly, measure the rate (L02) Number of runs
Infrastructure As for sampling; do not assume "greedy is stable" Time of the run
Prompt/code Regression test between two versions (L04) Prompt version, commit
Model Regression test before changing the model; follow the retirement schedule Exact model ID
  • What can go wrong: running once and drawing a conclusion; using an alias without recording the real snapshot; comparing strings instead of properties; not recording the configuration, so nothing can be compared later.

7. Real-world scenarios

Scenario 1 (fictional): "it passes on my machine". A chatbot test passes when the developer runs it and fails on CI in the evening. No code has changed. The cause: the test runs once and expects a fixed string. The real pass rate of the case is about 80%. The fix is not "rerun until it is green" but measuring the rate and setting a threshold (L02).

Scenario 2 (fictional): an alias changes snapshot. A team uses an old-style alias. The provider points the alias to a new snapshot, and the answers start getting longer. Nobody changed any code, but the length tests start failing. Because the old results did not record the real snapshot, the team needs two days to find the cause. Lesson: record the real model ID returned in the response.

8. Hands-on tutorial

8.1 Running the demo

cd academy-content/code-labs/l1-m06
python -m lab.demo l01

Output (copied from a real run, 2026-10-31):

sample mode, faq-v1@sim-2026-09: 3 distinct answers in 100 runs
   62  Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng.
   33  Thời hạn đổi trả là 30 ngày, tính từ khi nhận hàng.
    5  Bạn được đổi trả trong 30 ngày.
greedy mode, faq-v1@sim-2026-09: 2 distinct answers in 100 runs
   99  Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng.
    1  Thời hạn đổi trả là 30 ngày, tính từ khi nhận hàng.
sample mode, faq-v1@sim-2026-10 (new snapshot): 3 distinct answers in 100 runs
   47  Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng.
   46  Thời hạn đổi trả là 30 ngày, tính từ khi nhận hàng.
    7  Bạn được đổi trả trong 30 ngày.
same seed and run twice -> True

In English: the first two answers say that returns are accepted within the return window counted from the day the goods are received; the third answer gives the window but leaves out where it starts.

Reading the output:

  • Sample mode: three answers; the first two are both correct, the third lacks "kể từ ngày nhận hàng" (from the day the goods are received).
  • Greedy mode: 99 out of 100 runs give the same answer, but not 100 out of 100.
  • New snapshot: the split between the two correct answers changes to almost even. The wording changes; the quality hardly changes.
  • The last line: in the simulation, the same seed and run always give the same answer.

8.2 Running the tests

python -m pytest tests/test_l01_sources.py -v

Read test_a_snapshot_change_shifts_wording_without_changing_the_pass_rate: it asserts both things at once, the wording has changed and the pass rate has not changed.

8.3 Troubleshooting

Symptom Cause Fix
ValueError: unknown configuration Wrong version or snapshot name The error message lists the available configurations
Results differ from the lesson A different seed or number of runs Use exactly the seed and range(...) of the lesson

9. Independent exercise

Problem: Measure the "infrastructure noise" and classify five situations.

Requirements: complete exercises/test_l01_sources.py:

  1. TODO 1: run Q-SHIP 2000 times in greedy mode (seed 11), count the answers that differ from the most common answer, and assert that the rate lies between 0.01 and 0.06.
  2. TODO 2: assign a source (sampling, infrastructure, model_change, prompt_change) to each situation:
    • S1: the same prompt and the same model ID, called 10 times in a row, give 3 different answers.
    • S2: a "greedy" system gives the same answer 999 times and another answer 1 time, at peak hours.
    • S3: after switching from claude-sonnet-5 to claude-sonnet-5-5, the answers are longer.
    • S4: after adding one sentence to the system prompt, the model starts answering in English.
    • S5: the same model ID and the same prompt give results this month that differ slightly from last month, although nobody changed anything.
  3. For S5, quote a sentence from the documentation (section 4.2) as the explanation.

Deliverable: the completed test file and the explanation sentence for S5.

Acceptance criteria: the test file passes; each choice has a one-sentence reason (written in a comment).

Hint: counts.most_common(1)[0][1] is the count of the most common answer.

9.1 Extra exercise: a change of wording or a change of quality?

Time: 15-30 minutes. File: exercises/test_l01_extra_change_kind.py.

Problem: After every prompt or snapshot change, a tester must be able to answer: did the answers only change how they say things, or did their quality change too? A string comparison calls every new wording a "change"; a pass-rate comparison alone cannot see that the wording moved at all.

Requirements:

  1. Run python -m pytest exercises/test_l01_extra_change_kind.py. Untouched, 5 tests fail with a message starting with Failed: TODO.
  2. Write pass_rate(model, case): the oracle's pass rate over the valid runs, that is, with timeouts left out of the denominator (L02 section 4.1 explains why).
  3. Write kind_of_change(old_model, new_model, case): return "same", "wording" or "quality" as the docstring says.
  4. Run again until you get 5 passed. Write one sentence: if you compared only the two answer_mix results, how would the Q-REFUND example be classified wrongly?

Acceptance criteria: 5 tests pass; the answer to step 4 says that the wording changed while the pass rate stayed almost the same.

Hint: oracles.check(text, case["oracle"]) returns an empty list when the answer passes, and not [] is True. Two Counter objects can be compared with ==.

9.2 Real-world scenario: a bank's interest-rate chatbot (fictional)

An Phu Bank (fictional) has a chatbot that answers questions about savings interest rates by calling a model through an API. Over one week, the customer-care team sends you five observations:

  • O1: asking "what is the interest rate for a 6-month term?" 5 times in one minute gives 3 different wordings; all three say 4.5% per year.
  • O2: on Monday morning, the content team added the sentence "Always remind the customer to read the terms" to the system prompt; since then the answers are almost twice as long.
  • O3: the configuration calls the model through an old-style alias. Since Wednesday the answers have started to use bullet points, although nobody changed the code or the prompt.
  • O4: in the "most stable" mode the provider allows, about 1 in 500 answers is worded differently.
  • O5: a customer sends a screenshot of an answer saying the 6-month term pays 5.5% per year; the official rate table says 4.5% per year.

Your task (30-45 minutes):

  1. For each observation, write down the source of variation (§4.1-§4.3) and how a test handles it (table §6).
  2. Say which observations are only a change of wording and which may be a quality defect (§4.4).
  3. Write a template (the fields) for recording a test result so that it can be compared next month.
  4. Write 3-5 sentences to the product owner about O5: is it a bug yet, what do you measure next, and how much information do you need to conclude.

A good answer has:

  • Each observation has a source and a reason based on §4, not just a label
  • A clear split between observations that only change the wording and those that touch a property that must hold
  • A result template complete enough to compare two runs one month apart
  • A note to the product owner with a concrete measurement, and no conclusion drawn from one screenshot
  • No suggestion of the "re-run until it is right" kind

10. Knowledge check

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

P02 · True or false

If the model ID and the prompt do not change, the API's output will be identical between calls.

P03 · Short answer

Why does this module measure the pass rate of a property-based oracle instead of the rate of string matches?

P04 · Short answer

Name three pieces of information that must be recorded with every test result so that it can be compared later.

P05 · Short answer

(Scenario) A test fails once on CI and then passes when it is rerun. A colleague proposes "automatically rerun up to 3 times". How do you answer?

P06 · Match

Following the table in §5.1, match each source of variation with how the lab simulates it.

P08 · Multiple choice

In the demo in §8.1, the block sample mode, faq-v1@sim-2026-10 (new snapshot) gives 47, 46 and 7 runs, while the old snapshot gives 62, 33 and 5. Which conclusion is the most accurate?

P09 · Spot the bug

The excerpt below is copied from SimulatedFAQModel.answer() in lab/simulated_model.py, with one line modified. Find the bug.

    def answer(self, question_id, seed=0, run=0):
        if question_id not in self._table:
            raise KeyError(f"unknown question {question_id!r}")
        rng = random.Random(f"{self.prompt_version}|{self.model_snapshot}|{self.mode}|{question_id}|{seed}")
        if rng.random() < self._error_rate:
            return Reply("", self.config, error="timeout")
        variants = self._table[question_id]
        if self.mode == "greedy":
            ranked = sorted(variants, key=lambda v: -v[1])
            pick = ranked[1] if len(ranked) > 1 and rng.random() < INFRA_FLIP else ranked[0]
            return Reply(pick[0], self.config)
        texts, weights = zip(*variants)
        return Reply(rng.choices(texts, weights=weights)[0], self.config)

P10 · Recall

Lesson: L1-M05-L05

L1-M05-L05 §4.1 separates two questions. Which question needs a real model, repeated runs and a measured rate?

P11 · True or false

From API version 2026-10-21, sending temperature: 0 is a way to make Claude's output more stable.

P13 · Multiple choice

In the worked example of §4.4 (20 runs of Q-REFUND per snapshot), how many times does the weak test assert reply.text == "Bạn được đổi trả trong 30 ngày kể từ ngày nhận hàng." fail on the new snapshot?

P14 · True or false

In the worked example of §4.4, the Q-REFUND oracle gives the same result, 19/20 passes, on the old and on the new snapshot.

P15 · Apply now

In code-labs/l1-m06, do the extra exercise of §9.1 in exercises/test_l01_extra_change_kind.py, then run python -m pytest exercises/test_l01_extra_change_kind.py.

Checklist

P16 · Select all that apply

According to the Good vs bad table of §4.3, what does a good test-result line for Q-REFUND contain? Select every correct option.

P17 · True or false

In demo §8.1, greedy mode gives 2 different answers in 100 runs, although the simulation always picks the answer with the largest weight, except with a small probability.

11. Summary

  • Concepts: three sources of variation; a model ID is a pinned snapshot, but the infrastructure still causes fluctuations; an old-style alias can change snapshot; when a model is retired, requests fail; wording is not quality.
  • Skills: running repeatedly and reading the distribution; classifying sources of variation; recording the configuration.
  • Pitfalls: running once; believing that "greedy" or "temperature 0" is stable; comparing strings; not recording the model ID.
  • You can now: explain where an unstable result comes from, before deciding whether it is a bug.

12. References

ID Title Publisher URL Accessed Relevance
R1 Model deprecations Anthropic https://platform.claude.com/docs/en/about-claude/model-deprecations 2026-10-31 temperature/top_p/top_k removed in 2026-10-21; retired models; testing before retirement
R2 Glossary Anthropic https://platform.claude.com/docs/en/about-claude/glossary 2026-10-31 Temperature 0 is not fully deterministic
R3 Model IDs and versioning Anthropic https://platform.claude.com/docs/en/about-claude/models/model-ids-and-versions 2026-10-31 Pinned versions, aliases, fluctuations caused by the infrastructure
R4 Defeating Nondeterminism in LLM Inference (Horace He and Thinking Machines Lab), 2025 Thinking Machines Lab https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/ 2026-10-31 Batch invariance; 80 different answers in 1000 runs at temperature 0
R5 random - Generate pseudo-random numbers Python Software Foundation https://docs.python.org/3/library/random.html 2026-10-31 A seed reproduces the sequence of numbers

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Non-determinism Tính không xác định (cùng input, output khác)
Snapshot / alias Phiên bản model cố định / tên trỏ tới một phiên bản
Serving infrastructure Hạ tầng phục vụ model
Batch invariance Kết quả không phụ thuộc kích thước batch
Deprecation / retirement Ngừng khuyến nghị / ngừng hoạt động